Skip to content

Instantly share code, notes, and snippets.

@zhuangh
Forked from emil10001/app_requires.js
Created April 25, 2014 16:52
Show Gist options
  • Save zhuangh/11296042 to your computer and use it in GitHub Desktop.
Save zhuangh/11296042 to your computer and use it in GitHub Desktop.
var googleapis = require('googleapis')
, OAuth2Client = googleapis.OAuth2Client
, config = require('./config.json');
var oauth2Client = new OAuth2Client(config.CLIENT_ID, config.CLIENT_SECRET, config.REDIRECT_URL);
{
"CLIENT_ID" : "YOUR CLIENT ID",
"CLIENT_SECRET" : "YOUR CLIENT SECRET",
"REDIRECT_URL" : "http://example.com/oauth2callback"
}
var success = function(data) { console.log('success',data); }
var failure = function(data) { console.log('failure',data); }
var gotToken = function () {
googleapis
.discover('mirror', 'v1')
.execute(function(err, client) {
if (!!err){
failure();
return;
}
listTimeline(client, failure, success);
insertHello(client, failure, success);
});
};
var grabToken = function (code, errorCallback, successCallback){
oauth2Client.getToken(code, function(err, tokens){
if (!!err){
errorCallback(err);
} else {
console.log('tokens',tokens);
oauth2Client.credentials = tokens;
successCallback();
}
});
};
var insertHello = function(client, errorCallback, successCallback){
client
.mirror.timeline.insert({"text": "Hello world"})
.withAuthClient(oauth2Client)
.execute(function(err, data){
if (!!err)
errorCallback(err);
else
successCallback(data);
});
};
var listTimeline = function(client, errorCallback, successCallback){
client
.mirror.timeline.list()
.withAuthClient(oauth2Client)
.execute(function(err, data){
if (!!err)
errorCallback(err);
else
successCallback(data);
});
};
app.get('/', function(req,res){
if (!oauth2Client.credentials){
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/glass.timeline'
});
res.redirect(url);
} else {
gotToken();
}
res.send('something happened');
res.end();
});
app.get('/oauth2callback', function(req, res){
grabToken(req.query.code, failure, function(){ res.redirect('/'); });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment