authentication.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }, async (req, iss, uiProfile, idProfile, context, idToken, accessToken, refreshToken, params, cb) => {
  20. const profile = Object.assign({}, idProfile, uiProfile)
  21. try {
  22. const user = await WIKI.models.users.processProfile({
  23. providerKey: req.params.strategy,
  24. profile: {
  25. ...profile,
  26. email: _.get(profile, '_json.' + conf.emailClaim)
  27. }
  28. })
  29. if (conf.mapGroups) {
  30. const groups = _.get(profile, '_json.' + conf.groupsClaim)
  31. if (groups && _.isArray(groups)) {
  32. const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
  33. const expectedGroups = Object.values(WIKI.auth.groups).filter(g => groups.includes(g.name)).map(g => g.id)
  34. for (const groupId of _.difference(expectedGroups, currentGroups)) {
  35. await user.$relatedQuery('groups').relate(groupId)
  36. }
  37. for (const groupId of _.difference(currentGroups, expectedGroups)) {
  38. await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
  39. }
  40. }
  41. }
  42. cb(null, user)
  43. } catch (err) {
  44. cb(err, null)
  45. }
  46. })
  47. )
  48. },
  49. logout (conf) {
  50. if (!conf.logoutURL) {
  51. return '/'
  52. } else {
  53. return conf.logoutURL
  54. }
  55. }
  56. }