lib/authentication.js

  1. /**
  2. * @file Handle (pseudo-)authentication
  3. * @author Antonio Olmo Titos <a@olmo-titos.info>
  4. * @exports lib/authentication
  5. */
  6. // External packages:
  7. const COOKIE_SESSION = require('cookie-session');
  8. // Internal packages:
  9. const LOGGING = require('./logging');
  10. // Variables:
  11. var ready = false;
  12. /**
  13. * Set up authentication
  14. * @param {Object} app - the <a href="http://expressjs.com/">Express</a> application
  15. */
  16. const setUp = function(app) {
  17. if (ready)
  18. LOGGING.warn(`“authentication.setUp()” called more than once`);
  19. else {
  20. app.set('trust proxy', 1);
  21. app.use(new COOKIE_SESSION({name: 'session', keys: ['key1', 'key2']}));
  22. ready = true;
  23. // Export more stuff:
  24. exports.isKnownUser = isKnownUser;
  25. exports.getUser = getUser;
  26. exports.setUser = setUser;
  27. exports.logOut = logOut;
  28. }
  29. };
  30. /**
  31. * Check if the user is authenticated
  32. * @param {Object} req - Express request
  33. * @returns {Boolean} whether the user is authenticated
  34. */
  35. const isKnownUser = function(req) {
  36. return !!(req && req.session && req.session.user);
  37. };
  38. /**
  39. * Authenticate a user
  40. * @param {Object} req - Express request
  41. * @param {Object} user - user properties (a dictionary)
  42. */
  43. const setUser = function(req, user) {
  44. LOGGING.info(`authenticating user ${user.name}`);
  45. if (req && req.session && req.session.user)
  46. LOGGING.warn(`called “authentication.setUser()” for a session that is already authenticated`);
  47. req.session.user = user;
  48. };
  49. /**
  50. * Get the user that is currently authenticated (if any)
  51. * @param {Object} req - Express request
  52. * @returns {Object} user properties (dictionary) of the user, if any; <code>undefined</code> otherwise
  53. */
  54. const getUser = function(req) {
  55. LOGGING.dir(req.session.user);
  56. return req.session.user;
  57. };
  58. /**
  59. * De-authenticate a user (log them out)
  60. * @param {Object} req - Express request
  61. */
  62. const logOut = function(req) {
  63. if (req && req.session && req.session.user)
  64. delete req.session.user;
  65. };
  66. // Export stuff:
  67. exports.setUp = setUp;