Skip to content
1        10        20        30        40        50        60        70        80        901use actix_web::{cookie::Key, http::header::HeaderValue};23pub const DEFAULT_CACHE_CONTROL: &str = "public, max-age=31536000, immutable";45#[derive(Clone)]6pub struct Config {7    pub port: u16,8    pub cache_control: Option<HeaderValue>,9    pub db_path: String,10    pub reset_db: bool,11    pub invite_secret: Option<String>,12    pub session_key: Key,13}1415impl Config {16    pub fn new(17        port: u16,18        cache_control: impl Into<Option<HeaderValue>>,19        db_path: String,20        reset_db: bool,21    ) -> Self {22        Self {23            port,24            cache_control: cache_control.into(),25            db_path,26            reset_db,27            invite_secret: None,28            session_key: Key::generate(),29        }30    }3132    pub fn invites_enabled(&self) -> bool {33        self.invite_secret34            .as_deref()35            .is_some_and(|secret| !secret.is_empty())36    }3738    pub fn invite_secret_matches(&self, provided: &str) -> bool {39        self.invites_enabled() && self.invite_secret.as_deref() == Some(provided)40    }4142    /// Deletes the database file if `RESET_DB` is set to true.43    pub fn maybe_reset_database(&self) {44        if !self.reset_db {45            return;46        }4748        log::warn!(49            "RESET_DB is set to true, deleting database file: {}",50            self.db_path51        );5253        if std::path::Path::new(&self.db_path).exists() {54            if let Err(e) = std::fs::remove_file(&self.db_path) {55                log::error!("Failed to delete database file: {e}");56            } else {57                log::info!("Database file deleted successfully");58            }59        }60    }61}6263pub fn parse_cache_control(val: Option<&str>) -> Option<HeaderValue> {64    val.and_then(|v| {65        let trimmed = v.trim();66        if trimmed.is_empty() {67            None68        } else if trimmed.eq_ignore_ascii_case("true") || trimmed == "1" {69            Some(HeaderValue::from_static("no-cache"))70        } else {71            HeaderValue::from_str(trimmed).ok()72        }73    })74}7576pub fn from_env() -> Config {77    let port = std::env::var("PORT")78        .unwrap_or_else(|_| "8080".to_string())79        .parse()80        .unwrap_or(8080);8182    let cache_control = parse_cache_control(std::env::var("CACHE_CONTROL").ok().as_deref());8384    let db_path = std::env::var("DB_PATH").unwrap_or_else(|_| "pear.db".to_string());85    let reset_db = std::env::var("RESET_DB").unwrap_or_default() == "true";8687    let mut config = Config::new(port, cache_control, db_path, reset_db);88    config.invite_secret = std::env::var("INVITE_SECRET")89        .ok()90        .filter(|secret| !secret.is_empty());91    config.session_key = if let Ok(secret) = std::env::var("SESSION_SECRET") {92        Key::try_from(secret.as_bytes())93            .unwrap_or_else(|_| panic!("SESSION_SECRET must be at least 64 bytes long"))94    } else {95        log::warn!("SESSION_SECRET is unset; sessions will not survive process restarts");96        Key::generate()97    };98    config99}100101#[cfg(test)]102mod tests {103    use super::*;104105    #[test]106    fn test_parse_cache_control() {107        assert_eq!(108            parse_cache_control(Some("no-cache")),109            Some(HeaderValue::from_static("no-cache"))110        );111        assert_eq!(112            parse_cache_control(Some("true")),113            Some(HeaderValue::from_static("no-cache"))114        );115        assert_eq!(parse_cache_control(Some("")), None);116        assert_eq!(parse_cache_control(None), None);117    }118119    #[test]120    fn test_maybe_reset_database_with_flag() {121        let path = format!(122            "/tmp/test_pear_reset_{}.db",123            std::time::SystemTime::now()124                .duration_since(std::time::UNIX_EPOCH)125                .unwrap()126                .as_nanos()127        );128        std::fs::write(&path, b"test").unwrap();129130        let config = Config::new(131            8080,132            HeaderValue::from_static(DEFAULT_CACHE_CONTROL),133            path.clone(),134            true,135        );136        config.maybe_reset_database();137138        assert!(!std::path::Path::new(&path).exists());139    }140}