2023-05-24 14:19:46 +00:00
|
|
|
use crate::constants::StaticConstraints;
|
|
|
|
use crate::services::users_service;
|
|
|
|
use actix_remote_ip::RemoteIP;
|
|
|
|
use actix_web::error::ErrorInternalServerError;
|
|
|
|
use actix_web::{web, HttpResponse};
|
|
|
|
|
|
|
|
#[derive(serde::Deserialize)]
|
|
|
|
pub struct CreateAccountBody {
|
|
|
|
name: String,
|
|
|
|
email: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a new account
|
|
|
|
pub async fn create_account(
|
|
|
|
_remote_ip: RemoteIP,
|
|
|
|
req: web::Json<CreateAccountBody>,
|
|
|
|
) -> actix_web::Result<HttpResponse> {
|
|
|
|
// TODO : rate limiting
|
|
|
|
|
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
|
|
|
|
match users_service::exists_email(&req.email).await {
|
|
|
|
Ok(false) => {}
|
|
|
|
Ok(true) => {
|
|
|
|
return Ok(HttpResponse::Conflict()
|
|
|
|
.json("An account with the same email address already exists!"));
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("Failed to check email existence! {}", e);
|
|
|
|
return Err(ErrorInternalServerError(e));
|
|
|
|
}
|
|
|
|
}
|
2023-05-24 14:19:46 +00:00
|
|
|
|
2023-05-25 07:42:43 +00:00
|
|
|
// Create the account
|
2023-05-24 14:19:46 +00:00
|
|
|
let user_id = users_service::create_account(&req.name, &req.email)
|
|
|
|
.await
|
|
|
|
.map_err(|e| {
|
|
|
|
log::error!("Failed to create user! {e}");
|
|
|
|
ErrorInternalServerError(e)
|
|
|
|
})?;
|
|
|
|
|
|
|
|
// TODO : trigger reset password (send mail)
|
|
|
|
|
|
|
|
// Account successfully created
|
|
|
|
Ok(HttpResponse::Created().finish())
|
|
|
|
}
|