adminGuard.js 1.1KB

12345678910111213141516171819202122232425262728293031
  1. /* Guard that only allows admins to access whatever route the guard is attached to */
  2. var jwt = require('jsonwebtoken');
  3. var config = require('../config');
  4. exports.adminGuard = function (req, res, next) {
  5. //Check for a token in the body, params or headers
  6. var token = req.body.token || req.query.token || req.headers['x-access-token'];
  7. //Check that a token was actually supplied
  8. if (token) {
  9. //Now check that the token is actually legitimate
  10. jwt.verify(token, config.secretKey, function (err, decoded) {
  11. //If there was an error during the verification, the user is not authenticated
  12. if (err)
  13. return res.status(403).send({success: false, error: "Failed to authenticate token."});
  14. //Otherwise, the user is valid
  15. else {
  16. req.decoded = decoded;
  17. next();
  18. }
  19. });
  20. }
  21. //Otherwise, do not proceed and send back an error
  22. else {
  23. return res.status(403).send({success: false, error: "No token provided in request."});
  24. }
  25. };