Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Created May 27, 2012 21:44
Show Gist options
  • Save nickjacob/2816009 to your computer and use it in GitHub Desktop.
Save nickjacob/2816009 to your computer and use it in GitHub Desktop.
App.js (node.js server) for one-page OAuth flow. See post [here](http://nicholasjacob.com/Javascript/2012/05/27/oauth--websockets-avoiding-the-redirect/)
// App.js
// the main logic of the application.
// this handles pretty much everything that goes on
// author: nickjacob
// generate faux-guid
function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); };
function guid() { return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); };
// actual app
var Express = require('express')
, app = Express.createServer(Express.favicon(),Express.static(__dirname))
, io = require('socket.io').listen(app)
, OhAuth = require('ohauth');
var cK = 'client_key', cS = 'client_secret';
ohAuth = new OhAuth(OhAuth.strategies.twitter(cK,cS,'http://my-app.com'),app);
// users for auth
Users = {};
/** express config **/
app.configure(function(){
app.use(Express.cookieParser());
app.use(Express.bodyParser());
app.use(app.router);
});
// basic express configuration
app.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// lets a socket associate itself with a session
app.get('/register',function(req,res){
req.session.guid = guid();
Users[req.session.guid] = {};
Users[req.session.guid].credentials = req.session.credentials;
res.send(req.session.guid);
});
// this finishes the oauth; done in a separate window.
app.get('/oauth/success',function(req,res){
Users[req.session.guid].credentials = req.session.credentials;
Users[req.session.guid].socket.emit('auth_complete',req.session.credentials);
// the above settings block, now we can claim some success for the user
res.sendfile(__dirname+'/success.html');
});
// socket.io -- connection passes new socket, we bind eventlisteners
io.sockets.on('connection',function(socket){
// this is the second leg of the registration process
socket.on('finish_register',function(guid){
Users[guid].socket = socket;
socket.guid = guid; // both ways
});
});
@nickjacob
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment