diff --git a/Cargo.lock b/Cargo.lock index 815957e..b82b302 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -107,7 +107,7 @@ dependencies = [ "serde", "serde_derive", "unicode-ident", - "winnow", + "winnow 1.0.1", ] [[package]] @@ -2154,6 +2154,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2689,6 +2698,47 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tower" version = "0.5.3" @@ -3087,6 +3137,7 @@ dependencies = [ "sqlx", "thiserror 2.0.18", "tokio", + "toml", "tower-http", ] @@ -3467,6 +3518,15 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "1.0.1" diff --git a/Cargo.toml b/Cargo.toml index 590be41..41728e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,4 +16,5 @@ tokio = { version = "1.0", features = ["full"] } thiserror = "2.0" anyhow = "1.0" serde = { version = "1.0", features = ["derive"] } +toml = "0.8" tower-http = { version = "0.6", features = ["fs", "cors"] } diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..f81ebb0 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,20 @@ +# OIDC Configuration +[oidc] +client_id = "your_client_id" +client_secret = "your_client_secret" +auth_url = "https://your-provider.com/auth" +token_url = "https://your-provider.com/token" +redirect_url = "http://localhost:3000/auth/callback" + +# Server Configuration +[server] +host = "127.0.0.1" +port = 3000 + +# Database Configuration +[database] +url = "sqlite:weight_tracker.db" + +# Session Configuration +[session] +secret = "your_secret_key_that_is_long_enough_so_the_library_does_not_complain" diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..6e4d484 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,90 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::Path; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Config { + pub oidc: OidcConfig, + pub server: ServerConfig, + pub database: DatabaseConfig, + pub session: SessionConfig, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct OidcConfig { + pub client_id: String, + pub client_secret: String, + pub auth_url: String, + pub token_url: String, + pub redirect_url: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ServerConfig { + pub host: String, + pub port: u16, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DatabaseConfig { + pub url: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SessionConfig { + pub secret: String, +} + +impl Config { + /// Load configuration from a TOML file + /// Falls back to environment variables if file doesn't exist + pub fn load(path: &str) -> Result> { + if Path::new(path).exists() { + let content = fs::read_to_string(path)?; + let config: Config = toml::from_str(&content)?; + Ok(config) + } else { + // Fall back to environment variables + Ok(Config::from_env()) + } + } + + /// Load configuration from environment variables + pub fn from_env() -> Self { + let client_id = + std::env::var("OIDC_CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string()); + let client_secret = std::env::var("OIDC_CLIENT_SECRET") + .unwrap_or_else(|_| "your_client_secret".to_string()); + let auth_url = std::env::var("OIDC_AUTH_URL") + .unwrap_or_else(|_| "https://your-provider.com/auth".to_string()); + let token_url = std::env::var("OIDC_TOKEN_URL") + .unwrap_or_else(|_| "https://your-provider.com/token".to_string()); + let redirect_url = std::env::var("OIDC_REDIRECT_URL") + .unwrap_or_else(|_| "http://localhost:3000/auth/callback".to_string()); + let host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); + let port = std::env::var("SERVER_PORT") + .unwrap_or_else(|_| "3000".to_string()) + .parse() + .unwrap_or(3000); + let database_url = std::env::var("DATABASE_URL") + .unwrap_or_else(|_| "sqlite:weight_tracker.db".to_string()); + let session_secret = std::env::var("SESSION_SECRET").unwrap_or_else(|_| { + "your_secret_key_that_is_long_enough_so_the_library_does_not_complain".to_string() + }); + + Config { + oidc: OidcConfig { + client_id, + client_secret, + auth_url, + token_url, + redirect_url, + }, + server: ServerConfig { host, port }, + database: DatabaseConfig { url: database_url }, + session: SessionConfig { + secret: session_secret, + }, + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 2c65542..8138106 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod handlers; pub mod models; +pub mod config; use axum::{ Router, diff --git a/src/main.rs b/src/main.rs index 644b91b..cba8642 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,32 +1,29 @@ use oauth2::{AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl, basic::BasicClient}; use sqlx::SqlitePool; -use std::env; -use weight_tracker::{AppState, create_app}; +use weight_tracker::{AppState, create_app, config::Config}; #[tokio::main] async fn main() { + // Load configuration from config.toml or environment variables + let config = Config::load("config.toml").unwrap_or_else(|_| { + println!("config.toml not found, using environment variables"); + Config::from_env() + }); + // Set up database - let database_url = "sqlite:weight_tracker.db"; - let pool = SqlitePool::connect(database_url) + let pool = SqlitePool::connect(&config.database.url) .await .expect("Failed to connect to database"); // Set up OIDC client - let client_id = - ClientId::new(env::var("OIDC_CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string())); - let client_secret = ClientSecret::new( - env::var("OIDC_CLIENT_SECRET").unwrap_or_else(|_| "your_client_secret".to_string()), - ); - let auth_url = AuthUrl::new( - env::var("OIDC_AUTH_URL").unwrap_or_else(|_| "https://your-provider.com/auth".to_string()), - ) - .unwrap(); - let token_url = TokenUrl::new( - env::var("OIDC_TOKEN_URL") - .unwrap_or_else(|_| "https://your-provider.com/token".to_string()), - ) - .unwrap(); - let redirect_url = RedirectUrl::new("http://localhost:3000/auth/callback".to_string()).unwrap(); + let client_id = ClientId::new(config.oidc.client_id); + let client_secret = ClientSecret::new(config.oidc.client_secret); + let auth_url = AuthUrl::new(config.oidc.auth_url) + .unwrap(); + let token_url = TokenUrl::new(config.oidc.token_url) + .unwrap(); + let redirect_url = RedirectUrl::new(config.oidc.redirect_url) + .unwrap(); let oidc_client = BasicClient::new(client_id) .set_client_secret(client_secret) @@ -35,10 +32,7 @@ async fn main() { // Set the URL the user will be redirected to after the authorization process. .set_redirect_uri(redirect_url); - let secret = env::var("SESSION_SECRET") - .unwrap_or_else(|_| "your_secret_key_that_is_long_enough_so_the_library_does_not_complain".to_string()) - .as_bytes() - .to_vec(); + let secret = config.session.secret.as_bytes().to_vec(); let app_state = AppState { pool: pool.clone(), @@ -47,7 +41,8 @@ async fn main() { let app = create_app(app_state, secret, pool).await; - let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") + let addr = format!("{}:{}", config.server.host, config.server.port); + let listener = tokio::net::TcpListener::bind(&addr) .await .unwrap(); println!("listening on {}", listener.local_addr().unwrap()); diff --git a/tests/e2e.rs b/tests/e2e.rs index 8128905..af540c3 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -18,8 +18,8 @@ async fn make_app() -> axum::Router { Some(TokenUrl::new("http://localhost/token".into()).unwrap()), ); - let state = AppState { pool, oidc_client }; - create_app(state, b"01234567890123456789012345678901".to_vec()) + let state = AppState { pool: pool.clone(), oidc_client }; + create_app(state, b"01234567890123456789012345678901".to_vec(), pool).await } #[tokio::test]