authentication.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const _ = require('lodash')
  2. /* global WIKI */
  3. // ------------------------------------
  4. // OAuth2 Connect 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. }, async (req, accessToken, refreshToken, profile, cb) => {
  18. try {
  19. const user = await WIKI.models.users.processProfile({
  20. providerKey: req.params.strategy,
  21. profile: {
  22. ...profile,
  23. id: _.get(profile, conf.userId),
  24. displayName: _.get(profile, conf.displayName, ''),
  25. email: _.get(profile, conf.emailClaim)
  26. }
  27. })
  28. cb(null, user)
  29. } catch (err) {
  30. cb(err, null)
  31. }
  32. })
  33. client.userProfile = function (accesstoken, done) {
  34. this._oauth2._useAuthorizationHeaderForGET = true;
  35. this._oauth2.get(conf.userInfoURL, accesstoken, (err, data) => {
  36. if (err) {
  37. return done(err)
  38. }
  39. try {
  40. data = JSON.parse(data)
  41. } catch(e) {
  42. return done(e)
  43. }
  44. done(null, data)
  45. })
  46. }
  47. passport.use('oauth2', client)
  48. }
  49. }