2
0

authentication.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }, 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.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 = 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. logout (conf) {
  50. if (!conf.logoutURL) {
  51. return '/'
  52. } else {
  53. return conf.logoutURL
  54. }
  55. }
  56. }