1 from functools
import wraps
3 from django
.http
import HttpResponse
, HttpResponseBadRequest
, Http404
4 from django
.shortcuts
import get_object_or_404
5 from django
.contrib
.auth
import get_user_model
8 #############################################################################
10 def view_or_basicauth(view
, request
, username
, token_name
, realm
= "", *args
, **kwargs
):
12 User
= get_user_model()
13 user
= get_object_or_404(User
, username
=username
)
15 token
= getattr(user
, token_name
, '')
17 # check if a token is required at all
19 return view(request
, username
, *args
, **kwargs
)
21 # this header format is used when passing auth-headers
22 # from Aapache to fcgi
23 if 'AUTHORIZATION' in request
.META
:
24 auth
= request
.META
['AUTHORIZATION']
26 elif 'HTTP_AUTHORIZATION' in request
.META
:
27 auth
= request
.META
['HTTP_AUTHORIZATION']
33 auth
= auth
.split(None, 1)
36 auth_type
, credentials
= auth
38 # NOTE: We are only support basic authentication for now.
39 if auth_type
.lower() == 'basic':
40 credentials
= credentials
.decode('base64').split(':', 1)
41 if len(credentials
) == 2:
43 uname
, passwd
= credentials
49 return view(request
, uname
, *args
, **kwargs
)
54 def auth_request(realm
=''):
55 # Either they did not provide an authorization header or
56 # something in the authorization attempt failed. Send a 401
57 # back to them to ask them to authenticate.
58 response
= HttpResponse()
59 response
.status_code
= 401
60 response
['WWW-Authenticate'] = 'Basic realm="%s"' % realm
64 #############################################################################
66 def require_token_auth(token_name
):
67 def wrapper(protected_view
):
69 @wraps(protected_view
)
70 def tmp(request
, username
, *args
, **kwargs
):
71 return view_or_basicauth(protected_view
, \