[Fix #3] Delete account

develop
sundowndev 2018-11-16 16:43:01 +01:00
parent e9a2da4bd8
commit a6cdbed50d
2 changed files with 62 additions and 3 deletions

View File

@ -1,5 +1,42 @@
module.exports = (req, res) => {
const user = {};
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt-nodejs');
res.status(200).json({ user });
module.exports = (req, res, next) => {
const UserModel = mongoose.model('User');
const { user } = jwt.decode(req.headers.authorization);
return UserModel.findOne({ _id: user.id })
.lean()
.exec()
.then((User) => {
if (User === null) {
return next({ status: 404, message: 'User does not exists.' });
}
return bcrypt.compare(
req.body.password,
User.password,
(error, result) => {
if (!result || error) {
return next({
status: 401,
message: 'Authentication failed. Wrong password.',
});
}
return UserModel.deleteOne({ _id: User._id }, (err) => {
if (err) {
return next({ status: 500 });
}
return res.status(204).json({
success: true,
message: 'Account deleted.',
});
});
},
);
});
};

View File

@ -0,0 +1,22 @@
const Joi = require('joi');
module.exports = (req, res, next) => {
const schema = Joi.object().keys({
password: Joi.string().required(),
});
Joi.validate({
password: req.body.password,
},
schema, (validateErr) => {
if (validateErr) {
return next({
status: 400,
message: 'Form is invalid.',
error: validateErr.details,
});
}
return next();
});
};