[Publisher] incorrect number of new/existing publisher permissions
[mygpo.git] / mygpo / api / basic_auth.py
blob1a4896f7ae1053b27e493d6aa29d2a31b8a3f832
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
23 import logging
24 logger = logging.getLogger(__name__)
28 #############################################################################
30 def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
31 """
32 This is a helper function used by both 'require_valid_user' and
33 'has_perm_or_basicauth' that does the nitty of determining if they
34 are already logged in or if they have provided proper http-authorization
35 and returning the view if all goes well, otherwise responding with a 401.
36 """
37 if test_func(request.user):
38 # Already logged in, just return the view.
39 return view(request, *args, **kwargs)
41 # They are not logged in. See if they provided login credentials
43 # the AUTHORIZATION header is used when passing auth-headers
44 # from Aapache to fcgi
45 auth = None
46 for h in ('AUTHORIZATION', 'HTTP_AUTHORIZATION'):
47 auth = request.META.get(h, auth)
49 if not auth:
50 return auth_request()
53 auth = auth.split(None, 1)
55 if len(auth) == 2:
56 auth_type, credentials = auth
58 # NOTE: We are only support basic authentication for now.
59 if auth_type.lower() == 'basic':
60 try:
61 credentials = credentials.decode('base64').split(':', 1)
63 except UnicodeDecodeError as e:
64 return HttpResponseBadRequest(
65 'Could not decode credentials: {msg}'.format(msg=str(e)))
67 if len(credentials) == 2:
68 uname, passwd = credentials
69 user = authenticate(username=uname, password=passwd)
70 if user is not None and user.is_active:
71 login(request, user)
72 request.user = user
74 return view(request, *args, **kwargs)
76 return auth_request()
79 def auth_request(realm=''):
80 # Either they did not provide an authorization header or
81 # something in the authorization attempt failed. Send a 401
82 # back to them to ask them to authenticate.
83 response = HttpResponse()
84 response.status_code = 401
85 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
86 return response
89 #############################################################################
91 def require_valid_user(protected_view):
92 """
93 A simple decorator that requires a user to be logged in. If they are not
94 logged in the request is examined for a 'authorization' header.
96 If the header is present it is tested for basic authentication and
97 the user is logged in with the provided credentials.
99 If the header is not present a http 401 is sent back to the
100 requestor to provide credentials.
102 The purpose of this is that in several django projects I have needed
103 several specific views that need to support basic authentication, yet the
104 web site as a whole used django's provided authentication.
106 The uses for this are for urls that are access programmatically such as
107 by rss feed readers, yet the view requires a user to be logged in. Many rss
108 readers support supplying the authentication credentials via http basic
109 auth (and they do NOT support a redirect to a form where they post a
110 username/password.)
112 XXX: Fix usage descriptions, ideally provide an example as doctest.
114 @wraps(protected_view)
115 def wrapper(request, *args, **kwargs):
116 def check_valid_user(user):
117 return user.is_authenticated()
119 return view_or_basicauth(protected_view, \
120 request, \
121 check_valid_user, \
122 '', \
123 *args, \
124 **kwargs)
125 return wrapper
128 def check_username(protected_view):
130 decorator to check whether the username passed to the view (from the URL)
131 matches the username with which the user is authenticated.
133 @wraps(protected_view)
134 def wrapper(request, username, *args, **kwargs):
136 if request.user.username.lower() == username.lower():
137 return protected_view(request, *args, username=username, **kwargs)
139 else:
140 # TODO: raise SuspiciousOperation here?
141 logger.warn('username in authentication (%s) and in requested resource (%s) don\'t match' % (request.user.username, username))
142 return HttpResponseBadRequest('username in authentication (%s) and in requested resource (%s) don\'t match' % (request.user.username, username))
144 return wrapper
147 #############################################################################
149 def has_perm_or_basicauth(perm, realm = ""):
151 This is similar to the above decorator 'logged_in_or_basicauth'
152 except that it requires the logged in user to have a specific
153 permission.
155 Use:
157 @logged_in_or_basicauth('asforums.view_forumcollection')
158 def your_view:
162 def view_decorator(func):
163 @wraps(func)
164 def wrapper(request, *args, **kwargs):
165 return view_or_basicauth(func, request,
166 lambda u: u.has_perm(perm),
167 realm, *args, **kwargs)
168 return wrapper
169 return view_decorator