From e60bdc7efe247e6b93c7c99b1a44e7147cddbf31 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Sat, 8 May 2021 22:29:41 -0400 Subject: [PATCH] admin: Make invite_user error codes more specific - Return 409 Conflict for when a user with that email already exists - Return 500 InternalServerError for everything else --- src/api/admin.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/api/admin.rs b/src/api/admin.rs index c8eec93a..58be0ff6 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -292,19 +292,24 @@ fn invite_user(data: Json, _token: AdminToken, conn: DbConn) -> Json let data: InviteData = data.into_inner(); let email = data.email.clone(); if User::find_by_mail(&data.email, &conn).is_some() { - err!("User already exists") + err_code!("User already exists", Status::Conflict.code) } let mut user = User::new(email); - if CONFIG.mail_enabled() { - mail::send_invite(&user.email, &user.uuid, None, None, &CONFIG.invitation_org_name(), None)?; - } else { - let invitation = Invitation::new(data.email); - invitation.save(&conn)?; - } + // TODO: After try_blocks is stabilized, this can be made more readable + // See: https://github.com/rust-lang/rust/issues/31436 + (|| { + if CONFIG.mail_enabled() { + mail::send_invite(&user.email, &user.uuid, None, None, &CONFIG.invitation_org_name(), None)?; + } else { + let invitation = Invitation::new(data.email); + invitation.save(&conn)?; + } + + user.save(&conn) + })().map_err(|e| e.with_code(Status::InternalServerError.code))?; - user.save(&conn)?; Ok(Json(user.to_json(&conn))) }