2
0

googleAuth.js 1.9 KB

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