GeneIT/geneit_backend/src/controllers/auth_controller.rs

49 lines
1.7 KiB
Rust
Raw Normal View History

2023-05-24 14:19:46 +00:00
use crate::constants::StaticConstraints;
2023-05-26 15:55:19 +00:00
use crate::controllers::HttpResult;
use crate::services::rate_limiter_service::RatedAction;
use crate::services::{rate_limiter_service, users_service};
2023-05-24 14:19:46 +00:00
use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpResponse};
#[derive(serde::Deserialize)]
pub struct CreateAccountBody {
name: String,
email: String,
}
/// Create a new account
2023-05-26 15:55:19 +00:00
pub async fn create_account(remote_ip: RemoteIP, req: web::Json<CreateAccountBody>) -> HttpResult {
// Rate limiting
if rate_limiter_service::should_block_action(remote_ip.0, RatedAction::CreateAccount).await? {
return Ok(HttpResponse::TooManyRequests().finish());
}
rate_limiter_service::record_action(remote_ip.0, RatedAction::CreateAccount).await?;
2023-05-24 14:19:46 +00:00
2023-05-25 07:22:49 +00:00
// Check if email is valid
if !mailchecker::is_valid(&req.email) {
return Ok(HttpResponse::BadRequest().json("Email address is invalid!"));
}
2023-05-24 14:19:46 +00:00
// Check parameters
let constraints = StaticConstraints::default();
if !constraints.user_name_len.validate(&req.name) || !constraints.mail_len.validate(&req.email)
{
return Ok(HttpResponse::BadRequest().json("Size constraints were not respected!"));
}
2023-05-25 07:42:43 +00:00
// Check if email is already attached to an account
2023-05-26 15:55:19 +00:00
if users_service::exists_email(&req.email).await? {
return Ok(
HttpResponse::Conflict().json("An account with the same email address already exists!")
);
2023-05-25 07:42:43 +00:00
}
2023-05-24 14:19:46 +00:00
2023-05-25 07:42:43 +00:00
// Create the account
2023-05-26 15:55:19 +00:00
let user_id = users_service::create_account(&req.name, &req.email).await?;
2023-05-24 14:19:46 +00:00
// TODO : trigger reset password (send mail)
// Account successfully created
Ok(HttpResponse::Created().finish())
}