Skip to content

Instantly share code, notes, and snippets.

@kevinswiber
Created February 23, 2016 17:18
Show Gist options
  • Save kevinswiber/4c239771aaa4adec5e17 to your computer and use it in GitHub Desktop.
Save kevinswiber/4c239771aaa4adec5e17 to your computer and use it in GitHub Desktop.
Adding auth to Zetta WebSocket requests
var zetta = require('zetta');
var Photocell = require('zetta-photocell-mock-driver');
zetta()
.use(Photocell)
.use(function(runtime) {
var httpServer = runtime.httpServer.server;
var listener = httpServer.listeners('upgrade')[0];
httpServer.removeListener('upgrade', listener);
httpServer.addListener('upgrade', function(request, socket, headers) {
var forbidden = 'HTTP/1.1 403 Forbidden\r\n\r\n';
var unauthorized =
'HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Bearer\r\n\r\n';
var peerConnectionMatch = /^\/peers\/(.+)$/.exec(request.url);
if (peerConnectionMatch) {
socket.end(forbidden);
return;
}
// do authorization here
if (!request.headers.hasOwnProperty('authorization')) {
socket.end(unauthorized);
} else {
listener(request, socket, headers);
}
});
})
.listen(1337);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment