From 4ba4d10fce4e0c60d770689a448af7cae564688b Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Thu, 25 May 2023 09:42:43 +0200 Subject: [PATCH] Check for duplicate email --- geneit_backend/src/controllers/auth_controller.rs | 15 +++++++++++++-- geneit_backend/src/services/users_service.rs | 12 ++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/geneit_backend/src/controllers/auth_controller.rs b/geneit_backend/src/controllers/auth_controller.rs index be86373..47aa8fc 100644 --- a/geneit_backend/src/controllers/auth_controller.rs +++ b/geneit_backend/src/controllers/auth_controller.rs @@ -29,9 +29,20 @@ pub async fn create_account( return Ok(HttpResponse::BadRequest().json("Size constraints were not respected!")); } - // TODO : check the mail address + // Check if email is already attached to an account + match users_service::exists_email(&req.email).await { + Ok(false) => {} + Ok(true) => { + return Ok(HttpResponse::Conflict() + .json("An account with the same email address already exists!")); + } + Err(e) => { + log::error!("Failed to check email existence! {}", e); + return Err(ErrorInternalServerError(e)); + } + } - // Create the account + // Create the account let user_id = users_service::create_account(&req.name, &req.email) .await .map_err(|e| { diff --git a/geneit_backend/src/services/users_service.rs b/geneit_backend/src/services/users_service.rs index 0e337c7..caed4d0 100644 --- a/geneit_backend/src/services/users_service.rs +++ b/geneit_backend/src/services/users_service.rs @@ -20,3 +20,15 @@ pub async fn create_account(name: &str, email: &str) -> anyhow::Result { Ok(res) }) } + +/// Check if an email address is already associated with an account +pub async fn exists_email(email: &str) -> anyhow::Result { + db_connection::execute(|conn| { + let count: i64 = users::table + .filter(users::email.eq(email)) + .count() + .get_result(conn)?; + + Ok(count != 0) + }) +}