1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-18 20:59:44 +02:00
planka/server/api/controllers/users/update-email.js

84 lines
1.6 KiB
JavaScript
Raw Normal View History

const bcrypt = require('bcrypt');
const Errors = {
USER_NOT_FOUND: {
2020-04-03 00:35:25 +05:00
userNotFound: 'User not found',
},
2020-04-03 00:35:25 +05:00
INVALID_CURRENT_PASSWORD: {
invalidCurrentPassword: 'Invalid current password',
},
2020-04-03 00:35:25 +05:00
EMAIL_ALREADY_IN_USE: {
emailAlreadyInUse: 'Email already in use',
},
};
module.exports = {
inputs: {
id: {
type: 'string',
regex: /^[0-9]+$/,
required: true,
},
email: {
type: 'string',
isEmail: true,
required: true,
},
currentPassword: {
type: 'string',
isNotEmptyString: true,
},
},
exits: {
2020-04-03 00:35:25 +05:00
userNotFound: {
responseType: 'notFound',
},
2020-04-03 00:35:25 +05:00
invalidCurrentPassword: {
responseType: 'forbidden',
},
2020-04-03 00:35:25 +05:00
emailAlreadyInUse: {
responseType: 'conflict',
},
},
async fn(inputs, exits) {
const { currentUser } = this.req;
if (inputs.id === currentUser.id) {
if (!inputs.currentPassword) {
2020-04-03 00:35:25 +05:00
throw Errors.INVALID_CURRENT_PASSWORD;
}
} else if (!currentUser.isAdmin) {
throw Errors.USER_NOT_FOUND; // Forbidden
}
let user = await sails.helpers.getUser(inputs.id);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
if (
inputs.id === currentUser.id &&
!bcrypt.compareSync(inputs.currentPassword, user.password)
) {
2020-04-03 00:35:25 +05:00
throw Errors.INVALID_CURRENT_PASSWORD;
}
const values = _.pick(inputs, ['email']);
user = await sails.helpers
.updateUser(user, values, this.req)
2020-04-03 00:35:25 +05:00
.intercept('emailAlreadyInUse', () => Errors.EMAIL_ALREADY_IN_USE);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
return exits.success({
item: user.email,
});
},
};