googleAuth.js 2.0 KB

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