5.8 KiB · text History de2cabc
use sea_orm::DatabaseConnection;
use std::env;

/// Runtime configuration, sourced entirely from the environment so the same
/// binary works across local, container, and CI without a config file.
#[derive(Debug, Clone)]
pub struct Config {
    /// Display name shown in templates (title, nav brand, theme key).
    pub app_name: String,
    pub database_url: String,
    pub bind_address: String,
    pub session_duration_hours: i64,
    pub registration_token_duration_days: i64,
    /// Run pending migrations on startup.
    pub auto_migrate: bool,
    /// Allow `/register` without an invite link. Invite tokens are still
    /// required to actually create the account.
    pub registration_enabled: bool,
    /// Minimum trust level required to mint NEW tags (Discourse default: 3).
    /// Lower-tier users can still apply existing tags. Staff always can.
    pub min_trust_to_create_tag: i32,

    /// Absolute origin the app is reached at (no trailing slash): the base of
    /// email-verification links and of the default OIDC redirect URI. When it
    /// is https the session cookie is also marked `Secure`.
    pub public_url: String,
    /// "Sign in with NEIAM" and any other OIDC providers (neiam-auth). Off
    /// unless `OIDC_ENABLED=true`; see the README.
    pub oidc: neiam_auth::OidcProviders,
    /// `OIDC_PASSWORD_LOGIN` (default true). When false the password form is
    /// hidden and `POST /auth/login` is refused.
    pub password_login: bool,

    /// mail-prism (`MAIL_PRISM_URL` + `MAIL_PRISM_API_KEY`). Unset: mail is
    /// only logged (development).
    pub mail_prism_url: Option<String>,
    pub mail_prism_api_key: Option<String>,
    /// From address; must equal the mail-prism application address. Unset:
    /// mail-prism uses the application's own address.
    pub mail_from_address: Option<String>,
    pub mail_from_name: String,
    /// Lifetime of an email-verification link.
    pub email_verification_ttl_hours: i64,
    /// Unverified accounts can read but not post, reply, react, bookmark or
    /// tag. `REQUIRE_EMAIL_VERIFICATION=false` turns the gate off.
    pub require_email_verification: bool,
}

impl Config {
    pub fn from_env() -> Self {
        let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "0.0.0.0:3000".to_string());
        let public_url = env_present("PUBLIC_URL")
            .unwrap_or_else(|| default_public_url(&bind_address))
            .trim_end_matches('/')
            .to_string();
        let app_name = env::var("APP_NAME").unwrap_or_else(|_| "recourse".to_string());
        Config {
            oidc: neiam_auth::OidcProviders::from_env_with_public_url(&public_url),
            password_login: parse_bool("OIDC_PASSWORD_LOGIN", true),
            mail_prism_url: env_present("MAIL_PRISM_URL").map(|s| s.trim_end_matches('/').to_string()),
            mail_prism_api_key: env_present("MAIL_PRISM_API_KEY"),
            mail_from_address: env_present("MAIL_FROM_ADDRESS"),
            mail_from_name: env_present("MAIL_FROM_NAME").unwrap_or_else(|| app_name.clone()),
            email_verification_ttl_hours: env::var("EMAIL_VERIFICATION_TTL_HOURS")
                .ok()
                .and_then(|v| v.parse().ok())
                .filter(|h: &i64| *h > 0)
                .unwrap_or(48),
            require_email_verification: parse_bool("REQUIRE_EMAIL_VERIFICATION", true),
            public_url,
            app_name,
            database_url: env::var("DATABASE_URL").unwrap_or_else(|_| {
                // Host port 5439 (not 5432) — 5432 is commonly taken by other
                // local Postgres containers. Matches compose.yml's mapping.
                "postgres://recourse_user:recourse_password@localhost:5439/recourse".to_string()
            }),
            bind_address,
            session_duration_hours: env::var("SESSION_DURATION_HOURS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(24),
            registration_token_duration_days: env::var("REGISTRATION_TOKEN_DURATION_DAYS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(7),
            auto_migrate: env::var("AUTO_MIGRATE")
                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
                .unwrap_or(true),
            registration_enabled: env::var("REGISTRATION_ENABLED")
                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
                .unwrap_or(false),
            min_trust_to_create_tag: env::var("MIN_TRUST_TO_CREATE_TAG")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(3),
        }
    }
}

impl Config {
    /// Mark the session cookie `Secure` when the app is served over https.
    pub fn secure_cookies(&self) -> bool {
        self.public_url.starts_with("https://")
    }

    /// Whether mail actually goes out (mail-prism configured) rather than
    /// only being logged.
    pub fn mail_configured(&self) -> bool {
        self.mail_prism_url.is_some() && self.mail_prism_api_key.is_some()
    }
}

/// A set, non-blank environment variable (blank counts as unset).
fn env_present(key: &str) -> Option<String> {
    env::var(key).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
}

fn parse_bool(key: &str, default: bool) -> bool {
    env::var(key)
        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
        .unwrap_or(default)
}

/// `http://localhost:<port>` from a bind address like `0.0.0.0:3000`.
fn default_public_url(bind_address: &str) -> String {
    let port = bind_address.rsplit(':').next().unwrap_or("3000");
    format!("http://localhost:{port}")
}

pub async fn create_db_connection(database_url: &str) -> Result<DatabaseConnection, sea_orm::DbErr> {
    sea_orm::Database::connect(database_url).await
}