diff --git a/src/core/user.rs b/src/core/user.rs index 9cdf493..f3be97d 100644 --- a/src/core/user.rs +++ b/src/core/user.rs @@ -132,59 +132,42 @@ impl User { pub async fn get_all(mongo_client: &Client) -> Result> { let db = mongo_client.database("auth"); let collection: Collection = db.collection("users"); - let collection_dek: Collection = db.collection("deks"); - // let cursor = collection.find(None, None).await.unwrap(); - let mut cursor_dek = collection_dek.find(None, None).await.unwrap(); + // get all the users + let mut cursor_user = collection.find(None, None).await.unwrap(); let mut users = Vec::new(); - let kek = env::var("SERVER_KEK").expect("Server Kek must be set."); // iterate over the users and decrypt the data - while let Some(dek) = cursor_dek.next().await { - let dek_data: Dek = match dek { - Ok(data) => data.decrypt(&kek), + while let Some(user) = cursor_user.next().await { + let user_data = match user { + Ok(data) => data, Err(_) => { return Err(Error::ServerError { - message: "Failed to get DEK".to_string(), + message: "Failed to get User".to_string(), }); } }; - let encrypted_email_dek = Encryption::encrypt_data(&dek_data.email, &dek_data.dek); - - // find the user in the users collection using the encrypted email to iterate over the users - let cursor_user = collection - .find_one( - Some(doc! { - "email": encrypted_email_dek, - }), - None, - ) - .await - .unwrap(); - - match cursor_user { - Some(user) => { - let user_data = user.decrypt(&dek_data.dek); - - users.push(UserResponse { - name: user_data.name, - email: user_data.email, - role: user_data.role, - created_at: user_data.created_at, - updated_at: user_data.updated_at, - email_verified: user_data.email_verified, - is_active: user_data.is_active, - uid: user_data.uid, - }); + let dek_data = match Dek::get(&mongo_client, &user_data.uid).await { + Ok(dek) => dek, + Err(e) => { + return Err(e); } - None => { - return Err(Error::UserNotFound { - message: "No user found".to_string(), - }); - } - } + }; + + let decrypted_user = user_data.decrypt(&dek_data.dek); + + users.push(UserResponse { + name: decrypted_user.name, + email: decrypted_user.email, + role: decrypted_user.role, + created_at: decrypted_user.created_at, + updated_at: decrypted_user.updated_at, + email_verified: decrypted_user.email_verified, + is_active: decrypted_user.is_active, + uid: decrypted_user.uid, + }); } // sort the users by created_at