I am writing a small node.js web application that requires the Google API and uses OAuth2 as the authentication mechanism. I noticed something peculiar when requesting the access tokens - the "code" that is received after allowing access changes type from an object to a string. The response type is logged after "OAuth in the building."
Sorry if this is a duplicate question.
routes:
handle['/connect'] = requestHandlers.connect;
handle['/oauth2callback'] = requestHandlers.oauth;
router:
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function'){
handle[pathname](response);
if (pathname === '/oauth2callback'){
handle[pathname](query);
}
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
handlers:
function connect(response){
console.log("Request Handler 'start' was called.");
auth.access(response);
}
function oauth(response){
console.log("OAuth in the building. This is the instance: ");
if(typeof response !== 'undefined'){
if(typeof response == "string"){
var code = response.split("code=").pop();
auth.exchange(code);
}else {
console.log("This response isn't ready until it is a string. It has these values: " + Object.getPrototypeOf(response));
}
}
}
authentication:
function getAccess(response){
var url = authClient.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly'
});
console.log("[Auth.js] This is the response received: " + Object.keys(response));
response.writeHead(302,{
"Location":url
});
response.end();
}
function exchangeToken(code){
authClient.getToken(code,function(err,tokens){
console.log("We got some tokens! " + tokens);
});
console.log("Authorized");
}
