googleAuth.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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')('crowi: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. response.user_id = response.id; // This is for B.C. (tokeninfo をつかっている前提のコードに対してのもの)
  50. return callback(null, response);
  51. });
  52. });
  53. };
  54. return lib;
  55. };