diff --git a/config/default.toml b/config/default.toml index 303de8a..6a55023 100644 --- a/config/default.toml +++ b/config/default.toml @@ -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 diff --git a/src/settings.rs b/src/settings.rs index 0dd19db..d37c2ca 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -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, 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 { 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)); + } +}