Bläddra i källkod

Update create user route to return user data.

Lee Morgan 11 månader sedan
förälder
incheckning
35b838caea
4 ändrade filer med 20 tillägg och 17 borttagningar
  1. 1 0
      bruno/Suma/User/Create.bru
  2. 5 5
      src/auth.rs
  3. 5 4
      src/controllers/user.rs
  4. 9 8
      src/models/user.rs

+ 1 - 0
bruno/Suma/User/Create.bru

@@ -12,6 +12,7 @@ post {
 
 body:json {
   {
+    "name": "Lee Morgan",
     "email": "lee@leemorgan.dev",
     "password_hash": "leerobertmorgan",
     "password_salt": "leerobertmorgan",

+ 5 - 5
src/auth.rs

@@ -1,5 +1,6 @@
 use mongodb::Database;
 use actix_web::{HttpRequest};
+use bson::oid::ObjectId;
 
 use crate::models::user::User;
 use crate::app_error::AppError;
@@ -8,10 +9,9 @@ pub async fn user_auth(
     db: &Database,
     req: &HttpRequest
 ) -> Result<User, AppError> {
-    let user_id = req.cookie("user")
-        .ok_or(AppError::Auth)?
-        .value()
-        .to_string();
+    let cookie = req.cookie("user").ok_or(AppError::Auth)?;
+    let user_id = cookie.value();
+    let object_id = ObjectId::parse_str(user_id)?;
     let user_collection = db.collection::<User>("users");
-    Ok(User::find_by_id(&user_collection, user_id).await?)
+    Ok(User::find_by_id(&user_collection, object_id).await?)
 }

+ 5 - 4
src/controllers/user.rs

@@ -22,14 +22,15 @@ pub async fn get_password_salt_route(
 #[post("/api/user")]
 pub async fn create_route(
     db: web::Data<Database>,
-    payload: web::Json<CreateInput>
+    body: web::Json<CreateInput>
 ) -> Result<HttpResponse, AppError> {
     let user_collection = db.collection::<User>("users");
-    let email = payload.email.to_lowercase();
+    let email = body.email.to_lowercase();
     valid_email(&email)?;
     user_exists(&user_collection, &email).await?;
-    User::insert(&user_collection, payload.into_inner()).await?;
-    Ok(HttpResponse::Ok().json(json!({"success": true})))
+    let user_id = User::insert(&user_collection, body.into_inner()).await?;
+    let user = User::find_by_id(&user_collection, user_id.clone()).await?;
+    Ok(HttpResponse::Ok().json(user.response(None)))
 }
 
 #[post("/api/user/login")]

+ 9 - 8
src/models/user.rs

@@ -1,6 +1,6 @@
 use serde::{Serialize, Deserialize};
 use bson::{oid::ObjectId, DateTime, doc};
-use mongodb::{Collection, error::Error};
+use mongodb::Collection;
 
 use crate::app_error::AppError;
 use crate::models::account::ResponseAccount;
@@ -29,7 +29,7 @@ pub struct ResponseUser {
 }
 
 impl User {
-    pub async fn insert(collection: &Collection<User>, input: CreateInput) -> Result<(), Error> {
+    pub async fn insert(collection: &Collection<User>, input: CreateInput) -> Result<ObjectId, AppError> {
         let user = User {
             id: ObjectId::new(),
             name: input.name,
@@ -40,8 +40,11 @@ impl User {
             created_at: DateTime::now()
         };
 
-        collection.insert_one(user).await?;
-        Ok(())
+        let result = collection.insert_one(user).await?;
+        match result.inserted_id.as_object_id() {
+            Some(oid) => Ok(oid),
+            None => Err(AppError::InternalError("Internal server error".to_string()))
+        }
     }
 
     pub async fn find_by_email(collection: &Collection<User>, email: &str) -> Result<User, AppError> {
@@ -52,10 +55,8 @@ impl User {
         }
     }
 
-    pub async fn find_by_id(collection: &Collection<User>, user_id: String) -> Result<User, AppError> {
-        let object_id = ObjectId::parse_str(user_id)
-            .map_err(|_| AppError::invalid_input("Invalid user ID"))?;
-        match collection.find_one(doc!{"_id": object_id}).await {
+    pub async fn find_by_id(collection: &Collection<User>, user_id: ObjectId) -> Result<User, AppError> {
+        match collection.find_one(doc!{"_id": user_id}).await {
             Ok(Some(u)) => Ok(u),
             Ok(None) => Err(AppError::Auth),
             Err(e) => Err(AppError::Database(e.into()))