brass/src/auth/routes/post_register.rs

55 lines
1.4 KiB
Rust

use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use serde::Deserialize;
use sqlx::PgPool;
use crate::{auth::utils::generate_salt_and_hash_plain_password, models::User};
#[derive(Deserialize)]
struct RegisterForm {
pub name: String,
pub email: String,
pub password: String,
pub role_id: u8,
pub function_id: u8,
pub area_id: i32,
}
#[actix_web::post("/register")]
async fn route(
web::Form(form): web::Form<RegisterForm>,
pool: web::Data<PgPool>,
) -> impl Responder {
let (hash, salt) = generate_salt_and_hash_plain_password(&form.password).unwrap();
let role = match form.role_id.try_into() {
Ok(role) => role,
Err(_) => return HttpResponse::BadRequest().body("fsdf"),
};
let function = match form.function_id.try_into() {
Ok(function) => function,
Err(_) => return HttpResponse::BadRequest().body("fsdf"),
};
let result = User::create(
pool.get_ref(),
&form.name,
&form.email,
&hash,
&salt,
role,
function,
form.area_id,
)
.await;
match result {
Ok(_) => {
return HttpResponse::PermanentRedirect()
.insert_header((LOCATION, "/"))
.finish()
}
Err(err) => return HttpResponse::BadRequest().body(err.to_string()),
}
}