Skip to content

@fraserxu /google oauth
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Google OAuth
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.