Skip to content

Commit

Permalink
Added support for rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
kenkendk committed Jul 11, 2015
1 parent 6a98701 commit c598538
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions config-template.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
# Callback URI for OAuth
#OAUTH_CALLBACK_URI = 'https://' + APP_DOMAIN + '/logged-in'

# Sets a limit for how many requests can be performed in
# an hour for a single keyid+ip pair
#RATE_LIMIT = 4

# Conditional setup example:
#if TESTING:
# OAUTH_CALLBACK_URI = 'http://localhost:12080/logged-in'
Expand Down
17 changes: 17 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,23 @@ def get(self):
keyid = authid[:authid.index(':')]
password = authid[authid.index(':')+1:]


if settings.RATE_LIMIT > 0:

ratelimiturl = '/ratelimit?id=' + keyid + '&adr=' + self.request.remote_addr
ratelimit = memcache.get(ratelimiturl)

if ratelimit == None:
memcache.add(key=ratelimiturl, value=1, time=60*60)
elif ratelimit > settings.RATE_LIMIT:
logging.info('Rate limit response to: %s', keyid)
self.response.headers['X-Reason'] = 'Too many request for this key, wait 60 minutes'
self.response.set_status(503, 'Too many request for this key, wait 60 minutes')
return
else:
memcache.incr(ratelimiturl)


cacheurl = '/refresh?id=' + keyid + '&h=' + hashlib.sha256(password).hexdigest()

cached_res = memcache.get(cacheurl)
Expand Down
7 changes: 6 additions & 1 deletion settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
GD_CLIENT_SECRET='XXXXXXXXXXXXXXXXXXXX'
HC_CLIENT_ID='XXXXXXXXXXXXXXXXXXXX'
HC_CLIENT_SECRET='XXXXXXXXXXXXXXXXXXXX'

RATE_LIMIT=0

try:
from config import WL_CLIENT_ID
Expand Down Expand Up @@ -56,6 +56,11 @@
except ImportError:
pass

try:
from config import RATE_LIMIT
except ImportError:
pass

try:
from config import TESTING
except ImportError:
Expand Down

0 comments on commit c598538

Please sign in to comment.