/*
* 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),
}
}