authentication.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. cb(null, user)
  31. } catch (err) {
  32. cb(err, null)
  33. }
  34. })
  35. client.userProfile = function (accesstoken, done) {
  36. this._oauth2._useAuthorizationHeaderForGET = !conf.useQueryStringForAccessToken
  37. this._oauth2.get(conf.userInfoURL, accesstoken, (err, data) => {
  38. if (err) {
  39. return done(err)
  40. }
  41. try {
  42. data = JSON.parse(data)
  43. } catch (e) {
  44. return done(e)
  45. }
  46. done(null, data)
  47. })
  48. }
  49. passport.use(conf.key, client)
  50. },
  51. logout (conf) {
  52. if (!conf.logoutURL) {
  53. return '/'
  54. } else {
  55. return conf.logoutURL
  56. }
  57. }
  58. }