feat: add simple cli user management

image-uploads
Jef Roosens 2025-01-12 10:05:38 +01:00
parent 3800534a51
commit cc5f7856f6
No known key found for this signature in database
GPG Key ID: 21FD3D77D56BAF49
3 changed files with 47 additions and 1 deletions

View File

@ -39,7 +39,7 @@ pub enum Subcommands {
#[derive(Args)]
pub struct UserCmd {
#[command(subcommand)]
cmd: UserSubCmd,
pub cmd: UserSubCmd,
}
#[derive(Subcommand)]

View File

@ -51,6 +51,22 @@ impl User {
.verify_password(password.as_ref().as_bytes(), &password_hash)
.is_ok()
}
pub fn all(pool: &DbPool) -> Result<Vec<Self>, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare("select * from users")?;
let users: Result<Vec<_>, _> = stmt.query_map((), Self::from_row)?.collect();
Ok(users?)
}
pub fn remove_by_username(pool: &DbPool, username: impl AsRef<str>) -> Result<bool, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare("delete from users where username = $1")?;
Ok(stmt.execute((username.as_ref(),))? > 0)
}
}
fn hash_password(password: impl AsRef<str>) -> String {

View File

@ -27,6 +27,36 @@ pub struct Context {
}
fn run_user_cli(data_dir: impl AsRef<Path>, cmd: UserCmd) -> Result<(), DbError> {
let manager = SqliteConnectionManager::file(data_dir.as_ref().join(DB_FILENAME));
let pool = r2d2::Pool::new(manager)?;
match cmd.cmd {
cli::UserSubCmd::List => {
let users = db::User::all(&pool)?;
println!("id\tusername\tis admin");
for user in users {
println!("{}\t{}\t{}", user.id, user.username, user.admin);
}
}
cli::UserSubCmd::Add {
username,
password,
admin,
} => {
db::NewUser {
username,
password,
admin,
}
.insert(&pool)?;
}
cli::UserSubCmd::Remove { username } => {
db::User::remove_by_username(&pool, &username)?;
}
}
Ok(())
}