Remove unused license preamble
[mygpo.git] / mygpo / userfeeds / auth.py
blobcc34c93655a62f57c0edd568420859358561c812
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
18 if token == '':
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']
29 else:
30 return auth_request()
33 auth = auth.split(None, 1)
35 if len(auth) == 2:
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
45 if uname != username:
46 return auth_request()
48 if token == passwd:
49 return view(request, uname, *args, **kwargs)
51 return auth_request()
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
61 return response
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, \
72 request, \
73 username, \
74 token_name, \
75 '', \
76 *args, \
77 **kwargs)
78 return tmp
79 return wrapper