auth.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const passport = require('passport')
  2. const fs = require('fs-extra')
  3. const _ = require('lodash')
  4. const path = require('path')
  5. const NodeCache = require('node-cache')
  6. const userCache = new NodeCache({
  7. stdTTL: 10,
  8. checkperiod: 600,
  9. deleteOnExpire: true
  10. })
  11. /* global WIKI */
  12. module.exports = {
  13. strategies: {},
  14. init() {
  15. this.passport = passport
  16. // Serialization user methods
  17. passport.serializeUser(function (user, done) {
  18. done(null, user.id)
  19. })
  20. passport.deserializeUser(function (id, done) {
  21. const usr = userCache.get(id)
  22. if (usr) {
  23. done(null, usr)
  24. } else {
  25. WIKI.models.users.query().findById(id).then((user) => {
  26. if (user) {
  27. userCache.set(id, user)
  28. done(null, user)
  29. } else {
  30. done(new Error(WIKI.lang.t('auth:errors:usernotfound')), null)
  31. }
  32. return true
  33. }).catch((err) => {
  34. done(err, null)
  35. })
  36. }
  37. })
  38. return this
  39. },
  40. async activateStrategies() {
  41. try {
  42. // Unload any active strategies
  43. WIKI.auth.strategies = {}
  44. const currentStrategies = _.keys(passport._strategies)
  45. _.pull(currentStrategies, 'session')
  46. _.forEach(currentStrategies, stg => { passport.unuse(stg) })
  47. // Load enabled strategies
  48. const enabledStrategies = await WIKI.models.authentication.getStrategies()
  49. for (let idx in enabledStrategies) {
  50. const stg = enabledStrategies[idx]
  51. if (!stg.isEnabled) { continue }
  52. const strategy = require(`../modules/authentication/${stg.key}/authentication.js`)
  53. stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback` // TODO: config.host
  54. strategy.init(passport, stg.config)
  55. fs.readFile(path.join(WIKI.ROOTPATH, `assets/svg/auth-icon-${strategy.key}.svg`), 'utf8').then(iconData => {
  56. strategy.icon = iconData
  57. }).catch(err => {
  58. if (err.code === 'ENOENT') {
  59. strategy.icon = '[missing icon]'
  60. } else {
  61. WIKI.logger.warn(err)
  62. }
  63. })
  64. WIKI.auth.strategies[stg.key] = strategy
  65. WIKI.logger.info(`Authentication Strategy ${stg.title}: [ OK ]`)
  66. }
  67. } catch (err) {
  68. WIKI.logger.error(`Authentication Strategy: [ FAILED ]`)
  69. WIKI.logger.error(err)
  70. }
  71. }
  72. }