authMiddleware.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var config = require('../../server_config/settings.json');
  2. var jwt = require('jwt-simple');
  3. var debug = require('debug')('authMiddleware');
  4. var authMiddleware = function(req, res, next) {
  5. 'use strict';
  6. if (req.path.indexOf('/api/') === 0) {
  7. // Test if it's an authorized key
  8. if (req.headers && req.headers['x-api-key'] && isApiKeyValid(req.headers['x-api-key'])) {
  9. next();
  10. return;
  11. }
  12. // Test if it's an authorized token
  13. if (req.headers && req.headers['x-api-token'] && isTokenValid(req.headers['x-api-token'])) {
  14. next();
  15. return;
  16. }
  17. res.status(401).send('Unauthorized');
  18. }
  19. };
  20. function isApiKeyValid(apiKey) {
  21. return (config.authorizedKeys[apiKey]) ? true : false;
  22. }
  23. function isTokenValid(token) {
  24. var data = null;
  25. try {
  26. data = jwt.decode(token, config.tokenSalt);
  27. } catch(err) {
  28. debug('Error while decoding token');
  29. debug(err);
  30. return false;
  31. }
  32. return data.expire &&
  33. data.expire > Date.now() &&
  34. data.application &&
  35. config.authorizedApplications.indexOf(data.application) >= 0;
  36. }
  37. module.exports = authMiddleware;