feat: added basic user management
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
use sqlx::{sqlite::SqlitePool, Database};
|
||||
use pbkdf2::{pbkdf2_hmac_array, password_hash::{rand_core::OsRng, SaltString}};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
const PASSWORD_ITERATIONS: u32 = 100_000;
|
||||
|
||||
pub async fn reset_password<'a, E>(pool: E, id: i16, password: String) -> anyhow::Result<()>
|
||||
pub async fn reset_password<'a, E>(pool: E, id: i16, password: String) -> Result<(), crate::error::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Sqlite>
|
||||
E: sqlx::SqliteExecutor<'a>
|
||||
{
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
|
||||
@@ -30,3 +31,37 @@ where
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create_user<'a, E>(acq: E, name: String, password: String) -> Result<(), crate::error::Error>
|
||||
where
|
||||
E: sqlx::Acquire<'a, Database = sqlx::Sqlite>
|
||||
{
|
||||
let mut tx = acq.begin().await?;
|
||||
|
||||
let previous_user_check = sqlx::query_scalar!(
|
||||
"SELECT COUNT(*) FROM users WHERE user_name = ?",
|
||||
name
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if previous_user_check > 0 {
|
||||
return Err(Error::UserCreate("User already exists".to_string()));
|
||||
}
|
||||
|
||||
tracing::info!("Creating new user {}", name);
|
||||
|
||||
let new_id = sqlx::query!(
|
||||
r#"INSERT INTO users (user_name, password_salt, password_hash) VALUES (?, "", "")"#,
|
||||
name
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.last_insert_rowid();
|
||||
|
||||
reset_password(&mut *tx, new_id as i16, password).await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user