diff options
| author | Santo Cariotti <santo@dcariotti.me> | 2022-09-13 12:51:32 +0000 |
|---|---|---|
| committer | Santo Cariotti <santo@dcariotti.me> | 2022-09-13 12:51:32 +0000 |
| commit | 64d5f37d9e28363f27b49b9a5b421a19792d0165 (patch) | |
| tree | 210cbea0a4b17adee8c8916c3089a18fb9c77fbc /src/routes | |
| parent | ce62e3bac6a8acea555731d6222028c511dd9019 (diff) | |
Signup route
Diffstat (limited to 'src/routes')
| -rw-r--r-- | src/routes/auth.rs | 34 |
1 files changed, 32 insertions, 2 deletions
diff --git a/src/routes/auth.rs b/src/routes/auth.rs index b667b97..5c9b293 100644 --- a/src/routes/auth.rs +++ b/src/routes/auth.rs @@ -1,13 +1,15 @@ use crate::errors::AppError; use crate::models::{ - auth::{AuthBody, Claims, LoginCredentials}, + auth::{AuthBody, Claims, LoginCredentials, SignUpForm}, user::User, }; use axum::{routing::post, Json, Router}; /// Create routes for `/v1/auth/` namespace pub fn create_route() -> Router { - Router::new().route("/login", post(make_login)) + Router::new() + .route("/login", post(make_login)) + .route("/signup", post(signup)) } /// Make login. Check if a user with the email and password passed in request body exists into the @@ -23,3 +25,31 @@ async fn make_login(Json(payload): Json<LoginCredentials>) -> Result<Json<AuthBo Err(_) => Err(AppError::NotFound("User not found".to_string())), } } + +/// Create a new user +async fn signup(Json(payload): Json<SignUpForm>) -> Result<Json<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.email, payload.username, payload.password1); + let user = User::create(user).await?; + + let claims = Claims::new(user.id); + let token = claims.get_token()?; + Ok(Json(AuthBody::new(token))) +} |
