DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

82c3e0c9e677e9ed01e723882d7175079841a8f4 — Jonni Liljamo 1 year, 7 months ago dc1f6cd
feat(api): login password verification
1 files changed, 29 insertions(+), 3 deletions(-)

M api/src/actions/user/login.rs
M api/src/actions/user/login.rs => api/src/actions/user/login.rs +29 -3
@@ 6,14 6,40 @@
 * See LICENSE for licensing information.
 */

use diesel::PgConnection;
use argon2::{Argon2, PasswordHash, PasswordVerifier};
use diesel::{ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};
use laurelin_shared::error::api::APIError;

use crate::models::{User, UserCredentials};
use crate::{
    models::{User, UserCredentials},
    schema::users,
};

pub(crate) fn login(
    conn: &mut PgConnection,
    credentials: &UserCredentials,
) -> Result<User, APIError> {
    Err(APIError::UserInvalidCredentials)
    let user = match users::table
        .filter(users::email.eq(&credentials.email))
        .first::<User>(conn)
    {
        Err(_) => {
            // TODO: Handle and return other errors too...
            // Might be misleading if not actually this specific error,
            // but this is the most likely error.
            return Err(APIError::UserNotFound);
        }
        Ok(user) => user,
    };

    // TODO: handle unwrap
    let parsed_hash = PasswordHash::new(&user.password).unwrap();
    let password_ok =
        Argon2::default().verify_password(credentials.password.as_bytes(), &parsed_hash);

    if password_ok.is_ok() {
        Ok(user)
    } else {
        Err(APIError::UserInvalidCredentials)
    }
}