Created
June 28, 2013 00:45
-
-
Save fraserxu/5881632 to your computer and use it in GitHub Desktop.
Google OAuth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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