feat: accept API keys from settings
This commit is contained in:
parent
82da016441
commit
6145695980
2 changed files with 40 additions and 3 deletions
|
@ -1,6 +1,10 @@
|
|||
debug = true
|
||||
source_code = "https://git.batsense.net/librepages/conductor"
|
||||
conductor = "dummy"
|
||||
api_keys = [
|
||||
# CHANGE THIS!!
|
||||
{ username = "librepages_api", password="longrandomlygeneratedpassword"}
|
||||
]
|
||||
|
||||
[server]
|
||||
# Please set a unique value, your mCaptcha instance's security depends on this being
|
||||
|
|
|
@ -52,9 +52,16 @@ pub enum ConductorType {
|
|||
Dummy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Creds {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Settings {
|
||||
pub debug: bool,
|
||||
pub api_keys: Vec<Creds>,
|
||||
pub server: Server,
|
||||
pub source_code: String,
|
||||
pub conductor: ConductorType,
|
||||
|
@ -62,6 +69,12 @@ pub struct Settings {
|
|||
|
||||
#[cfg(not(tarpaulin_include))]
|
||||
impl Settings {
|
||||
pub fn authenticate(&self, username: &str, password: &str) -> bool {
|
||||
self.api_keys
|
||||
.iter()
|
||||
.any(|c| c.username == username && c.password == password)
|
||||
}
|
||||
|
||||
pub fn new() -> Result<Self, ConfigError> {
|
||||
let mut s = Config::new();
|
||||
|
||||
|
@ -107,9 +120,8 @@ fn set_separator_field(s: &mut Config) {
|
|||
fn from_env(s: &mut Config, env_name: &str, config_name: &str) {
|
||||
if let Ok(val) = env::var(env_name) {
|
||||
info!("Overriding {config_name} with data from env var {env_name}");
|
||||
s.set(config_name, val).unwrap_or_else(|_| panic!(
|
||||
"Couldn't set {config_name} from env var {env_name}"
|
||||
));
|
||||
s.set(config_name, val)
|
||||
.unwrap_or_else(|_| panic!("Couldn't set {config_name} from env var {env_name}"));
|
||||
}
|
||||
}
|
||||
from_env(s, &format!("{PREFIX}{SEPARATOR}SOURCE_CODE"), "source_code");
|
||||
|
@ -133,3 +145,24 @@ fn check_url(s: &Config) {
|
|||
|
||||
Url::parse(&url).expect("Please enter a URL for source_code in settings");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn creds_works() {
|
||||
let settings = Settings::new().unwrap();
|
||||
let mut creds = settings.api_keys.get(0).unwrap().clone();
|
||||
|
||||
assert!(settings.authenticate(&creds.username, &creds.password));
|
||||
|
||||
creds.username = "noexist".into();
|
||||
assert!(!settings.authenticate(&creds.username, &creds.password));
|
||||
|
||||
let mut creds = settings.api_keys.get(0).unwrap().clone();
|
||||
|
||||
creds.password = "noexist".into();
|
||||
assert!(!settings.authenticate(&creds.username, &creds.password));
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue