add seed ability
This commit is contained in:
+64
@@ -0,0 +1,64 @@
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::db::Database;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SeedConfig {
|
||||
#[serde(default)]
|
||||
pub user: Option<SeedUser>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SeedUser {
|
||||
pub email: String,
|
||||
pub display_name: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
/// Reads the seed config file and creates the configured default user if the
|
||||
/// database has no users yet. The file is optional; if it does not exist (or
|
||||
/// cannot be parsed) seeding is skipped.
|
||||
pub async fn seed_if_needed(db: &Database, path: &Path) {
|
||||
let Ok(contents) = std::fs::read_to_string(path) else {
|
||||
return;
|
||||
};
|
||||
let config: SeedConfig = match serde_json::from_str(&contents) {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
warn!(path = %path.display(), %error, "could not parse seed config; skipping");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(user) = config.user else {
|
||||
return;
|
||||
};
|
||||
if user.email.trim().is_empty() {
|
||||
warn!("seed user requires a non-empty email; skipping");
|
||||
return;
|
||||
}
|
||||
if db.has_users().await.unwrap_or(true) {
|
||||
info!("database already has users; skipping seed");
|
||||
return;
|
||||
}
|
||||
let password_hash = match crate::hash_password(&user.password) {
|
||||
Ok(hash) => hash,
|
||||
Err(error) => {
|
||||
warn!(%error, "could not hash seed password; skipping");
|
||||
return;
|
||||
}
|
||||
};
|
||||
match db
|
||||
.create_user(
|
||||
user.email.trim().to_lowercase(),
|
||||
user.display_name.trim().to_owned(),
|
||||
password_hash,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(user) => info!(id = user.id, email = %user.email, "seeded default user"),
|
||||
Err(error) => warn!(%error, "could not seed default user"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user