Parcourir la source

Refactor user creation to the user implementation

Lee Morgan il y a 2 mois
Parent
commit
aaf0173032
2 fichiers modifiés avec 18 ajouts et 14 suppressions
  1. 3 14
      src/controllers/user/create.rs
  2. 15 0
      src/models/user.rs

+ 3 - 14
src/controllers/user/create.rs

@@ -3,7 +3,6 @@ use serde::Deserialize;
 use serde_json::json;
 use sqlx::PgPool;
 use email_address::EmailAddress;
-use uuid::Uuid;
 use chrono::{DateTime, Utc, Duration};
 use argon2::{
     Argon2,
@@ -38,8 +37,9 @@ pub async fn route(
     }
     valid_password(&body.password, &body.confirm_password)?;
     let pass_hash = hash_password(&body.password)?;
-    let email = validate_email(&body.email)?;
-    let user = create_user(body.into_inner(), email, pass_hash);
+    let Body { name, email, .. } = body.into_inner();
+    validate_email(&email)?;
+    let user = User::new(name, email, pass_hash);
     user.insert(&db).await?;
     Ok(HttpResponse::Ok().json(json!({"success": true})))
 }
@@ -94,14 +94,3 @@ fn hash_password(pass: &String) -> Result<String, AppError> {
         Err(e) => Err(AppError::InternalError(e.to_string()))
     }
 }
-
-fn create_user(body: Body, email: String, pass_hash: String) -> User {
-    User {
-        id: Uuid::now_v7(),
-        token: Uuid::new_v4(),
-        name: body.name,
-        email: email,
-        pass_hash: pass_hash,
-        created_at: Utc::now()
-    }
-}

+ 15 - 0
src/models/user.rs

@@ -22,6 +22,21 @@ pub struct ResponseUser {
 }
 
 impl User {
+    pub fn new(
+        name: String,
+        email: String,
+        pass_hash: String
+    ) -> Self {
+        Self {
+            id: Uuid::now_v7(),
+            token: Uuid::new_v4(),
+            name: name,
+            email: email.to_lowercase(),
+            pass_hash: pass_hash,
+            created_at: Utc::now()
+        }
+    }
+
     pub async fn insert(&self, db: &PgPool) -> Result<(), AppError> {
         let result = sqlx::query!(
             r#"