Skip to content

Commit

Permalink
Delete user using authentication token
Browse files Browse the repository at this point in the history
  • Loading branch information
muntaqamahmood committed Sep 29, 2022
1 parent cecd729 commit 409ebbd
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
21 changes: 21 additions & 0 deletions server/controller/controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const bcrypt = require('bcryptjs');
const jsonwebtoken = require('jsonwebtoken');
const User = require('../models/User');

//http://localhost:8000/api/delete

/*
ROUTE: DELETE api/delete
DESC: Delete a user
ACCESS: Private
*/
//controller to delete a user from the "database"
exports.deleteUser = async (request, response) => {
try {
await User.findByIdAndDelete(request.userID);
response.json({message: "User deleted"});
} catch(error) {
console.log(error.message);
response.json({message: error.message});
}
}
15 changes: 15 additions & 0 deletions server/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,21 @@ const jsonwebtoken = require('jsonwebtoken');
const constants = require('../config/constants.json');
const bcrypt = require('bcryptjs');

const auth = (request, response, next) => {
const token = request.header('x-auth-token');

if(!token){
return response.status(401).json({message: 'No token, authorization denied'});
}
try {
const decoded = jsonwebtoken.verify(token, constants.jsonwebtokenSecret);
request.userID = decoded.userID;
next();
} catch(error) {
response.status(401).json({message: 'Token is not valid'});
}
}

//http://localhost:8000/api/auth

/*
Expand Down
12 changes: 12 additions & 0 deletions server/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const User = require("../models/User");
const jsonwebtoken = require('jsonwebtoken');
const constants = require('../config/constants.json');
const bcrypt = require('bcryptjs');
const auth = require('../routes/auth');
const controller = require('../controller/controller');


//http://localhost:8000/api/users
Expand Down Expand Up @@ -50,4 +52,14 @@ router.post('/', [
}
});

/*
ROUTE: DELETE api/users
DESC: Delete a user
ACCESS: Private
*/
//check controller.js for the delete function
router.delete('/', auth, controller.deleteUser);



module.exports = router;

0 comments on commit 409ebbd

Please sign in to comment.