Created
September 13, 2012 19:51
-
-
Save naxhh/3717119 to your computer and use it in GitHub Desktop.
Throttle APP ID based on APP public token
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
| /** | |
| * This is based on the idea you have an authorization class done with: | |
| * auth.getToken to generate a token based on a ID and a password | |
| * auth.checkToken to validate this token (returning the ID of the app to use in req.username) | |
| * | |
| * NOTES: | |
| * I use a redis loader to set redis instance in res.locals | |
| * | |
| * I set burst and rate to 1 to easy check the override and the system working | |
| */ | |
| var restify = require('restify'), | |
| auth = require('./libs/auth.js'), | |
| redis = require('./libs/redis.js'), | |
| server = restify.createServer({ | |
| name : 'tolstoy.eu API', | |
| version : '0.0.1' | |
| }); | |
| server.use(restify.queryParser()); | |
| server.use(redis.load); //load redis to res.locals.redis | |
| //Generate a token or ERROR! | |
| server.get({path:'/getToken/:appID/:secret'}, function(req,res,next) { | |
| auth.getToken(req.params.appID, req.params.secret, res.locals.redis, function(err, token) { | |
| if (typeof err != 'undefined') | |
| res.send({err:"login"}); //invalid login | |
| else | |
| res.send({token:token}); //send token to the user | |
| }); | |
| }); | |
| //Check API authorization! | |
| server.use(function(req, res, next) { | |
| if (typeof req.params.token == 'undefined' ) { | |
| res.send({err:"login"}); return; //no token? go to hell | |
| } | |
| auth.checkToken(req.params.token, res.locals.redis, function(err, appID) { | |
| if (typeof err != 'undefined') | |
| res.send({err:"login"}); | |
| else { | |
| req.username = appID; //Set req.username as APP id to throttle count | |
| next(); | |
| } | |
| }); | |
| }); | |
| //All from here needs Authorization | |
| //Check Throttle | |
| server.use( | |
| restify.throttle({ | |
| burst: 1, | |
| rate: 1, | |
| username: true, | |
| overrides: { | |
| 1 : {burst:10, rate:10} | |
| } | |
| })); | |
| //Server Routes | |
| require('./routes')(server); | |
| server.listen(8080, function() { | |
| console.log('%s listening at %s', server.name, server.url); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment