public
Created

Google OAuth

  • Download Gist
google oauth
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
var request = require('request');
var events = require('events');
var url = require('url');
var path = require('path');
var crypto = require('crypto');
 
module.exports = function(opts) {
if (!opts.callbackURI) opts.callbackURI = 'google/callback';
if (!opts.loginURI) opts.loginURI = '/google/login';
if (!opts.scope) opts.scope = 'email';
var state = crypto.randomBytes(8).toString('hex');
var urlObj = url.parse(opts.baseURL);
urlObj.pathname = path.join(urlObj.pathname, opts.callbackURI);
var redirectURI = url.format(urlObj);
var emitter = new events.EventEmitter();
 
function login(req, resp) {
var u = 'https://accounts.google.com/o/oauth2/auth?'
+ '&response_type=code'
+ '&client_id=' + opts.googleClient
+ '&redirect_uri=' + redirectURI
+ '&scope=' + opts.scope
+ '&approval_prompt=force&access_type=offline';
resp.statusCode = 302;
resp.setHeader('location', u);
resp.end();
}
 
function callback(req, resp) {
var query = url.parse(req.url, true).query;
var code = query.code;
if (!code) return emitter.emit('error', {error: 'missing oauth code'}, resp);
 
request.post('https://accounts.google.com/o/oauth2/token?code=' + code, { form: {
client_id: opts.googleClient,
client_secret: opts.googleSecret,
scope: '',
redirect_uri: redirectURI,
grant_type: 'authorization_code'
}}, function(err, tokenResp, body) {
if (err) return emitter.emit('error', body, err, resp, tokenResp);
emitter.emit('token', body, resp, tokenResp);
});
}
 
emitter.login = login;
emitter.callback = callback;
// emitter.addRoutes = addRoutes;
return emitter;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.