DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: f16455699e446e720cd55c99925f06aad952a46a deck-builder/api/src/handlers/user/create.rs -rw-r--r-- 1.7 KiB
f1645569Jonni Liljamo wip!(client, server, shared): initial updating to bevy 0.10 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
50
51
52
53
54
55
56
57
58
59
/*
 * 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;

use crate::{actions, models, PgPool};

#[post("/api/user")]
pub(crate) async fn create(
    pool: web::Data<PgPool>,
    session: Session,
    user: web::Json<models::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?
            return HttpResponse::InternalServerError().json(APIError::Undefined);
        }
        Ok(user_res) => match user_res {
            Err(err) => {
                return 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),
            },
        },
    }
}