remove unused variable
[mygpo.git] / mygpo / api / basic_auth.py
blob2eab402d72e86d03aa19305495cfcc3391c331e6
2 # This file is part of my.gpodder.org.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
18 from django.http import HttpResponse, HttpResponseBadRequest
19 from django.contrib.auth import authenticate, login
20 from mygpo.log import log
22 #############################################################################
24 def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
25 """
26 This is a helper function used by both 'require_valid_user' and
27 'has_perm_or_basicauth' that does the nitty of determining if they
28 are already logged in or if they have provided proper http-authorization
29 and returning the view if all goes well, otherwise responding with a 401.
30 """
31 if test_func(request.user):
32 # Already logged in, just return the view.
33 return view(request, *args, **kwargs)
35 # They are not logged in. See if they provided login credentials
37 # the AUTHORIZATION header is used when passing auth-headers
38 # from Aapache to fcgi
39 auth = None
40 for h in ('AUTHORIZATION', 'HTTP_AUTHORIZATION'):
41 auth = request.META.get(h, auth)
43 if not auth:
44 return auth_request()
47 auth = auth.split(None, 1)
49 if len(auth) == 2:
50 auth_type, credentials = auth
52 # NOTE: We are only support basic authentication for now.
53 if auth_type.lower() == 'basic':
54 credentials = credentials.decode('base64').split(':', 1)
55 if len(credentials) == 2:
56 uname, passwd = credentials
57 user = authenticate(username=uname, password=passwd)
58 if user is not None and user.is_active:
59 login(request, user)
60 request.user = user
62 return view(request, *args, **kwargs)
64 return auth_request()
67 def auth_request(realm=''):
68 # Either they did not provide an authorization header or
69 # something in the authorization attempt failed. Send a 401
70 # back to them to ask them to authenticate.
71 response = HttpResponse()
72 response.status_code = 401
73 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
74 return response
77 #############################################################################
79 def require_valid_user(protected_view):
80 """
81 A simple decorator that requires a user to be logged in. If they are not
82 logged in the request is examined for a 'authorization' header.
84 If the header is present it is tested for basic authentication and
85 the user is logged in with the provided credentials.
87 If the header is not present a http 401 is sent back to the
88 requestor to provide credentials.
90 The purpose of this is that in several django projects I have needed
91 several specific views that need to support basic authentication, yet the
92 web site as a whole used django's provided authentication.
94 The uses for this are for urls that are access programmatically such as
95 by rss feed readers, yet the view requires a user to be logged in. Many rss
96 readers support supplying the authentication credentials via http basic
97 auth (and they do NOT support a redirect to a form where they post a
98 username/password.)
100 XXX: Fix usage descriptions, ideally provide an example as doctest.
102 def wrapper(request, *args, **kwargs):
103 def check_valid_user(user):
104 return user.is_authenticated()
106 return view_or_basicauth(protected_view, \
107 request, \
108 check_valid_user, \
109 '', \
110 *args, \
111 **kwargs)
112 return wrapper
115 def check_username(protected_view):
117 decorator to check whether the username passed to the view (from the URL)
118 matches the username with which the user is authenticated.
120 def wrapper(request, username, *args, **kwargs):
122 if request.user.username.lower() == username.lower():
123 return protected_view(request, *args, username=username, **kwargs)
125 else:
126 log('username in authentication (%s) and in requested resource (%s) don\'t match' % (request.user.username, username))
127 return HttpResponseBadRequest('username in authentication (%s) and in requested resource (%s) don\'t match' % (request.user.username, username))
129 return wrapper
132 #############################################################################
134 def has_perm_or_basicauth(perm, realm = ""):
136 This is similar to the above decorator 'logged_in_or_basicauth'
137 except that it requires the logged in user to have a specific
138 permission.
140 Use:
142 @logged_in_or_basicauth('asforums.view_forumcollection')
143 def your_view:
147 def view_decorator(func):
148 def wrapper(request, *args, **kwargs):
149 return view_or_basicauth(func, request,
150 lambda u: u.has_perm(perm),
151 realm, *args, **kwargs)
152 return wrapper
153 return view_decorator