DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: c4de093f521dd6e4c6574f826e6a22f43a75b294 deck-builder/api/src/handlers/user/login.rs -rw-r--r-- 1.5 KiB
c4de093fJonni Liljamo feat(api): logout endpoint 1 year, 7 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;

use crate::{actions, models::UserCredentials, 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),
    }
}