forked from dgraziotin/dycapo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication.py
85 lines (65 loc) · 2.92 KB
/
authentication.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Copyright 2010 Daniel Graziotin <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from server.models import Person
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
class HttpBasicAuthentication(object):
"""
A slighty modified version of piston.authentication.HttpBasicAuthentication
Basic HTTP authenticater. Synopsis:
Authentication handlers must implement two methods:
- `is_authenticated`: Will be called when checking for
authentication. Receives a `request` object, please
set your `User` object on `request.user`, otherwise
return False (or something that evaluates to False.)
- `challenge`: In cases where `is_authenticated` returns
False, the result of this method will be returned.
This will usually be a `HttpResponse` object with
some kind of challenge headers and 401 code on it.
"""
def __init__(self):
self.realm = 'Dycapo Server API'
def authenticate(self,username,password):
# checks that the username is valid
try:
user = Person.objects.get(username=username)
except Person.DoesNotExist:
return None
# verifies that the password is valid for the user
if user.check_password(password):
return user
else:
return None
def is_authenticated(self, request):
auth_string = request.META.get('HTTP_AUTHORIZATION', None)
if not auth_string:
return False
try:
(authmeth, auth) = auth_string.split(" ", 1)
if not authmeth.lower() == 'basic':
return False
auth = auth.strip().decode('base64')
(username, password) = auth.split(':', 1)
except (ValueError, binascii.Error):
return False
request.user = self.authenticate(username=username, password=password) \
or AnonymousUser()
request.META['REMOTE_USER'] = request.user.username
return not request.user in (False, None, AnonymousUser())
def challenge(self):
resp = HttpResponse("Authorization Required")
resp['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm
resp.status_code = 401
return resp
def __repr__(self):
return u'<HTTPBasic: realm=%s>' % self.realm