64 lines
1.7 KiB
Rust
64 lines
1.7 KiB
Rust
use std::process::ExitCode;
|
|
|
|
use futures_util::StreamExt;
|
|
use sqlx::{query, sqlite::SqlitePool};
|
|
|
|
use crate::cli::UserCommand as UC;
|
|
|
|
pub async fn handle_user_command(user_command: UC, db: SqlitePool) -> anyhow::Result<ExitCode> {
|
|
match user_command {
|
|
UC::List {} => list_users(db).await,
|
|
UC::Create { user_name } => create_user(db, user_name).await,
|
|
UC::ResetPassword { user_id } => reset_password(&db, user_id).await
|
|
}
|
|
}
|
|
|
|
async fn list_users(db: SqlitePool) -> anyhow::Result<ExitCode> {
|
|
println!("\n\nListing users:");
|
|
|
|
let mut results = query!("SELECT user_id, user_name FROM users;").fetch(&db);
|
|
while let Some(Ok(user)) = results.next().await {
|
|
println!("\t{:?}: {}", user.user_id, user.user_name);
|
|
}
|
|
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
|
|
fn get_password() -> anyhow::Result<String> {
|
|
let password1 = rpassword::prompt_password("Enter new password: ")?;
|
|
let password2 = rpassword::prompt_password("Enter password again: ")?;
|
|
|
|
if password1 != password2 {
|
|
Err(anyhow::anyhow!("Passwords do not match!"))?
|
|
}
|
|
|
|
Ok(password1)
|
|
}
|
|
|
|
async fn create_user(db: SqlitePool, name: String) -> anyhow::Result<ExitCode> {
|
|
let password = get_password()?;
|
|
|
|
let mut tx = db.begin().await?;
|
|
|
|
crate::db::user::create_user(&mut tx, name, password).await?;
|
|
|
|
tx.commit().await?;
|
|
|
|
println!("User successfully created!");
|
|
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
|
|
async fn reset_password<'a, E>(db: E, id: i16) -> anyhow::Result<ExitCode>
|
|
where
|
|
E: sqlx::SqliteExecutor<'a>
|
|
{
|
|
let password = get_password()?;
|
|
|
|
crate::db::user::reset_password(db, id, password).await?;
|
|
|
|
println!("Password set successfully!");
|
|
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|