96 lines
2.5 KiB
JavaScript
96 lines
2.5 KiB
JavaScript
let sanitize = require('mongo-sanitize');
|
|
let db = global['requireModule']('database');
|
|
let crypto = require('crypto');
|
|
let auth = global['requireModule']('auth');
|
|
|
|
module.exports = {
|
|
path: "/settings",
|
|
/**
|
|
* update user
|
|
* @TODO add implementation
|
|
* @url /api/settings
|
|
* @method POST
|
|
* @POST ['email', 'password', 'repassword', 'mfa']
|
|
*/
|
|
post: async (req, res) => {
|
|
// if user is not logged in; FAIL
|
|
if(!req.session || !req.session.user) {
|
|
return res.type('json').end(JSON.stringify({
|
|
status: 401,
|
|
message: 'msg.auth.logout.required'
|
|
}));
|
|
}
|
|
|
|
// check body variables
|
|
if(
|
|
!(
|
|
(req.body.email) ||
|
|
(req.body.password && req.body.repassword) ||
|
|
(req.body.mfa)
|
|
)
|
|
) {
|
|
return res.type('json').status(401).end(JSON.stringify({
|
|
status: 401,
|
|
message: 'msg.request.data.missing'
|
|
}));
|
|
}
|
|
|
|
user = await db.getUser(req.session.user.id);
|
|
// if database error
|
|
if(user.err) {
|
|
// log error while debugging
|
|
global['logs'].debug(user.err);
|
|
|
|
// query failed because of database error
|
|
return res.type('json').status(500).end(JSON.stringify({
|
|
status: 500,
|
|
message: 'msg.database.error'
|
|
}));
|
|
}
|
|
|
|
obj = {};
|
|
if(req.body.email) obj.email = sanitize(req.body.email);
|
|
if(req.body.password && req.body.repassword) {
|
|
password = sanitize(req.body.password);
|
|
repassword = sanitize(req.body.repassword);
|
|
if(password.length == repassword.length && crypto.timingSafeEqual(
|
|
Buffer.from(password, 'hex'),
|
|
Buffer.from(repassword, 'hex')
|
|
)) {
|
|
obj.passhash = auth.generateHash(password);
|
|
} else {
|
|
return res.type('json').status(400).end(JSON.stringify({status: 400, message: "msg.request.data.missing"}));
|
|
}
|
|
}
|
|
|
|
// empty obj, do not update
|
|
if(Object.keys(obj).length === 0 && obj.constructor === Object) {
|
|
return res.type('json').status(400).end(JSON.stringify({status: 400, message: "msg.request.data.missing"}));
|
|
}
|
|
update = await db.updateUser(user.reply._id, obj);
|
|
// if database error
|
|
if(update.err) {
|
|
// log error while debugging
|
|
global['logs'].debug(update.err);
|
|
|
|
// update failed because of database error
|
|
return res.type('json').status(500).end(JSON.stringify({
|
|
status: 500,
|
|
message: 'msg.database.error'
|
|
}));
|
|
}
|
|
else if(update.reply) {
|
|
console.log(obj);
|
|
return res.type('json').end(JSON.stringify({
|
|
status: 200,
|
|
message: 'msg.settings.update.successful'
|
|
}));
|
|
}
|
|
|
|
return res.type('json').end(JSON.stringify({
|
|
status: 401,
|
|
message: 'msg.auth.logout.required'
|
|
}));
|
|
}
|
|
};
|