DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 87f3f31d9d46d0ac597b7c6d58c1b5c36d21aa1a deck-builder/api/src/actions/user/login.rs -rw-r--r-- 1.3 KiB
87f3f31dJonni Liljamo feat(schema, shared, api): move all types to shared, separate schema 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 * This file is part of laurelin/api
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use argon2::{Argon2, PasswordHash, PasswordVerifier};
use diesel::{ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};
use laurelin_schema::schema::users;
use laurelin_shared::{
    error::api::APIError,
    types::user::{User, UserCredentials},
};

pub(crate) fn login(
    conn: &mut PgConnection,
    credentials: &UserCredentials,
) -> Result<User, APIError> {
    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)
    }
}