From 434423454db3a7244c0f1e422f1ab2df06f7d867 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 18 Oct 2022 21:14:16 +0200 Subject: Add signup --- server/src/routes/auth.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) (limited to 'server/src/routes/auth.rs') diff --git a/server/src/routes/auth.rs b/server/src/routes/auth.rs index 37c41b2..e3d7e4e 100644 --- a/server/src/routes/auth.rs +++ b/server/src/routes/auth.rs @@ -1,13 +1,15 @@ use crate::errors::AppError; use crate::models::{ - auth::{AuthBody, Claims}, - user::{User, UserCreate}, + auth::{AuthBody, Claims, SignUpForm}, + 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,24 @@ async fn make_login(Json(payload): Json) -> Result, A Err(_) => Err(AppError::NotFound), } } +/// Create a new user +async fn signup(Json(payload): Json) -> Result, 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(), + )); + } + + let user = User::new(payload.email, payload.password1); + let user = User::create(user).await?; + + let claims = Claims::new(user.id); + let token = claims.get_token()?; + Ok(Json(AuthBody::new(token))) +} -- cgit v1.2.3-18-g5258