/*
* 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 email_address::EmailAddress;
use laurelin_shared::{error::api::APIError, types::user::InsertableUser};
use crate::{actions, PgPool};
#[post("/api/user")]
pub(crate) async fn create(
pool: web::Data<PgPool>,
session: Session,
user: web::Json<InsertableUser>,
) -> impl Responder {
if user.username.len() < 3 {
return HttpResponse::BadRequest().json(APIError::UserUsernameTooShort);
}
if user.password.len() < 8 {
return HttpResponse::BadRequest().json(APIError::UserPasswordTooShort);
}
if !EmailAddress::is_valid(&user.email) {
return HttpResponse::BadRequest().json(APIError::UserEmailInvalid);
}
let user_create = web::block(move || {
let mut conn = match pool.get() {
Err(_) => return Err(APIError::DatabasePoolGetFailed),
Ok(conn) => conn,
};
actions::user::create(&mut conn, &user.0)
})
.await;
match user_create {
Err(_err) => {
// TODO: handle?
HttpResponse::InternalServerError().json(APIError::Undefined)
}
Ok(user_res) => match user_res {
Err(err) => HttpResponse::InternalServerError().json(err),
Ok(user) => match session.insert("user_id", user.id) {
Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
Ok(_) => HttpResponse::Ok().json(user),
},
},
}
}