From 96e20a66a08ad72835b677607949e03af0e58ad4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa?= Date: Thu, 19 Apr 2018 18:57:17 +0200 Subject: [PATCH] Removed some duplicated code in the delete cipher functions --- src/api/core/ciphers.rs | 61 +++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 33 deletions(-) diff --git a/src/api/core/ciphers.rs b/src/api/core/ciphers.rs index 5ca371b..3dae6a8 100644 --- a/src/api/core/ciphers.rs +++ b/src/api/core/ciphers.rs @@ -361,27 +361,12 @@ fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn #[post("/ciphers//delete")] fn delete_cipher_post(uuid: String, headers: Headers, conn: DbConn) -> EmptyResult { - delete_cipher(uuid, headers, conn) + _delete_cipher_by_uuid(&uuid, &headers, &conn) } #[delete("/ciphers/")] fn delete_cipher(uuid: String, headers: Headers, conn: DbConn) -> EmptyResult { - let cipher = match Cipher::find_by_uuid(&uuid, &conn) { - Some(cipher) => cipher, - None => err!("Cipher doesn't exist") - }; - - if cipher.user_uuid != headers.user.uuid { - err!("Cipher is not owned by user") - } - - // Delete attachments - for a in Attachment::find_by_cipher(&cipher.uuid, &conn) { a.delete(&conn); } - - // Delete cipher - cipher.delete(&conn); - - Ok(()) + _delete_cipher_by_uuid(&uuid, &headers, &conn) } #[post("/ciphers/delete", data = "")] @@ -397,20 +382,9 @@ fn delete_cipher_selected(data: Json, headers: Headers, conn: DbConn) -> }; for uuid in uuids { - let cipher = match Cipher::find_by_uuid(uuid, &conn) { - Some(cipher) => cipher, - None => err!("Cipher doesn't exist") + if let error @ Err(_) = _delete_cipher_by_uuid(uuid, &headers, &conn) { + return error; }; - - if cipher.user_uuid != headers.user.uuid { - err!("Cipher is not owned by user") - } - - // Delete attachments - for a in Attachment::find_by_cipher(&cipher.uuid, &conn) { a.delete(&conn); } - - // Delete cipher - cipher.delete(&conn); } Ok(()) @@ -477,9 +451,7 @@ fn delete_all(data: Json, headers: Headers, conn: DbConn) -> Empty // Delete ciphers and their attachments for cipher in Cipher::find_by_user(&user.uuid, &conn) { - for a in Attachment::find_by_cipher(&cipher.uuid, &conn) { a.delete(&conn); } - - cipher.delete(&conn); + _delete_cipher(cipher, &conn); } // Delete folders @@ -487,3 +459,26 @@ fn delete_all(data: Json, headers: Headers, conn: DbConn) -> Empty Ok(()) } + +fn _delete_cipher_by_uuid(uuid: &str, headers: &Headers, conn: &DbConn) -> EmptyResult { + let cipher = match Cipher::find_by_uuid(uuid, conn) { + Some(cipher) => cipher, + None => err!("Cipher doesn't exist"), + }; + + if cipher.user_uuid != headers.user.uuid { + err!("Cipher is not owned by user") + } + + _delete_cipher(cipher, conn); + + Ok(()) +} + +fn _delete_cipher(cipher: Cipher, conn: &DbConn) { + // Delete the attachments + for a in Attachment::find_by_cipher(&cipher.uuid, &conn) { a.delete(&conn); } + + // Delete the cipher + cipher.delete(conn); +}