Permalink
Browse files

added ratelimit() middleware

  • Loading branch information...
1 parent f961275 commit 6d10315b6f4efda38c1eda7589dd898f4b09edcf @tj tj committed Dec 18, 2011
Showing with 39 additions and 1 deletion.
  1. +37 −0 lib/ratelimit.js
  2. +2 −1 routes.js
View
@@ -0,0 +1,37 @@
+
+var db = app.db;
+
+/**
+ * Limit `max` requests per 10 minutes.
+ *
+ * @param {Number} max
+ * @return {Function}
+ */
+
+module.exports = function(max){
+ var min = 60
+ , ttl = min * 10;
+
+ return function(req, res, next){
+ var addr = req.socket.remoteAddress;
+ var key = 'limit:' + addr;
+ res.set('X-Ratelimit-Max', max);
+
+ db.get(key, function(err, n){
+ if (err) return next(err);
+
+ if (n > max) {
+ var wait = ttl / min;
+ res.set('X-Ratelimit', n);
+ res.send(400, 'Limit exceeded! try again in ~' + wait + ' minutes\n');
+ } else if (n) {
+ res.set('X-Ratelimit', n);
+ db.incr(key, next);
+ } else {
+ res.set('X-Ratelimit', 0);
+ db.incr(key);
+ db.expire(key, ttl, next);
+ }
+ });
+ }
+};
View
@@ -1,5 +1,6 @@
var rasterize = require('./lib/rasterize')
+ , ratelimit = require('./lib/ratelimit')
, utils = require('./lib/utils')
, path = require('path')
, join = path.join
@@ -37,7 +38,7 @@ app.get('/', function(req, res, next){
* GET stats.
*/
-app.get('/stats', function(req, res){
+app.get('/stats', ratelimit(10), function(req, res){
db.hgetall('screenshot:stats', function(err, obj){
if (err) return next(err);
res.send(obj);

0 comments on commit 6d10315

Please sign in to comment.