Created
March 7, 2016 18:52
-
-
Save kevinswiber/5f9731735a30be437a0e to your computer and use it in GitHub Desktop.
Apply authorization policy to local Zetta client requests, not server-to-server requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var zetta = require('zetta'); | |
var Photocell = require('zetta-photocell-mock-driver'); | |
zetta() | |
.use(Photocell) | |
.use(function(runtime) { | |
// Create an array to store sockets associated | |
// with PeerClient instances. | |
var peerClientSockets = []; | |
// Listen for peer connections and populate | |
// peerClientSockets. | |
runtime.pubsub.subscribe('_peer/connect', function(ev, data) { | |
peerClientSockets.push(data.peer.ws.socket); | |
}); | |
// Clean up peerClientSockets when the peer | |
// disconnects. | |
runtime.pubsub.subscribe('_peer/disconnect', function(ev, data) { | |
var index = peerClients.indexOf(data.peer.ws.socket); | |
if (index !== -1) { | |
peerClientSockets.splice(index, 1); | |
} | |
}); | |
// Function to call for checking local auth. | |
// Replace this with your own implementation. | |
function checkLocalAuth(env, next) { | |
// Check credentials | |
if (env.request.headers['authorization'] === 'test') { | |
// Allow request | |
next(env); | |
return; | |
} | |
// Do not call `next(env)`. | |
// End response with a 401 | |
env.response.statusCode = 401; | |
env.response.end(); | |
} | |
var argo = runtime.httpServer.cloud; | |
argo | |
.use(function(handle) { | |
handle('resource:request:before', function(env, next) { | |
// On SPDY requests, env.request.socket.socket | |
// will be the underlying socket. If this | |
// property doesn't exist, it is a local request | |
// and it should be checked for authorization. | |
if (env.request.socket.socket === undefined) { | |
checkLocalAuth(env, next); | |
return; | |
} | |
// If `env.request.socket.socket` does exist, | |
// it may be a local SPDY request or a | |
// server-to-server request. | |
// Grab the underlying socket for the request. | |
var socket = env.request.socket.socket; | |
// Check if this is a socket for a peer connection. | |
// If there is no match, this is a local request, | |
// not a server-to-server request. | |
if (peerClientSockets.indexOf(socket) === -1) { | |
checkLocalAuth(next, env); | |
return; | |
} | |
next(env); | |
}); | |
}); | |
}) | |
.link('http://localhost:3003') | |
.listen(process.env.PORT || 3004); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 20 should be
peerClientSockets
notpeerClients