authentication.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const _ = require('lodash')
  2. // ------------------------------------
  3. // Rocket.chat Account
  4. // ------------------------------------
  5. const OAuth2Strategy = require('passport-oauth2').Strategy
  6. module.exports = {
  7. init (passport, conf) {
  8. const siteURL = conf.siteURL.slice(-1) === '/' ? conf.siteURL.slice(0, -1) : conf.siteURL
  9. OAuth2Strategy.prototype.userProfile = function (accessToken, cb) {
  10. this._oauth2.get(`${siteURL}/api/v1/me`, accessToken, (err, body, res) => {
  11. if (err) {
  12. WIKI.logger.warn('Rocket.chat - Failed to fetch user profile.')
  13. return cb(err)
  14. }
  15. try {
  16. const usr = JSON.parse(body)
  17. cb(null, {
  18. id: usr._id,
  19. displayName: _.isEmpty(usr.name) ? usr.username : usr.name,
  20. email: usr.emails[0].address,
  21. picture: usr.avatarUrl
  22. })
  23. } catch (err) {
  24. WIKI.logger.warn('Rocket.chat - Failed to parse user profile.')
  25. cb(err)
  26. }
  27. })
  28. }
  29. passport.use(conf.key,
  30. new OAuth2Strategy({
  31. authorizationURL: `${siteURL}/oauth/authorize`,
  32. tokenURL: `${siteURL}/oauth/token`,
  33. clientID: conf.clientId,
  34. clientSecret: conf.clientSecret,
  35. callbackURL: conf.callbackURL,
  36. passReqToCallback: true
  37. }, async (req, accessToken, refreshToken, profile, cb) => {
  38. try {
  39. const user = await WIKI.db.users.processProfile({
  40. providerKey: req.params.strategy,
  41. profile
  42. })
  43. cb(null, user)
  44. } catch (err) {
  45. cb(err, null)
  46. }
  47. })
  48. )
  49. },
  50. logout (conf) {
  51. if (!conf.logoutURL) {
  52. return '/'
  53. } else {
  54. return conf.logoutURL
  55. }
  56. }
  57. }