authentication.js 1.7 KB

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