googleAuth.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * googleAuth utility
  3. */
  4. module.exports = function(config) {
  5. 'use strict';
  6. const { GoogleApis } = require('googleapis');
  7. var google = new GoogleApis()
  8. , debug = require('debug')('growi:lib:googleAuth')
  9. , lib = {}
  10. ;
  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. var callbackUrl = config.crowi['app:url'] + '/google/callback';
  20. var oauth2Client = createOauth2Client(callbackUrl);
  21. google.options({auth: oauth2Client});
  22. var redirectUrl = oauth2Client.generateAuthUrl({
  23. access_type: 'offline',
  24. scope: ['profile', 'email'],
  25. });
  26. callback(null, redirectUrl);
  27. };
  28. lib.handleCallback = function(req, callback) {
  29. var callbackUrl = config.crowi['app:url'] + '/google/callback';
  30. var oauth2Client = createOauth2Client(callbackUrl);
  31. google.options({auth: oauth2Client});
  32. var 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, function(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. var oauth2 = google.oauth2('v2');
  44. oauth2.userinfo.get({}, function(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. let 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. };