Example #1
0
function(req, res) {
    console.log("incoming auth " + req.param('code'));
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    var OAuth = require("oauth").OAuth2;
    var oa = new OAuth(appID, appSecret, 'https://graph.facebook.com');

    oa.getOAuthAccessToken(
    req.param('code'),
    {
        redirect_uri: 'http://localhost:3003/auth'
    },
    function(error, access_token, refresh_token) {
        if (error) {
            console.log(error);
            res.end("uhoh " + error);

        } else {
            console.log("a " + access_token + " r " + refresh_token)
            res.end("too legit to quit: " + access_token);
            fs.writeFile("access.token", access_token);
            // Z run validation
            // once validated, exit(0)
        }
    }
    );
});
Example #2
0
                RestAPI.OAuth.createClient(localAdminRestContext, simong.user.id, clientDisplayName, function(err, client) {
                    assert.ok(!err);
                    assert.equal(client.displayName, clientDisplayName);

                    // Setup an OAuth instance with which we can make oauth authenticated http calls
                    var oauth = new OAuth.OAuth2(client.id, client.secret, 'http://' + global.oaeTests.tenants.localhost.host, null, '/api/auth/oauth/v2/token',  null);
                    oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, accessToken, refreshToken, results) {
                        assert.ok(!err);

                        // Assert we retrieved an access token
                        assert.ok(accessToken);

                        // Assert we're not doing token expiration just yet
                        assert.ok(!refreshToken);

                        // Ensure we're outputting OAuth compliant data
                        assert.ok(results['access_token']);
                        assert.equal(results['access_token'], accessToken);

                        // Generate a rest context that authenticates simong via OAuth
                        simong.oauthRestContext = _generateOAuthRestContext(global.oaeTests.tenants.localhost.host, accessToken);

                        return callback(simong, client, accessToken);
                    });
                });
Example #3
0
                TestsUtil.generateTestUsers(localAdminRestContext, 1, function(err, users, simong) {
                    assert.ok(!err);

                    // Assert that using a random Client ID/Secret combination is not sufficient
                    var oauth = new OAuth.OAuth2('Fake ID', 'Fake secret', 'http://' + global.oaeTests.tenants.localhost.host, null, '/api/auth/oauth/v2/token',  null);
                    oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, accessToken, refreshToken, results) {
                        assert.equal(err.statusCode, 401);
                        assert.ok(!accessToken);

                        var clientDisplayName = TestsUtil.generateRandomText(1);
                        RestAPI.OAuth.createClient(localAdminRestContext, simong.user.id, clientDisplayName, function(err, client) {
                            assert.ok(!err);
                            assert.ok(!accessToken);

                            // Assert that just the ID is not sufficient
                            oauth = new OAuth.OAuth2(client.id, 'Fake secret', 'http://' + global.oaeTests.tenants.localhost.host, null, '/api/auth/oauth/v2/token',  null);
                            oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, accessToken, refreshToken, results) {
                                assert.equal(err.statusCode, 401);
                                assert.ok(!accessToken);

                                // Assert that just the secret is not sufficient
                                oauth = new OAuth.OAuth2('Fake ID', client.secret, 'http://' + global.oaeTests.tenants.localhost.host, null, '/api/auth/oauth/v2/token',  null);
                                oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, accessToken, refreshToken, results) {
                                    assert.equal(err.statusCode, 401);
                                    assert.ok(!accessToken);

                                    return callback();
                                });
                            });
                        });
                    });
                });
Example #4
0
	app.get('/tweets', function(req, res) {

var oauth2 = new OAuth2('uRpaaKqj9e4ombt4ZniARqKHW', 'Y8T9NnZrpl0P2lHXLatB7DblSq7nKVtTgrBYnJOdtU9frl2AeD', 'https://api.twitter.com/', null, 'oauth2/token', null);
oauth2.getOAuthAccessToken('', {
    'grant_type': 'client_credentials'
}, function (e, access_token) {
    console.log(access_token); //string that we can use to authenticate request
    
    var query = req.query;

    var options = {
        hostname: 'api.twitter.com',
        path: encodeURI('/1.1/search/tweets.json?q=' + query.q + '&geocode=' + query.geocode + 'km' + '&result_type=recent&count=100'),
        headers: {
            Authorization: 'Bearer ' + access_token
        }
    };

    console.log('AUTHED');

    https.get(options, function (result) {
        var buffer = '';
        result.setEncoding('utf8');
        result.on('data', function (data) {
            buffer += data;
        });
        result.on('end', function () {
            var tweets = JSON.parse(buffer);
        res.send(tweets);
        });
    });
});
	});
Example #5
0
    function refreshAccessToken(callback) {

        if (!refreshToken){
            callback("empty refreshToken");
            return;
        }

        this._clientId = config.clientId;
        this._clientSecret = config.clientSecret;
        this._basePath = '';
        this._authorizePath = 'https://api.netatmo.net/oauth2/authorize';
        this._accessTokenPath = 'https://api.netatmo.net/oauth2/token';

        var oa = new OAuth2(this._clientId, this._clientSecret, this._basePath, this._authorizePath, this._accessTokenPath);

        var data = { grant_type: "refresh_token" };
        oa.getOAuthAccessToken(
            refreshToken,
            data,
            function (error, access_token, refresh_token) {
                if (error) {
                    return callback(error);
                }

                console.log(arguments);
                return callback(null, access_token);
            }
        );

    }
Example #6
0
    function getNewAccessToken(callback) {

        this._clientId = config.clientId;
        this._clientSecret = config.clientSecret;
        this._basePath = '';
        this._authorizePath = 'https://api.netatmo.net/oauth2/authorize';
        this._accessTokenPath = 'https://api.netatmo.net/oauth2/token';

        var oa = new OAuth2(this._clientId, this._clientSecret, this._basePath, this._authorizePath, this._accessTokenPath);

        var data = {
            password : config.password,
            username : config.username,
            grant_type: "password",
            scope : "read_station read_thermostat write_thermostat"
        };

        oa.getOAuthAccessToken(
            '',
            data,
            function (error, access_token, refresh_token) {
                if (error) {
                    return callback(error);
                }

                return callback(null, access_token, refresh_token);
            }
        );
    }
Example #7
0
module.exports = function() {
  var oauth = new OAuth2(process.env.GITHUB_CLIENT_ID, process.env.GITHUB_CLIENT_SECRET, "https://github.com/", "login/oauth/authorize", "login/oauth/access_token");
  return oauth.getAuthorizeUrl({
    redirect_uri: process.env.GITHUB_REDIRECT_URI,
    scope: process.env.GITHUB_SCOPE
  });
}
Example #8
0
			return function(callback, params, accessToken, bypassCache) {
				if (typeof callback !== 'function' || (typeof params !== 'undefined' && typeof params !== 'string')) {
					return false;
				}

				if (apiKey != 'account') {
					apiRequest(apiKey, params, callback, bypassCache);
				}

				if (apiKey == 'account') {
					// Live Data From GW2 Private API
					var url = config.baseUrl + config.api[apiKey].uri

					oauth2 = new OAuth2(
					    "CLIENT-ID",
					    "SECRET-ID",
					    "https://account.guildwars2.com",
					    "/oauth2/authorization",
					    "/oauth2/token"
					);
					oauth2.useAuthorizationHeaderforGET(true);
					oauth2.get(
			            url,
			            accessToken,
			            function(err, body, response) {
			                console.log(JSON.parse(body));
			            }
			        );

					// Have to auth for every type of request
					console.log('f*****g account data');
				};

				return true;
			};
Example #9
0
	callback: function() {

		var self = this,
			req = self.req;
			query = req.url.query;

		req.user.tokens  = {};

		if (query.error || !query.code) {
			//self.failed (query.error_description || "token was not accepted");
			self.completed ({ error : query.error_description || "token was not accepted"});
		}

		var oa = new OAuth2(facebookConfig.appId,  facebookConfig.appSecret,  facebookConfig.baseUrl);

		oa.getOAuthAccessToken(
			query.code,
			{redirect_uri: facebookConfig.callbackUrl},
			function( error, access_token, refresh_token ){

				if (error) {
					self.failed(error);
				} else {

					req.user.tokens.oauth_access_token = access_token;
					if (refresh_token) req.user.tokens.oauth_refresh_token = refresh_token;

					var redirectUrl = (query.action && query.action != "") ? query.action : "/";
					self.completed (redirectUrl)

				}
		});
	},
Example #10
0
   }, function ( error, access_token ) {
   if( !error ) {
     // Enable bearer token authorization for GET requests
     oauth2.useAuthorizationHeaderforGET( true );
     // Call Twitter Search API
     oauth2.get( 'https://api.twitter.com/1.1/search/tweets.json?' + query, access_token, function( error, response ){
       if( !error ) {
         var json_response = JSON.parse( response );
         var statuses = json_response.statuses;
         if( statuses.length > 0 ) {
           var random_number = getRandomInt( 0, statuses.length - 1 );
           var random_tweet = statuses[ random_number ];
           console.log( '@' + random_tweet.user.screen_name + ': ' + random_tweet.text );
           if( !!random_tweet.entities.media ) {
             var all_urls = getUrls( random_tweet.entities.media );
             console.log( 'media:', all_urls );
           }
         }
         else {
           console.error( 'Error occurred. No tweets found for the keyword: ' + keyword );
         }
       }
       else {
         console.error( 'Error occurred while searching for a random tweet. Details: ', error );
       }
     } );
   }
   else {
     console.error( 'Error occured while obtaining the bearer token. Details: ', error );
   }
 });
router.post('/authenticate', jsonParser, function (req, res) {
    var env = req.body.env;
    req.session.env = env;

    // Set keys for LMV module and initialize it
    var configLMV = require("./config-view-and-data")(
        config.baseURL(env),
        config.credentials.consumerKey(env),
        config.credentials.consumerSecret(env)
    );

    lmv = require("view-and-data");
    lmv = new lmv(configLMV);

    var oauth2 = new OAuth2(
        config.credentials.consumerKey(env),
        config.credentials.consumerSecret(env),
        config.baseURL(env),
        config.authenticationUrl,
        config.accessTokenUrl,
        null);

    var authURL = oauth2.getAuthorizeUrl({
        redirect_uri: config.redirectUrl,
        scope: config.scope,
    });

    // this will await the callback
    router.get('/autodesk/callback', function (req, res) {
        oauth2.getOAuthAccessToken(
            req.query.code,
            {
                'grant_type': 'authorization_code',
                'redirect_uri': config.redirectUrl
            },
            function (e, access_token, refresh_token, results) {
                console.log(results);
                if (results) {
                    req.session.oauthcode = access_token;
                    req.session.oauthcode3 = access_token;
                    req.session.cookie.maxAge = parseInt(results.expires_in) * 6000;
                    dm.getUsersMe(req.session.env, req.session.oauthcode, function(data) {
                        // We need this because each users file upload info
                        // will be stored in their "env + userId" named folder
                        req.session.userId = data.userId;
                        console.log("Got userId = " + data.userId);
                        res.end('<script>window.opener.location.reload(false);window.close();</script>');
                        return;
                    });
                } else {
                    res.status(500).end(e.data);
                    return;
                }
            }
        );
    });

    res.end(JSON.stringify(authURL + '&response_type=code'));
});
          topic: function (body) {
            oauth2 = new OAuth2('c67f0160-7aad-4aa5-8a88-92bbd6f02a4c',
              '8638be31-2f91-479d-924a-3742feb17443', '',
              'http://localhost:5000/dialog/authorize',
              'http://localhost:5000/oauth/token');

            oauth2.getOAuthAccessToken(body.code, {
              grant_type: 'authorization_code',
              redirect_uri: 'http://localhost:5000/test/callback'
            }, this.callback);
          },
Example #13
0
app.get('/', function(request, response){
    oa = new oauth.OAuth2(clientId,
        clientSecret,
        "https://accounts.google.com/o",
        "/oauth2/auth",
        "/oauth2/token");
    if(database)
    {
        response.redirect(oa.getAuthorizeUrl({scope:scopes, response_type:'code', redirect_uri:"http://localhost:3000/callback", access_type:'offline',user_id:googleUserId}));

    }
});
Example #14
0
                            oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, accessToken, refreshToken, results) {
                                assert.equal(err.statusCode, 401);
                                assert.ok(!accessToken);

                                // Assert that just the secret is not sufficient
                                oauth = new OAuth.OAuth2('Fake ID', client.secret, 'http://' + global.oaeTests.tenants.localhost.host, null, '/api/auth/oauth/v2/token',  null);
                                oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, accessToken, refreshToken, results) {
                                    assert.equal(err.statusCode, 401);
                                    assert.ok(!accessToken);

                                    return callback();
                                });
                            });
Example #15
0
var twitter_loop = function(event_name, keyword_array){
  clearTimeout(timeout);
  var oauth2 = new OAuth2(access_token_key, access_token_secret, 'https://api.twitter.com/', null, 'oauth2/token', null);
  oauth2.getOAuthAccessToken('',
    {
      'grant_type': 'client_credentials'
    },
    function(e, access_token, args){
      bearer_token = access_token;
      timeout = setTimeout(search_tweets, update_period, event_name, keyword_array);
    }
  );
}
Example #16
0
exp.AirVantageOAuthAccess = function() {

  var oauthAccess = new OAuth2(
    exp.airVantageSettings.CLIENT_ID,
    exp.airVantageSettings.CLIENT_SECRET,
    exp.airVantageSettings.API_ROOT_URL,
    exp.airVantageSettings.AUTH_URL,
    exp.airVantageSettings.TOKEN_URL,
    null
  );

  oauthAccess.useAuthorizationHeaderforGET(true);
  return oauthAccess;
};
Example #17
0
                _setupOAuth(function(simong, client, firstAccessToken) {
                    // When we request a new access token it should be the same as the first one
                    var oauth = new OAuth.OAuth2(client.id, client.secret, 'http://' + global.oaeTests.tenants.localhost.host, null, '/api/auth/oauth/v2/token',  null);
                    oauth.getOAuthAccessToken('', {'grant_type':'client_credentials'}, function (err, newAccessToken, refreshToken, results) {
                        assert.ok(!err);

                        // Assert we retrieved an access token
                        assert.ok(newAccessToken);

                        // Assert that it's the same as the original one
                        assert.equal(firstAccessToken, newAccessToken);

                        return callback();
                    });
                });
 tokenStore.getUserTokens(owner, source, function(error, data) {
   var oauth2 = new OAuth2(data.clientID,  data.accessToken, null, /* Don't need the callback at this point */
       '/oauth/authenticate','/oauth/access_token');
   var facebookUrl = 'https://graph.facebook.com/me/likes?access_token='+  data.accessToken;
   oauth2.get(facebookUrl, data.accessToken , function(error, data) {
     if (error) {
       callback(error, null);
     } else {
       callback( null, {
         'uri': uri,
         'data': data
       });
     }
   });
 });
router.post('/authenticate', jsonParser, function (req, res) {
    var env = req.body.env;
    req.session.env = env;

    // using a NodeJS package for OAuth 2
    // create the object with the information
    var oauth2 = new OAuth2(
        config.credentials.consumerKey(env),
        config.credentials.consumerSecret(env),
        config.baseURL(env),
        config.authenticationUrl,
        config.accessTokenUrl,
        null);

    // this will call /authorize and get the url for user authorization
    var authURL = oauth2.getAuthorizeUrl({
        redirect_uri: config.redirectUrl,
        scope: config.scope,
    });

    // listen for the callback on http://local.host/autodesk/callback (note the endpoint is the same as used above)
    router.get('/autodesk/callback', function (req, res) {
        // this callback will have the 'code'
        // now we finally call /gettoken with this code
        // the NodeJS package handles the call
        oauth2.getOAuthAccessToken(
            req.query.code,
            {
                'grant_type': 'authorization_code',
                'redirect_uri': config.redirectUrl
            },
            function (e, access_token, refresh_token, results) {
                console.log(results);
                // this response will have the access token we need to all
                // calls to ForgeDM endpoints (to read user data), let’s store in session
                req.session.oauthcode = access_token;
                req.session.cookie.maxAge = parseInt(results.expires_in) * 1000 * 60; // same as access_token
                // assuming the login was a popup, let's close it
                res.end('<script>window.opener.location.reload(false);window.close();</script>');
            }
        );
    });

    // respond the original caller with a URL, which can show a popup
    // the user will enter his/her password and Autodesk
    // will redirect to redirectUrl callback (same on Dev Portal)
    res.end(JSON.stringify(authURL + '&response_type=code'));
});
Example #20
0
	searchFriends: function () {
		var self = this;

		var queryTpl = [
			'SELECT username, name',
			'FROM user',
			'WHERE uid IN',
			'(SELECT uid2 FROM friend WHERE uid1 = me())',
			'AND (',
			'strpos(lower(name), "{$filter}") >= 0',
			'OR strpos(lower(username), "{$filter}") >= 0',
			')',
			'ORDER BY name LIMIT {$start}, {$limit}'
		].join(' ');

		var urlTpl = '/fql?q={$query}';

		var query = this.tmpl(queryTpl, this.pager);
		var url = this.tmpl(urlTpl, { query: query });

		var oa = new OAuth2(
			facebookConfig.appId,
			facebookConfig.appSecret,
			facebookConfig.baseUrl
		);

		oa.getProtectedResource(
			facebookConfig.baseUrl + url,
			this.req.user.tokens.oauth_access_token,

			function (error, data, response) {
				var items = JSON.parse(data);

				if (!error) {
					var users = items.data.map(function (user) {
						return self.mapFields(self.mappingUser(user));
					});
				}

				self.completed({
					data: users || null,
					total: users ? users.length : 0,
					success: !error,
					error: error
				});
			}
		);
	},
module.exports = function (facebookKey, facebookSecret) {

    var key = facebookKey,
        secret = facebookSecret;

    var oauth = new OAuth(
        key,
        secret,
        'https://graph.facebook.com',
        null,
        'oauth2/token',
        null
        );

    var getFacebookData = function (userKey, done) {

        oauth.get('https://graph.facebook.com/v2.5/me?fields=picture,email',
            userKey,
            function (err, results, res) {

                results = JSON.parse(results);
                done(results);
            });
    };

    return {
        getFacebookData: getFacebookData
    };
};
Example #22
0
function loginCallback(req,res) {
    oauth.getOAuthAccessToken(req.query.code, {}, function (err, access_token, refresh_token) {
        if (err) {
            console.log(err);
            res.writeHead(500);
            res.end(err + "");
            return;
        }
        req.session.accessToken = access_token;

        github.getAuthedUser(req.session.accessToken).then(function(user) {
            req.session.user = {
                login: user.login,
                avatar_url: user.avatar_url,
                url: user.html_url,
                name: user.name
            };
            res.writeHead(303, {
                Location: req.session.returnPath||"/"
            });
            res.end();
        }).otherwise(function(err) {
            if (err) {
                res.writeHead(err.code);
                res.end(err + "");
            }
        });
    });
}
Example #23
0
var Facebook = function(facebookKey, facebookSecret) {
    var key    = facebookKey;
    var secret = facebookSecret;

    var oauth = new OAuth(
        key,
        secret,
        'http://graph.facebook.com',
        null,
        'oauth2/token',
        null
    );

    // OAuth call to graph api
    var getImage = function(userKey, done) {
        oauth.get(
            'https://graph.facebook.com/v2.3/me/picture?redirect=false&type=large',
            userKey,
            function(err, results, res) {
                results = JSON.parse(results);
                done(results.data);
            }
        );
    }

    return {
        getImage: getImage
    }
}
 router.get('/autodesk/callback', function (req, res) {
     oauth2.getOAuthAccessToken(
         req.query.code,
         {
             'grant_type': 'authorization_code',
             'redirect_uri': config.redirectUrl
         },
         function (e, access_token, refresh_token, results) {
             console.log(results);
             if (results) {
                 req.session.oauthcode = access_token;
                 req.session.oauthcode3 = access_token;
                 req.session.cookie.maxAge = parseInt(results.expires_in) * 6000;
                 dm.getUsersMe(req.session.env, req.session.oauthcode, function(data) {
                     // We need this because each users file upload info
                     // will be stored in their "env + userId" named folder
                     req.session.userId = data.userId;
                     console.log("Got userId = " + data.userId);
                     res.end('<script>window.opener.location.reload(false);window.close();</script>');
                     return;
                 });
             } else {
                 res.status(500).end(e.data);
                 return;
             }
         }
     );
 });
Example #25
0
router.get('/oauth/cb', function(req, res){
  var code = req.query.code;

  console.log(code);

  oauth2.getOAuthAccessToken(
    code,
    { // NOT IN THE UBER DOCS
      grant_type: 'authorization_code',
      redirect_uri: serverUrl+'/api/oauth/cb'
    },
    function (err, access_token, refresh_token, results){
      if(err){
        console.log('err1',err);
        if(err.data){
          res.end(err.data);
        }else{
          console.log('err2');
          res.json(err);
        }
      } else if(results.error) {
        console.log(results.error);
        console.log('err3');

        res.json(results.error);
      } else {
        // got token, send back to client
        // POPUP Blocker must be disabled, or find workaround, or use redirect instead
        console.log('access token', access_token);
        res.redirect(serverUrl+'/#/store-auth-token/'+access_token);
      }
    });
});
Example #26
0
module.exports.twitter = function(congresspersonID, cb){
    oauth2.getOAuthAccessToken('', {
        'grant_type': 'client_credentials'
    }, function (e, access_token) {
     
        var options = {
            hostname: 'api.twitter.com',
            path: '/1.1/statuses/user_timeline.json?screen_name=' + congresspersonID,
            headers: {
                Authorization: 'Bearer ' + access_token
            }
        };
     
     
        https.get(options, function (result) {
            var buffer = '';
            result.setEncoding('utf8');
            result.on('data', function (data) {
                buffer += data;
            });
            result.on('end', function () {
                var tweets = JSON.parse(buffer);
                cb(tweets);
            });
        });
    });
}
Example #27
0
 oauth2.getOAuthAccessToken(code, null, function (err, access_token) {
     if (err) { throw err; }
     oauth2.get(
         'https://api.github.com/user',
         access_token,
         function (err, result) {
             if (err) { throw err; }
             var data = JSON.parse(result);
             data._id = data.name;
             delete data.name;
             delete data.plan;
             model.getCollection('user', function (err, collection) {
                 if (err) { throw err; }
                 collection.findAndModify({ _id: data._id }, [], data, { upsert: true, 'new': true }, function (err, result) {
                     if (err) { throw err; }
                     var redirect = req.session.redirect || '/';
                     delete req.session.redirect;
                     req.session.user = {
                         id: result.id,
                         name: result._id,
                         image: result.avatar_url
                     };
                     res.redirect(redirect);
                 });
             });
         }
     );
 });
Example #28
0
app.use('/oauth', (req, res, next) => {
    oauth2.getOAuthAccessToken(
        '',
        { grant_type: 'client_credentials' },
        () => next()
    );
});
Example #29
0
router.get('/login', function(req, res, next) {
	var p = req.url.split('/');
	var pLen = p.length;
	console.log(pLen);
	console.log(p[1].indexOf('code'))
	
	var authURL = oauth2.getAuthorizeUrl({
		redirect_uri: 'http://localhost:3000/login',
		scope: ['user'],
		state: 'some random string to protect against cross-site request forgery attacks'
	});
	var body = '<a href="' + authURL + '"> Get Code </a>';
	if (pLen === 2 && p[1] === 'login') {
		res.writeHead(200, {
			'Content-Length': body.length,
			'Content-Type': 'text/html' });
		res.end(body);
	} else if (pLen === 2 && p[1].indexOf('code') != -1) {
		/** Github sends auth code so that access_token can be obtained */
		var qsObj = {};
		
		/** To obtain and parse code='...' from code?code='...' */
		qsObj = qs.parse(p[1].split('?')[1]); 
		console.log(qsObj);

		/** Obtaining access_token */
		oauth2.getOAuthAccessToken(
			qsObj.code,
			{'redirect_uri': 'http://localhost:3000/login'},
			function (e, access_token, refresh_token, results){
				if (e) {
					console.log(e);
					res.end(e);
				} else if (results.error) {
					console.log(results);
					res.end(JSON.stringify(results));
				}
				else {
					console.log('Obtained access_token: ', access_token);
					res.end( access_token);
				}
			});

	} else {
        // Unhandled url
    }
});
Example #30
0
 authenticate: function(request, response, username, password, callback) {
     var parsedUrl = url.parse(request.originalUrl, true);
     var self = this;
     if (request.getAuthDetails()['github_login_attempt_failed'] === true) {
         // Because we bounce through authentication calls across multiple requests
         // we use this to keep track of the fact we *Really* have failed to authenticate
         // so that we don't keep re-trying to authenticate forever.
         // (To clarify this infinite retry that we're stopping here would only
         //  occur when the attempt has failed, not when it has succeeded!!!)
         delete request.getAuthDetails()['github_login_attempt_failed'];
         self.fail(callback);
     }
     else {
         if (parsedUrl.query && parsedUrl.query.code) {
             oa.getOAuthAccessToken(parsedUrl.query.code, {
                 redirect_uri: my._redirectUri
             }, function(error, access_token, refresh_token) {
                 if (error) callback(error)
                 else {
                     request.session["access_token"] = access_token;
                     if (refresh_token) request.session["refresh_token"] = refresh_token;
                     oa.getProtectedResource("https://api.github.com/user", request.session["access_token"], function(error, data, response) {
                         if (error) {
                             request.getAuthDetails()['github_login_attempt_failed'] = true;
                             self.fail(callback);
                         }
                         else {
                             self.success(JSON.parse(data), callback)
                         }
                     })
                 }
             });
         }
         else if (parsedUrl.query && parsedUrl.query.error) {
             request.getAuthDetails()['github_login_attempt_failed'] = true;
             self.fail(callback);
         }
         else {
             request.session['github_redirect_url'] = request.originalUrl;
             var redirectUrl = oa.getAuthorizeUrl({
                 redirect_uri: my._redirectUri,
                 scope: my.scope
             })
             self.redirect(response, redirectUrl, callback);
         }
     }
 }