Skip to content

Commit

Permalink
Merge pull request #85 from bloomberg/rate-limit
Browse files Browse the repository at this point in the history
rate limit by user id
  • Loading branch information
fiorda committed Sep 4, 2018
2 parents 6b06a55 + ebf1366 commit 028e65f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
9 changes: 8 additions & 1 deletion pybossa/ratelimit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,15 @@ def get_view_rate_limit():
return getattr(g, '_view_rate_limit', None)


def default_scope_func():
if current_app.config.get('RATE_LIMIT_BY_USER_ID'):
if current_user.is_authenticated():
return current_user.id
return anonymizer.ip(request.remote_addr or '127.0.0.1')


def ratelimit(limit, per, send_x_headers=True,
scope_func=lambda: anonymizer.ip(request.remote_addr or '127.0.0.1'),
scope_func=default_scope_func,
key_func=lambda: request.endpoint,
path=lambda: request.path):
"""
Expand Down
18 changes: 17 additions & 1 deletion test/test_ratelimit.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"""
import json

from default import flask_app, sentinel
from default import flask_app, sentinel, with_context, rebuild_db
from factories import ProjectFactory, UserFactory
from mock import patch

Expand Down Expand Up @@ -138,3 +138,19 @@ def test_05_user_progress(self, mock):

url = '/api/project/1/userprogress'
self.check_limit(url, 'get', 'project')

@with_context
@patch('pybossa.api.api_base.APIBase._db_query')
def test_06_project_get_user_id(self, mock):
"""Test API.project GET rate limit by user id."""
rebuild_db()
mock.return_value = {}
user1 = UserFactory.create(id=500)
user2 = UserFactory.create(id=501)
users = [user1, user2]
url = '/api/project?api_key=%s'
action = 'get'
with patch.dict(flask_app.config, {'RATE_LIMIT_BY_USER_ID': True}):
for user in users:
_url = url % user.api_key
self.check_limit(_url, action, 'project')

0 comments on commit 028e65f

Please sign in to comment.