googleAuth.js 2.1 KB

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