From 406c7266019c0c36cfe5069bfe5cf293badd3a30 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 9 Aug 2022 23:27:22 +0200 Subject: create password reset utility Co-authored-by: Wout Schellaert --- planetwars-server/src/db/users.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'planetwars-server/src/db/users.rs') diff --git a/planetwars-server/src/db/users.rs b/planetwars-server/src/db/users.rs index ebb2268..9676dae 100644 --- a/planetwars-server/src/db/users.rs +++ b/planetwars-server/src/db/users.rs @@ -42,11 +42,17 @@ fn argon2_config() -> argon2::Config<'static> { } } -pub fn create_user(credentials: &Credentials, conn: &PgConnection) -> QueryResult { +pub fn hash_password(password: &str) -> (Vec, [u8; 32]) { let argon_config = argon2_config(); - let salt: [u8; 32] = rand::thread_rng().gen(); - let hash = argon2::hash_raw(credentials.password.as_bytes(), &salt, &argon_config).unwrap(); + let hash = argon2::hash_raw(password.as_bytes(), &salt, &argon_config).unwrap(); + + (hash, salt) +} + +pub fn create_user(credentials: &Credentials, conn: &PgConnection) -> QueryResult { + let (hash, salt) = hash_password(&credentials.password); + let new_user = NewUser { username: credentials.username, password_salt: &salt, @@ -69,6 +75,22 @@ pub fn find_user_by_name(username: &str, db_conn: &PgConnection) -> QueryResult< .first::(db_conn) } +pub fn set_user_password(credentials: Credentials, db_conn: &PgConnection) -> QueryResult<()> { + let (hash, salt) = hash_password(&credentials.password); + + let n_changes = diesel::update(users::table.filter(users::username.eq(&credentials.username))) + .set(( + users::password_salt.eq(salt.as_slice()), + users::password_hash.eq(hash.as_slice()), + )) + .execute(db_conn)?; + if n_changes == 0 { + Err(diesel::result::Error::NotFound) + } else { + Ok(()) + } +} + pub fn authenticate_user(credentials: &Credentials, db_conn: &PgConnection) -> Option { find_user_by_name(credentials.username, db_conn) .optional() -- cgit v1.2.3