Browse Source

Validate ownership of account before creating transaction.

Lee Morgan 1 năm trước cách đây
mục cha
commit
f0e4ac5c24

+ 1 - 1
bruno/Suma/Account/folder.bru

@@ -1,6 +1,6 @@
 meta {
   name: Account
-  seq: 2
+  seq: 3
 }
 
 auth {

+ 11 - 0
bruno/Suma/Transaction/Transaction.bru

@@ -0,0 +1,11 @@
+meta {
+  name: Transaction
+  type: http
+  seq: 3
+}
+
+get {
+  url: http://localhost:8000/api/transaction
+  body: none
+  auth: inherit
+}

+ 8 - 0
bruno/Suma/Transaction/folder.bru

@@ -0,0 +1,8 @@
+meta {
+  name: Transaction
+  seq: 4
+}
+
+auth {
+  mode: inherit
+}

+ 4 - 0
bruno/Suma/User/folder.bru

@@ -0,0 +1,4 @@
+meta {
+  name: User
+  seq: 2
+}

+ 5 - 0
src/controllers/transaction.rs

@@ -2,6 +2,7 @@ use actix_web::{post, web, HttpResponse, HttpRequest};
 use mongodb::Database;
 
 use crate::models::transaction::Transaction;
+use crate::models::account::Account;
 use crate::app_error::AppError;
 use crate::auth::user_auth;
 use crate::dto::transaction::CreateInput;
@@ -14,6 +15,10 @@ pub async fn create_route(
 ) -> Result<HttpResponse, AppError> {
     let user = user_auth(&db, &request).await?;
     let transaction_collection = db.collection::<Transaction>("transactions");
+
+    let account_collection = db.collection::<Account>("accounts");
+    Account::user_owns(&account_collection, &user, &body.account).await?;
+
     let id = Transaction::insert(&transaction_collection, body.into_inner()).await?;
     let transaction = Transaction::find_one(&transaction_collection, id).await?;
     Ok(HttpResponse::Ok().json(transaction.response()))

+ 13 - 0
src/models/account.rs

@@ -58,6 +58,19 @@ impl Account {
         }
     }
 
+    pub async fn user_owns(
+        coll: &Collection<Account>,
+        user: &User,
+        account: &String
+    ) -> Result<(), AppError> {
+        let id = ObjectId::parse_str(account)?;
+        let account = Account::find_by_id(coll, id).await?;
+        if user.id != account.user {
+            return Err(AppError::Auth);
+        }
+        Ok(())
+    }
+
     pub fn response(self) -> ResponseAccount {
         ResponseAccount {
             id: self.id.to_string(),