authentication.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. }, async (req, accessToken, refreshToken, profile, cb) => {
  19. try {
  20. const user = await WIKI.models.users.processProfile({
  21. providerKey: req.params.strategy,
  22. profile: {
  23. ...profile,
  24. id: _.get(profile, conf.userIdClaim),
  25. displayName: _.get(profile, conf.displayNameClaim, '???'),
  26. email: _.get(profile, conf.emailClaim)
  27. }
  28. })
  29. cb(null, user)
  30. } catch (err) {
  31. cb(err, null)
  32. }
  33. })
  34. client.userProfile = function (accesstoken, done) {
  35. this._oauth2._useAuthorizationHeaderForGET = !conf.useQueryStringForAccessToken
  36. this._oauth2.get(conf.userInfoURL, accesstoken, (err, data) => {
  37. if (err) {
  38. return done(err)
  39. }
  40. try {
  41. data = JSON.parse(data)
  42. } catch (e) {
  43. return done(e)
  44. }
  45. done(null, data)
  46. })
  47. }
  48. passport.use(conf.key, client)
  49. },
  50. logout (conf) {
  51. if (!conf.logoutURL) {
  52. return '/'
  53. } else {
  54. return conf.logoutURL
  55. }
  56. }
  57. }