authMiddleware.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var config = require('../../../server_config/settings.json');
  2. var debug = require('debug')('authMiddleware');
  3. var authMiddleware = function(req, res, next) {
  4. 'use strict';
  5. if (req.path.indexOf('/api/') === 0) {
  6. if (req.headers && req.headers['x-api-key']) {
  7. // Test if it's an authorized key
  8. if (isApiKeyValid(req.headers['x-api-key'])) {
  9. // Come in!
  10. debug('Authorized key: %s', req.headers['x-api-key']);
  11. res.locals.hasApiKey = true;
  12. } else {
  13. // Sorry :/
  14. debug('Unauthorized key %s', req.headers['x-api-key']);
  15. res.status(401).send('Unauthorized');
  16. return;
  17. }
  18. } else {
  19. debug('No authorization key');
  20. // It's ok for the moment but you might be blocked by the apiLimitsMiddleware, dude
  21. }
  22. }
  23. next();
  24. };
  25. function isApiKeyValid(apiKey) {
  26. return (config.authorizedKeys[apiKey]) ? true : false;
  27. }
  28. module.exports = authMiddleware;