2019-10-18 08:06:34 +05:00
|
|
|
const bcrypt = require('bcrypt');
|
|
|
|
|
|
|
|
const Errors = {
|
|
|
|
USER_NOT_FOUND: {
|
2019-11-05 18:01:42 +05:00
|
|
|
notFound: 'User is not found',
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
CURRENT_PASSWORD_NOT_VALID: {
|
2019-11-05 18:01:42 +05:00
|
|
|
forbidden: 'Current password is not valid',
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
USER_EXIST: {
|
2019-11-05 18:01:42 +05:00
|
|
|
conflict: 'User is already exist',
|
|
|
|
},
|
2019-10-18 08:06:34 +05:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
inputs: {
|
|
|
|
id: {
|
|
|
|
type: 'string',
|
|
|
|
regex: /^[0-9]+$/,
|
2019-11-05 18:01:42 +05:00
|
|
|
required: true,
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
email: {
|
|
|
|
type: 'string',
|
|
|
|
isEmail: true,
|
2019-11-05 18:01:42 +05:00
|
|
|
required: true,
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
currentPassword: {
|
|
|
|
type: 'string',
|
2019-11-05 18:01:42 +05:00
|
|
|
isNotEmptyString: true,
|
|
|
|
},
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
|
|
|
|
exits: {
|
|
|
|
notFound: {
|
2019-11-05 18:01:42 +05:00
|
|
|
responseType: 'notFound',
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
forbidden: {
|
2019-11-05 18:01:42 +05:00
|
|
|
responseType: 'forbidden',
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
conflict: {
|
2019-11-05 18:01:42 +05:00
|
|
|
responseType: 'conflict',
|
|
|
|
},
|
2019-10-18 08:06:34 +05:00
|
|
|
},
|
|
|
|
|
2019-11-05 18:01:42 +05:00
|
|
|
async fn(inputs, exits) {
|
2019-10-18 08:06:34 +05:00
|
|
|
const { currentUser } = this.req;
|
|
|
|
|
|
|
|
if (inputs.id === currentUser.id) {
|
|
|
|
if (!inputs.currentPassword) {
|
|
|
|
throw Errors.CURRENT_PASSWORD_NOT_VALID;
|
|
|
|
}
|
|
|
|
} 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 (
|
2019-11-05 18:01:42 +05:00
|
|
|
inputs.id === currentUser.id
|
|
|
|
&& !bcrypt.compareSync(inputs.currentPassword, user.password)
|
2019-10-18 08:06:34 +05:00
|
|
|
) {
|
|
|
|
throw Errors.CURRENT_PASSWORD_NOT_VALID;
|
|
|
|
}
|
|
|
|
|
|
|
|
const values = _.pick(inputs, ['email']);
|
|
|
|
|
|
|
|
user = await sails.helpers
|
|
|
|
.updateUser(user, values, this.req)
|
|
|
|
.intercept('conflict', () => Errors.USER_EXIST);
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
throw Errors.USER_NOT_FOUND;
|
|
|
|
}
|
|
|
|
|
|
|
|
return exits.success({
|
2019-11-05 18:01:42 +05:00
|
|
|
item: user.email,
|
2019-10-18 08:06:34 +05:00
|
|
|
});
|
2019-11-05 18:01:42 +05:00
|
|
|
},
|
2019-10-18 08:06:34 +05:00
|
|
|
};
|