DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 87f3f31d9d46d0ac597b7c6d58c1b5c36d21aa1a deck-builder/api/src/handlers/user/login.rs -rw-r--r-- 1.5 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
45
46
47
48
49
/*
 * 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 actix_session::Session;
use actix_web::{post, web, HttpResponse, Responder};
use laurelin_shared::{error::api::APIError, types::user::UserCredentials};

use crate::{actions, PgPool};

#[post("/api/user/login")]
pub(crate) async fn login(
    pool: web::Data<PgPool>,
    session: Session,
    credentials: web::Json<UserCredentials>,
) -> impl Responder {
    let user = match web::block(move || {
        let mut conn = match pool.get() {
            Err(_) => return Err(APIError::DatabasePoolGetFailed),
            Ok(conn) => conn,
        };
        actions::user::login(&mut conn, &credentials.0)
    })
    .await
    {
        Err(_) => {
            // TODO: handle?
            return HttpResponse::InternalServerError().json(APIError::Undefined);
        }
        Ok(user_res) => match user_res {
            Err(err) => match err {
                APIError::UserInvalidCredentials => {
                    return HttpResponse::Unauthorized().json(APIError::UserInvalidCredentials)
                }
                _ => return HttpResponse::InternalServerError().json(err),
            },
            Ok(user) => user,
        },
    };

    match session.insert("user_id", user.id) {
        Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
        Ok(_) => HttpResponse::Ok().json(user),
    }
}