googleAuth.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const debug = require('debug')('growi:lib:googleAuth');
  2. const urljoin = require('url-join');
  3. const { GoogleApis } = require('googleapis');
  4. /**
  5. * googleAuth utility
  6. */
  7. module.exports = function(crowi) {
  8. const google = new GoogleApis();
  9. const config = crowi.getConfig();
  10. const lib = {};
  11. function createOauth2Client(url) {
  12. return new google.auth.OAuth2(
  13. config.crowi['google:clientId'],
  14. config.crowi['google:clientSecret'],
  15. url,
  16. );
  17. }
  18. lib.createAuthUrl = function(req, callback) {
  19. const callbackUrl = urljoin(crowi.configManager.getSiteUrl(), '/google/callback');
  20. const oauth2Client = createOauth2Client(callbackUrl);
  21. google.options({ auth: oauth2Client });
  22. const redirectUrl = oauth2Client.generateAuthUrl({
  23. access_type: 'offline',
  24. scope: ['profile', 'email'],
  25. });
  26. callback(null, redirectUrl);
  27. };
  28. lib.handleCallback = function(req, callback) {
  29. const callbackUrl = urljoin(crowi.configManager.getSiteUrl(), '/google/callback');
  30. const oauth2Client = createOauth2Client(callbackUrl);
  31. google.options({ auth: oauth2Client });
  32. const code = req.session.googleAuthCode || null;
  33. if (!code) {
  34. return callback(new Error('No code exists.'), null);
  35. }
  36. debug('Request googleToken by auth code', code);
  37. oauth2Client.getToken(code, (err, tokens) => {
  38. debug('Result of google.getToken()', err, tokens);
  39. if (err) {
  40. return callback(new Error('[googleAuth.handleCallback] Error to get token.'), null);
  41. }
  42. oauth2Client.credentials = tokens;
  43. const oauth2 = google.oauth2('v2');
  44. oauth2.userinfo.get({}, (err, response) => {
  45. debug('Response of oauth2.userinfo.get', err, response);
  46. if (err) {
  47. return callback(new Error('[googleAuth.handleCallback] Error while proceccing userinfo.get.'), null);
  48. }
  49. const data = response.data;
  50. data.user_id = data.id; // This is for B.C. (tokeninfo をつかっている前提のコードに対してのもの)
  51. return callback(null, data);
  52. });
  53. });
  54. };
  55. return lib;
  56. };