diff --git a/Cargo.lock b/Cargo.lock index c2bfde1..abfe2db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5060,6 +5060,7 @@ dependencies = [ "axum", "axum-extra", "chrono", + "dotenvy", "fluent-templates", "include_dir", "insta", diff --git a/Cargo.toml b/Cargo.toml index d16be96..af50745 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ sea-orm = { version = "1.1", features = [ ] } chrono = { version = "0.4" } time = { version = "0.3" } +dotenvy = { version = "0.15" } validator = { version = "0.20" } uuid = { version = "1.6", features = ["v4"] } include_dir = { version = "0.7" } diff --git a/src/app.rs b/src/app.rs index 2ab714f..7c431fc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -43,10 +43,16 @@ impl Hooks for App { create_app::(mode, environment, config).await } + async fn load_config(environment: &Environment) -> Result { + dotenvy::dotenv().ok(); + environment.load() + } + async fn initializers(_ctx: &AppContext) -> Result>> { - Ok(vec![Box::new( - initializers::view_engine::ViewEngineInitializer, - )]) + Ok(vec![ + Box::new(initializers::view_engine::ViewEngineInitializer), + Box::new(initializers::admin_seeder::AdminSeeder), + ]) } fn routes(_ctx: &AppContext) -> AppRoutes { diff --git a/src/initializers/admin_seeder.rs b/src/initializers/admin_seeder.rs new file mode 100644 index 0000000..b4d4620 --- /dev/null +++ b/src/initializers/admin_seeder.rs @@ -0,0 +1,36 @@ +use async_trait::async_trait; +use loco_rs::prelude::*; + +use crate::models::users::{self, RegisterParams}; + +pub struct AdminSeeder; + +#[async_trait] +impl Initializer for AdminSeeder { + fn name(&self) -> String { + "admin-seeder".to_string() + } + + async fn before_run(&self, ctx: &AppContext) -> Result<()> { + let email = std::env::var("ADMIN_EMAIL").unwrap_or_default(); + let password = std::env::var("ADMIN_PASSWORD").unwrap_or_default(); + let name = std::env::var("ADMIN_NAME").unwrap_or_else(|_| "Admin".to_string()); + + if email.is_empty() || password.is_empty() { + tracing::warn!("ADMIN_EMAIL / ADMIN_PASSWORD not set in .env; admin not seeded"); + } else if users::Model::find_by_email(&ctx.db, &email).await.is_err() { + users::Model::create_with_password( + &ctx.db, + &RegisterParams { + email: email.clone(), + password, + name, + }, + ) + .await?; + tracing::info!(admin = %email, "admin user seeded"); + } + + Ok(()) + } +} diff --git a/src/initializers/mod.rs b/src/initializers/mod.rs index cbe3470..a5780a7 100644 --- a/src/initializers/mod.rs +++ b/src/initializers/mod.rs @@ -1 +1,2 @@ +pub mod admin_seeder; pub mod view_engine;