diff --git a/constants/error.constant.js b/constants/error.constant.js index 06ab069d..f2e6c535 100644 --- a/constants/error.constant.js +++ b/constants/error.constant.js @@ -9,6 +9,7 @@ const VOLUNTEER_404_MESSAGE = "Volunteer not found"; const SETTINGS_404_MESSAGE = "Settings not found"; const ACCOUNT_TYPE_409_MESSAGE = "Wrong account type"; +const ACCOUNT_EMAIL_409_MESSAGE = "Email already in use"; const SPONSOR_ID_409_MESSAGE = "Conflict with sponsor accountId link"; const VOLUNTEER_ID_409_MESSAGE = "Conflict with volunteer accountId link"; const HACKER_ID_409_MESSAGE = "Conflict with hacker accountId link"; @@ -50,6 +51,7 @@ module.exports = { TEAM_404_MESSAGE: TEAM_404_MESSAGE, RESUME_404_MESSAGE: RESUME_404_MESSAGE, ACCOUNT_TYPE_409_MESSAGE: ACCOUNT_TYPE_409_MESSAGE, + ACCOUNT_EMAIL_409_MESSAGE: ACCOUNT_EMAIL_409_MESSAGE, SPONSOR_ID_409_MESSAGE: SPONSOR_ID_409_MESSAGE, VOLUNTEER_ID_409_MESSAGE: VOLUNTEER_ID_409_MESSAGE, TEAM_MEMBER_409_MESSAGE: TEAM_MEMBER_409_MESSAGE, diff --git a/middlewares/account.middleware.js b/middlewares/account.middleware.js index bea0e578..4d333afb 100644 --- a/middlewares/account.middleware.js +++ b/middlewares/account.middleware.js @@ -156,6 +156,24 @@ async function addAccount(req, res, next) { return next(); } +/** + * @async + * @function validateUniqueEmail + * @param {{params:{id: string}, body: {email: string}}} req + * @param {*} res + * @description Gets an account by email in req.body, and if found ensures id matches req.params.id + */ +async function validateUniqueEmail(req, res, next) { + const acc = await Services.Account.findByEmail(req.body.email); + if (acc && acc.id != req.params.id) { + return next({ + status: 409, + message: Constants.Error.ACCOUNT_EMAIL_409_MESSAGE, + }); + } + return next(); +} + /** * Updates an account that is specified by req.params.id * @param {{params:{id: string}, body: *}} req @@ -254,5 +272,6 @@ module.exports = { updatePassword: Middleware.Util.asyncMiddleware(updatePassword), addAccount: Middleware.Util.asyncMiddleware(addAccount), updateAccount: Middleware.Util.asyncMiddleware(updateAccount), - inviteAccount: Middleware.Util.asyncMiddleware(inviteAccount) + inviteAccount: Middleware.Util.asyncMiddleware(inviteAccount), + validateUniqueEmail: Middleware.Util.asyncMiddleware(validateUniqueEmail) }; diff --git a/routes/api/account.js b/routes/api/account.js index dfa7c802..6f7cc559 100644 --- a/routes/api/account.js +++ b/routes/api/account.js @@ -21,7 +21,7 @@ const Services = { }; module.exports = { - activate: function(apiRouter) { + activate: function (apiRouter) { const accountRouter = express.Router(); /** @@ -252,6 +252,7 @@ module.exports = { Middleware.parseBody.middleware, Middleware.Account.parsePatch, + Middleware.Account.validateUniqueEmail, Middleware.Account.updateAccount, Middleware.Auth.sendConfirmAccountEmail, // no parse account because will use req.body as information