authentication.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const _ = require('lodash')
  2. /* global WIKI */
  3. // ------------------------------------
  4. // OAuth2 Account
  5. // ------------------------------------
  6. const OAuth2Strategy = require('passport-oauth2').Strategy
  7. module.exports = {
  8. init (passport, conf) {
  9. var client = new OAuth2Strategy({
  10. authorizationURL: conf.authorizationURL,
  11. tokenURL: conf.tokenURL,
  12. clientID: conf.clientId,
  13. clientSecret: conf.clientSecret,
  14. userInfoURL: conf.userInfoURL,
  15. callbackURL: conf.callbackURL,
  16. passReqToCallback: true,
  17. scope: conf.scope,
  18. state: conf.enableCSRFProtection
  19. }, async (req, accessToken, refreshToken, profile, cb) => {
  20. try {
  21. const user = await WIKI.models.users.processProfile({
  22. providerKey: req.params.strategy,
  23. profile: {
  24. ...profile,
  25. id: _.get(profile, conf.userIdClaim),
  26. displayName: _.get(profile, conf.displayNameClaim, '???'),
  27. email: _.get(profile, conf.emailClaim)
  28. }
  29. })
  30. if (conf.mapGroups) {
  31. const groups = _.get(profile, conf.groupsClaim)
  32. if (groups && _.isArray(groups)) {
  33. const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
  34. const expectedGroups = Object.values(WIKI.auth.groups).filter(g => groups.includes(g.name)).map(g => g.id)
  35. for (const groupId of _.difference(expectedGroups, currentGroups)) {
  36. await user.$relatedQuery('groups').relate(groupId)
  37. }
  38. for (const groupId of _.difference(currentGroups, expectedGroups)) {
  39. await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
  40. }
  41. }
  42. }
  43. cb(null, user)
  44. } catch (err) {
  45. cb(err, null)
  46. }
  47. })
  48. client.userProfile = function (accesstoken, done) {
  49. this._oauth2._useAuthorizationHeaderForGET = !conf.useQueryStringForAccessToken
  50. this._oauth2.get(conf.userInfoURL, accesstoken, (err, data) => {
  51. if (err) {
  52. return done(err)
  53. }
  54. try {
  55. data = JSON.parse(data)
  56. } catch (e) {
  57. return done(e)
  58. }
  59. done(null, data)
  60. })
  61. }
  62. passport.use(conf.key, client)
  63. },
  64. logout (conf) {
  65. if (!conf.logoutURL) {
  66. return '/'
  67. } else {
  68. return conf.logoutURL
  69. }
  70. }
  71. }