authentication.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const _ = require('lodash')
  2. /* global WIKI */
  3. // ------------------------------------
  4. // OpenID Connect Account
  5. // ------------------------------------
  6. const OpenIDConnectStrategy = require('passport-openidconnect').Strategy
  7. module.exports = {
  8. init (passport, conf) {
  9. passport.use(conf.key,
  10. new OpenIDConnectStrategy({
  11. authorizationURL: conf.authorizationURL,
  12. tokenURL: conf.tokenURL,
  13. clientID: conf.clientId,
  14. clientSecret: conf.clientSecret,
  15. issuer: conf.issuer,
  16. userInfoURL: conf.userInfoURL,
  17. callbackURL: conf.callbackURL,
  18. passReqToCallback: true,
  19. skipUserProfile: conf.skipUserProfile,
  20. acrValues: conf.acrValues
  21. }, async (req, iss, uiProfile, idProfile, context, idToken, accessToken, refreshToken, params, cb) => {
  22. const profile = Object.assign({}, idProfile, uiProfile)
  23. try {
  24. const user = await WIKI.models.users.processProfile({
  25. providerKey: req.params.strategy,
  26. profile: {
  27. ...profile,
  28. email: _.get(profile, '_json.' + conf.emailClaim),
  29. displayName: _.get(profile, '_json.' + conf.displayNameClaim, '')
  30. }
  31. })
  32. if (conf.mapGroups) {
  33. const groups = _.get(profile, '_json.' + conf.groupsClaim)
  34. if (groups && _.isArray(groups)) {
  35. const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
  36. const expectedGroups = Object.values(WIKI.auth.groups).filter(g => groups.includes(g.name)).map(g => g.id)
  37. for (const groupId of _.difference(expectedGroups, currentGroups)) {
  38. await user.$relatedQuery('groups').relate(groupId)
  39. }
  40. for (const groupId of _.difference(currentGroups, expectedGroups)) {
  41. await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
  42. }
  43. }
  44. }
  45. cb(null, user)
  46. } catch (err) {
  47. cb(err, null)
  48. }
  49. })
  50. )
  51. },
  52. logout (conf) {
  53. if (!conf.logoutURL) {
  54. return '/'
  55. } else {
  56. return conf.logoutURL
  57. }
  58. }
  59. }