@wraps for all decorators
[mygpo.git] / mygpo / api / basic_auth.py
blob5b737edd0de43dc25e74a0cc005bcf17624ae12a
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 functools import wraps
20 from django.http import HttpResponse, HttpResponseBadRequest
21 from django.contrib.auth import authenticate, login
22 from mygpo.log import log
24 #############################################################################
26 def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
27 """
28 This is a helper function used by both 'require_valid_user' and
29 'has_perm_or_basicauth' that does the nitty of determining if they
30 are already logged in or if they have provided proper http-authorization
31 and returning the view if all goes well, otherwise responding with a 401.
32 """
33 if test_func(request.user):
34 # Already logged in, just return the view.
35 return view(request, *args, **kwargs)
37 # They are not logged in. See if they provided login credentials
39 # the AUTHORIZATION header is used when passing auth-headers
40 # from Aapache to fcgi
41 auth = None
42 for h in ('AUTHORIZATION', 'HTTP_AUTHORIZATION'):
43 auth = request.META.get(h, auth)
45 if not auth:
46 return auth_request()
49 auth = auth.split(None, 1)
51 if len(auth) == 2:
52 auth_type, credentials = auth
54 # NOTE: We are only support basic authentication for now.
55 if auth_type.lower() == 'basic':
56 credentials = credentials.decode('base64').split(':', 1)
57 if len(credentials) == 2:
58 uname, passwd = credentials
59 user = authenticate(username=uname, password=passwd)
60 if user is not None and user.is_active:
61 login(request, user)
62 request.user = user
64 return view(request, *args, **kwargs)
66 return auth_request()
69 def auth_request(realm=''):
70 # Either they did not provide an authorization header or
71 # something in the authorization attempt failed. Send a 401
72 # back to them to ask them to authenticate.
73 response = HttpResponse()
74 response.status_code = 401
75 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
76 return response
79 #############################################################################
81 def require_valid_user(protected_view):
82 """
83 A simple decorator that requires a user to be logged in. If they are not
84 logged in the request is examined for a 'authorization' header.
86 If the header is present it is tested for basic authentication and
87 the user is logged in with the provided credentials.
89 If the header is not present a http 401 is sent back to the
90 requestor to provide credentials.
92 The purpose of this is that in several django projects I have needed
93 several specific views that need to support basic authentication, yet the
94 web site as a whole used django's provided authentication.
96 The uses for this are for urls that are access programmatically such as
97 by rss feed readers, yet the view requires a user to be logged in. Many rss
98 readers support supplying the authentication credentials via http basic
99 auth (and they do NOT support a redirect to a form where they post a
100 username/password.)
102 XXX: Fix usage descriptions, ideally provide an example as doctest.
104 @wraps(protected_view)
105 def wrapper(request, *args, **kwargs):
106 def check_valid_user(user):
107 return user.is_authenticated()
109 return view_or_basicauth(protected_view, \
110 request, \
111 check_valid_user, \
112 '', \
113 *args, \
114 **kwargs)
115 return wrapper
118 def check_username(protected_view):
120 decorator to check whether the username passed to the view (from the URL)
121 matches the username with which the user is authenticated.
123 @wraps(protected_view)
124 def wrapper(request, username, *args, **kwargs):
126 if request.user.username.lower() == username.lower():
127 return protected_view(request, *args, username=username, **kwargs)
129 else:
130 log('username in authentication (%s) and in requested resource (%s) don\'t match' % (request.user.username, username))
131 return HttpResponseBadRequest('username in authentication (%s) and in requested resource (%s) don\'t match' % (request.user.username, username))
133 return wrapper
136 #############################################################################
138 def has_perm_or_basicauth(perm, realm = ""):
140 This is similar to the above decorator 'logged_in_or_basicauth'
141 except that it requires the logged in user to have a specific
142 permission.
144 Use:
146 @logged_in_or_basicauth('asforums.view_forumcollection')
147 def your_view:
151 def view_decorator(func):
152 @wraps(func)
153 def wrapper(request, *args, **kwargs):
154 return view_or_basicauth(func, request,
155 lambda u: u.has_perm(perm),
156 realm, *args, **kwargs)
157 return wrapper
158 return view_decorator