diff options
author | Ilion Beyst <ilion.beyst@gmail.com> | 2022-08-09 23:27:22 +0200 |
---|---|---|
committer | Ilion Beyst <ilion.beyst@gmail.com> | 2022-08-09 23:27:22 +0200 |
commit | 406c7266019c0c36cfe5069bfe5cf293badd3a30 (patch) | |
tree | 1f5d054add282f45d9ff14de7a62160ff7ca31b2 /planetwars-server/src/db | |
parent | 58c1c5f9fb48040ad6b0891d586543c219de74d2 (diff) | |
download | planetwars.dev-406c7266019c0c36cfe5069bfe5cf293badd3a30.tar.xz planetwars.dev-406c7266019c0c36cfe5069bfe5cf293badd3a30.zip |
create password reset utility
Co-authored-by: Wout Schellaert <wout.schellaert@gmail.com>
Diffstat (limited to 'planetwars-server/src/db')
-rw-r--r-- | planetwars-server/src/db/users.rs | 28 |
1 files changed, 25 insertions, 3 deletions
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<User> { +pub fn hash_password(password: &str) -> (Vec<u8>, [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<User> { + 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::<User>(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<User> { find_user_by_name(credentials.username, db_conn) .optional() |