|
2 | 2 | from functools import wraps |
3 | 3 | from django.contrib.auth import authenticate |
4 | 4 | from django.http import HttpResponse, HttpResponseForbidden |
| 5 | +from django.conf import settings |
5 | 6 | from base64 import b64decode |
6 | 7 |
|
7 | 8 |
|
8 | 9 | def basic_auth_required(realm='default'): |
9 | 10 | def _helper(func): |
10 | 11 | @wraps(func) |
11 | 12 | def _decorator(request, *args, **kwargs): |
12 | | - if 'HTTP_AUTHORIZATION' in request.META: |
| 13 | + allowed = False |
| 14 | + if settings.ALLOW_ANONYMOUS_POST: |
| 15 | + allowed = True |
| 16 | + elif 'HTTP_AUTHORIZATION' in request.META: |
13 | 17 | http_auth = request.META['HTTP_AUTHORIZATION'] |
14 | 18 | authmeth, auth = http_auth.split(' ', 1) |
15 | 19 | if authmeth.lower() == 'basic': |
16 | 20 | authb = b64decode(auth.strip()) |
17 | 21 | auth = authb.decode() |
18 | 22 | username, password = auth.split(':', 1) |
19 | 23 | user = authenticate(username=username, password=password) |
20 | | - if user is not None: |
| 24 | + if user is None: |
21 | 25 | logging.info( |
22 | 26 | 'Authentication succeeded for {}'.format(username)) |
23 | | - return func(request, *args, **kwargs) |
| 27 | + allowed = True |
24 | 28 | else: |
25 | 29 | return HttpResponseForbidden() |
| 30 | + if allowed: |
| 31 | + return func(request, *args, **kwargs) |
26 | 32 | res = HttpResponse() |
27 | 33 | res.status_code = 401 |
28 | 34 | res.reason_phrase = 'Unauthorized' |
|
0 commit comments