summaryrefslogtreecommitdiff
path: root/server/src/routes/auth.rs
blob: 504d428b2695fcd17eb7868b0341075125f2fb0b (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::errors::AppError;
use crate::models::{
    auth::{AuthBody, Claims, LoginCredentials, SignUpForm},
    user::*,
};
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use serde::Serialize;

/// Create routes for `/v1/auth/` namespace
pub fn create_route() -> Router {
    Router::new()
        .route("/login", post(make_login))
        .route("/signup", post(signup))
}

/// Extension of `Json` which returns the CREATED status code
pub struct JsonCreate<T>(pub T);

impl<T> IntoResponse for JsonCreate<T>
where
    T: Serialize,
{
    fn into_response(self) -> Response {
        (StatusCode::CREATED, Json(self.0)).into_response()
    }
}

/// Make login. Check if a user with the email and password passed in request body exists into the
/// database
async fn make_login(Json(payload): Json<LoginCredentials>) -> Result<Json<AuthBody>, AppError> {
    let user = User::new(
        String::new(),
        String::new(),
        payload.username,
        payload.password,
    );
    match User::find(user).await {
        Ok(user) => {
            let claims = Claims::new(user.id);
            let token = claims.get_token()?;
            Ok(Json(AuthBody::new(token)))
        }
        Err(_) => Err(AppError::NotFound("User not found".to_string())),
    }
}

/// Create a new user
async fn signup(Json(payload): Json<SignUpForm>) -> Result<JsonCreate<AuthBody>, AppError> {
    if payload.password1 != payload.password2 {
        return Err(AppError::BadRequest(
            "The inserted passwords do not match".to_string(),
        ));
    }

    if User::email_has_taken(&payload.email).await? {
        return Err(AppError::BadRequest(
            "An user with this email already exists".to_string(),
        ));
    }

    if User::username_has_taken(&payload.username).await? {
        return Err(AppError::BadRequest(
            "An user with this username already exists".to_string(),
        ));
    }

    let user = User::new(
        payload.name,
        payload.email,
        payload.username,
        payload.password1,
    );
    let user = User::create(user).await?;

    let claims = Claims::new(user.id);
    let token = claims.get_token()?;
    Ok(JsonCreate(AuthBody::new(token)))
}