From 860fd769695a651248c53fc2e4b657bb3f5a9a88 Mon Sep 17 00:00:00 2001 From: MedzikUser Date: Sat, 30 Apr 2022 21:56:06 +0200 Subject: [PATCH] server (/auth/register): add validator --- server/src/auth/register.rs | 15 +++++++++++++++ types/src/errors/auth.rs | 9 +++++++++ types/src/errors/mod.rs | 3 +++ 3 files changed, 27 insertions(+) diff --git a/server/src/auth/register.rs b/server/src/auth/register.rs index 6e73e54..7ba456a 100644 --- a/server/src/auth/register.rs +++ b/server/src/auth/register.rs @@ -15,6 +15,21 @@ pub async fn handle( ) -> Result, ServerError> { let request = validate_json::(request)?; + // username must contain at least 4 characters + if request.username.len() < 4 { + return Err(ServerError::AuthError(AuthError::UsernameTooShort)); + } + + // username must be less than 20 characters + if request.username.len() < 20 { + return Err(ServerError::AuthError(AuthError::UsernameTooLong)); + } + + // password must contain at least 8 characters + if request.password.len() < 8 { + return Err(ServerError::AuthError(AuthError::PasswordTooShort)); + } + let user = User::new(&request.username, &request.password); let response = match db.create_user(&user).await { diff --git a/types/src/errors/auth.rs b/types/src/errors/auth.rs index 162cc48..d1f35b8 100644 --- a/types/src/errors/auth.rs +++ b/types/src/errors/auth.rs @@ -8,6 +8,15 @@ pub enum Error { #[error("user already exists")] UserAlreadyExists, + #[error("username is too short")] + UsernameTooShort, + + #[error("username is too long")] + UsernameTooLong, + + #[error("password is too short")] + PasswordTooShort, + #[error("generate jwt token")] TokenGenerate, diff --git a/types/src/errors/mod.rs b/types/src/errors/mod.rs index b9692a6..d529a37 100644 --- a/types/src/errors/mod.rs +++ b/types/src/errors/mod.rs @@ -43,6 +43,9 @@ impl axum::response::IntoResponse for ServerError { Self::AuthError(ref err) => match err { AuthError::UserNotFound => StatusCode::BAD_REQUEST, AuthError::UserAlreadyExists => StatusCode::NOT_ACCEPTABLE, + AuthError::UsernameTooShort => StatusCode::NOT_ACCEPTABLE, + AuthError::UsernameTooLong => StatusCode::NOT_ACCEPTABLE, + AuthError::PasswordTooShort => StatusCode::NOT_ACCEPTABLE, AuthError::TokenGenerate => StatusCode::INTERNAL_SERVER_ERROR, AuthError::InvalidToken => StatusCode::BAD_REQUEST, AuthError::UnknowError(_) => StatusCode::INTERNAL_SERVER_ERROR,