authentication.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const _ = require('lodash')
  2. // ------------------------------------
  3. // OAuth2 Account
  4. // ------------------------------------
  5. const OAuth2Strategy = require('passport-oauth2').Strategy
  6. module.exports = {
  7. init (passport, conf) {
  8. var client = new OAuth2Strategy({
  9. authorizationURL: conf.authorizationURL,
  10. tokenURL: conf.tokenURL,
  11. clientID: conf.clientId,
  12. clientSecret: conf.clientSecret,
  13. userInfoURL: conf.userInfoURL,
  14. callbackURL: conf.callbackURL,
  15. passReqToCallback: true,
  16. scope: conf.scope
  17. }, async (req, accessToken, refreshToken, profile, cb) => {
  18. try {
  19. const user = await WIKI.db.users.processProfile({
  20. providerKey: req.params.strategy,
  21. profile: {
  22. ...profile,
  23. id: _.get(profile, conf.userIdClaim),
  24. displayName: _.get(profile, conf.displayNameClaim, '???'),
  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 = !conf.useQueryStringForAccessToken
  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(conf.key, client)
  48. },
  49. logout (conf) {
  50. if (!conf.logoutURL) {
  51. return '/'
  52. } else {
  53. return conf.logoutURL
  54. }
  55. }
  56. }