DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

049bf0bac43bc3f464c2e45d61ed154a87df4e76 — Jonni Liljamo 1 year, 7 months ago 3a729b2
fix(api): check if user exists before hashing password on registration
1 files changed, 12 insertions(+), 1 deletions(-)

M api/src/actions/user/create.rs
M api/src/actions/user/create.rs => api/src/actions/user/create.rs +12 -1
@@ 10,7 10,7 @@ use argon2::{
    password_hash::{rand_core::OsRng, SaltString},
    Argon2, PasswordHasher,
};
use diesel::{PgConnection, RunQueryDsl};
use diesel::{ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};
use laurelin_shared::error::api::APIError;

use crate::{


@@ 19,6 19,17 @@ use crate::{
};

pub(crate) fn create(conn: &mut PgConnection, user: &InsertableUser) -> Result<User, APIError> {
    // NOTE: password hashing is expensive, a query at the start is about 170 times faster,
    // compared to hashing the password and finding out the user exists and erroring out on the insert
    // (according to quick maths and like 5 tests)
    if users::table
        .filter(users::email.eq(&user.email))
        .first::<User>(conn)
        .is_ok()
    {
        return Err(APIError::UserCreationFailed);
    }

    let salt = SaltString::generate(&mut OsRng);
    let password_hash_result = Argon2::default().hash_password(user.password.as_bytes(), &salt);