Permalink
Browse files

add support for offline access

Basically, 2 additions were made:
1. expose an option to request for offline access
2. save an expiry date to the session so that we could regenerate the access token before it expires.
  • Loading branch information...
ozkatz committed Apr 11, 2013
1 parent 00e8681 commit 1764d423d55c45f323e011f529258dfa7a4ef9d9
Showing with 18 additions and 2 deletions.
  1. +18 −2 lib/auth.strategies/google2.js
@@ -15,6 +15,7 @@ module.exports= function(options, server) {
my._oAuth= new OAuth(options.appId, options.appSecret, "", "https://accounts.google.com/o/oauth2/auth", "https://accounts.google.com/o/oauth2/token");
my._redirectUri= options.callback;
my.scope= options.scope || "https://www.googleapis.com/auth/userinfo.profile";
+ my.accessType = options.accessType || null;
// Ensure we have the correct scopes to match what the consumer really wants.
if( options.requestEmailPermission === true && my.scope.indexOf("auth/userinfo.email") == -1 ) {
@@ -62,14 +63,21 @@ module.exports= function(options, server) {
} else {
self.trace( 'Phase 2/2 : Requesting an OAuth access token.' );
my._oAuth.getOAuthAccessToken(parsedUrl.query.code ,
- {redirect_uri: my._redirectUri, grant_type: 'authorization_code'}, function( error, access_token, refresh_token ){
+ {redirect_uri: my._redirectUri, grant_type: 'authorization_code'}, function( error, access_token, refresh_token, results ){
if( error ) {
self.trace( 'Error retrieving the OAuth Access Token: ' + error );
callback(error)
}
else {
request.session["access_token"]= access_token;
if( refresh_token ) request.session["refresh_token"]= refresh_token;
+ if(!!results.expires_in) {
+ // save the access token's expiration date.
+ // useful for offline access, where we need to regenerate the access token
+ // before it expires (using refresh_token).
+ var now = +new Date();
+ request.session["access_token_expiry"] = now + (parseInt(results.expires_in, 10) * 1000);
+ }
my._oAuth.get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",
access_token,
function(error, profileData){
@@ -88,7 +96,15 @@ module.exports= function(options, server) {
else {
self.trace( 'Phase 1/2 - Redirecting to Google Authorizing url' )
request.session['google2_redirect_url']= request.originalUrl;
- var redirectUrl= my._oAuth.getAuthorizeUrl({redirect_uri : my._redirectUri, scope: my.scope, response_type: 'code' })
+ var urlParams = {
+ redirect_uri : my._redirectUri,
+ scope: my.scope,
+ response_type: 'code'
+ };
+ // support offline access as per https://developers.google.com/accounts/docs/OAuth2WebServer#offline
+ if(my.accessType !== null)
+ urlParams.access_type = my.accessType; // access_type=offline
+ var redirectUrl= my._oAuth.getAuthorizeUrl(urlParams);
self.redirect(response, redirectUrl, callback);
}
}

0 comments on commit 1764d42

Please sign in to comment.