You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.4 KiB

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