const utils = require('../../../utils');
const bcrypt = require('bcrypt');
module.exports = {
post: {
"username": function(req, res) {
utils.validate.keys(req.body, [
'username'
]).then(function() {
req.body.username = req.body.username.trim();
if (!req.body.username) {
return Promise.reject("Could not update username: Username cannot be empty");
}
return utils.query("UPDATE users" + utils.set_where({
username: req.body.username
}, {
user_id: req.user.user_id
})).catch(utils.handle_err.sql(res));
}).then(function(result) {
res.send(utils.ok({
message: result.changedRows ? "Username Updated" : "Username Unchanged"
}));
}).catch(utils.handle_err.res(res, "Could not update username"));
},
"password": function(req, res) {
utils.validate.keys(req.body, [
'current_password',
['new_password', utils.validate.password, "New password not strong enough"]
]).then(function() {
if (utils.validate.password(req.body.new_password)) {
return bcrypt.compare(req.body.current_password, req.user.password);
}
return utils.reject("New password not good enough");
}).then(function(passwords_match) {
if (passwords_match) {
return bcrypt.hash(req.body.new_password, 10);
}
return utils.reject("Current password incorrect");
}).then(function(hashword) {
return utils.query("UPDATE users" + utils.set_where({
password: hashword
}, {
user_id: req.user.user_id
})).catch(utils.handle_err.sql(res));
}).then(function(result) {
res.send(utils.ok({
message: result.changedRows ? "Password Updated" : "Password Unchanged"
}));
}).catch(utils.handle_err.res(res, "Could not update password"));
}
}
}