init.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright Epic Games, Inc. All Rights Reserved.
  2. // Adapted from
  3. // * https://blog.risingstack.com/node-hero-node-js-authentication-passport-js/
  4. // * https://github.com/RisingStack/nodehero-authentication/tree/master/app
  5. // * https://github.com/passport/express-4.x-local-example
  6. const passport = require('passport');
  7. const session = require('express-session');
  8. const bcrypt = require('bcryptjs');
  9. const LocalStrategy = require('passport-local').Strategy;
  10. const path = require('path');
  11. const fs = require('fs');
  12. var db = require('./db');
  13. function initPassport (app) {
  14. // Generate session secret if it doesn't already exist and save it to file for use next time
  15. let config = {};
  16. let configPath = path.join(__dirname, './config.json');
  17. if (fs.existsSync(configPath)) {
  18. let content = fs.readFileSync(configPath, 'utf8');
  19. try {
  20. config = JSON.parse(content);
  21. } catch (e) {
  22. console.log(`Error with config file '${configPath}': ${e}`);
  23. }
  24. }
  25. if(!config.sessionSecret){
  26. config.sessionSecret = bcrypt.genSaltSync(12);
  27. let content = JSON.stringify(config);
  28. fs.writeFileSync(configPath, content);
  29. }
  30. // Setup session id settings
  31. app.use(session({
  32. secret: config.sessionSecret,
  33. resave: false,
  34. saveUninitialized: false,
  35. cookie: {
  36. secure: true,
  37. maxAge: 24 * 60 * 60 * 1000 /* 1 day */
  38. //maxAge: 5 * 1000 /* 5 seconds */
  39. }
  40. }));
  41. app.use(passport.initialize());
  42. app.use(passport.session());
  43. passport.serializeUser(function(user, cb) {
  44. cb(null, user.id);
  45. });
  46. passport.deserializeUser(function(id, cb) {
  47. db.users.findById(id, function (err, user) {
  48. if (err) { return cb(err); }
  49. cb(null, user);
  50. });
  51. });
  52. console.log('Setting up auth');
  53. passport.use(new LocalStrategy(
  54. (username, password, callback) => {
  55. db.users.findByUsername(username, (err, user) => {
  56. if (err) {
  57. console.log(`Unable to login '${username}', error ${err}`);
  58. return callback(err);
  59. }
  60. // User not found
  61. if (!user) {
  62. console.log(`User '${username}' not found`);
  63. return callback(null, false);
  64. }
  65. // Always use hashed passwords and fixed time comparison
  66. bcrypt.compare(password, user.passwordHash, (err, isValid) => {
  67. if (err) {
  68. console.log(`Error comparing password for user '${username}': ${err}`);
  69. return callback(err);
  70. }
  71. if (!isValid) {
  72. console.log(`Password incorrect for user '${username}'`)
  73. return callback(null, false);
  74. }
  75. console.log(`User '${username}' logged in`);
  76. return callback(null, user);
  77. });
  78. })
  79. }
  80. ));
  81. passport.authenticationMiddleware = function authenticationMiddleware (redirectUrl) {
  82. return function (req, res, next) {
  83. if (req.isAuthenticated()) {
  84. return next();
  85. }
  86. // Set redirectTo property so that user can be redirected back there after logging in
  87. //console.log(`Original request path '${req.originalUrl}'`);
  88. req.session.redirectTo = req.originalUrl;
  89. res.redirect(redirectUrl);
  90. }
  91. }
  92. }
  93. module.exports = initPassport;