diff --git a/server/controller/controller.js b/server/controller/controller.js new file mode 100644 index 0000000..ca14f7e --- /dev/null +++ b/server/controller/controller.js @@ -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}); + } +} \ No newline at end of file diff --git a/server/routes/auth.js b/server/routes/auth.js index 33aa63a..8ea925f 100644 --- a/server/routes/auth.js +++ b/server/routes/auth.js @@ -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 /* diff --git a/server/routes/users.js b/server/routes/users.js index 3fb88a0..4b8d564 100644 --- a/server/routes/users.js +++ b/server/routes/users.js @@ -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 @@ -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;