|
| 1 | +from django.test import override_settings |
| 2 | +from django_forbid.middleware import ForbidMiddleware |
| 3 | + |
| 4 | +from tests import IP, Header |
| 5 | +from tests import WSGIRequest |
| 6 | + |
| 7 | +wsgi = WSGIRequest() |
| 8 | +request = wsgi.get() |
| 9 | + |
| 10 | + |
| 11 | +def forbids(get_response, request): |
| 12 | + response = ForbidMiddleware(get_response)(request) |
| 13 | + if response.status_code == 302: |
| 14 | + request = wsgi.post({"timezone": "Europe/London"}) |
| 15 | + response = ForbidMiddleware(get_response)(request) |
| 16 | + return response.status_code == 403 |
| 17 | + |
| 18 | + |
| 19 | +def test_should_allow_all_when_no_config_provided(get_response): |
| 20 | + """Should allow access to all users if no config is provided.""" |
| 21 | + for ip_address in IP.all: |
| 22 | + request.META["HTTP_X_FORWARDED_FOR"] = ip_address |
| 23 | + assert not forbids(get_response, request) |
| 24 | + |
| 25 | + |
| 26 | +@override_settings(DJANGO_FORBID={"DEVICES": ["desktop"]}) |
| 27 | +def test_should_allow_users_when_device_is_desktop(get_response): |
| 28 | + """Should allow access to desktop users only.""" |
| 29 | + for user_agent in Header.all_user_agents: |
| 30 | + request.session["DEVICE"] = None |
| 31 | + request.META["HTTP_USER_AGENT"] = user_agent |
| 32 | + if user_agent != Header.user_agent_desktop: |
| 33 | + assert forbids(get_response, request) |
| 34 | + continue |
| 35 | + assert not forbids(get_response, request) |
| 36 | + |
| 37 | + |
| 38 | +@override_settings(DJANGO_FORBID={"TERRITORIES": ["NA"]}) |
| 39 | +def test_should_forbid_users_when_country_in_territories_blacklist(get_response): |
| 40 | + """Should forbid access to users from territories in blacklist.""" |
| 41 | + for ip_address in IP.all: |
| 42 | + request.META["HTTP_X_FORWARDED_FOR"] = ip_address |
| 43 | + if ip_address in [*IP.locals, IP.ip_cobain]: |
| 44 | + assert forbids(get_response, request) |
| 45 | + continue |
| 46 | + assert not forbids(get_response, request) |
| 47 | + |
| 48 | + |
| 49 | +@override_settings(DJANGO_FORBID={"COUNTRIES": ["GB"], "OPTIONS": {"ACTION": "PERMIT", "VPN": True}}) |
| 50 | +def test_should_allow_users_when_country_in_countries_whitelist(get_response): |
| 51 | + for ip_address in IP.all: |
| 52 | + request.META["HTTP_X_FORWARDED_FOR"] = ip_address |
| 53 | + if ip_address == IP.ip_london: |
| 54 | + assert not forbids(get_response, request) |
| 55 | + continue |
| 56 | + assert forbids(get_response, request) |
0 commit comments