remove print statement in logo.py
[mygpo.git] / mygpo / userfeeds / auth.py
blobca0a6759bb9fe06d734907f5f8b304065ff6075f
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, Http404
22 from mygpo.users.models import User
25 #############################################################################
27 def view_or_basicauth(view, request, username, token_name, realm = "", *args, **kwargs):
29 user = User.get_user(username)
30 if not user:
31 raise Http404
33 token = getattr(user, token_name, '')
35 # check if a token is required at all
36 if token == '':
37 return view(request, username, *args, **kwargs)
39 # this header format is used when passing auth-headers
40 # from Aapache to fcgi
41 if 'AUTHORIZATION' in request.META:
42 auth = request.META['AUTHORIZATION']
44 elif 'HTTP_AUTHORIZATION' in request.META:
45 auth = request.META['HTTP_AUTHORIZATION']
47 else:
48 return auth_request()
51 auth = auth.split(None, 1)
53 if len(auth) == 2:
54 auth_type, credentials = auth
56 # NOTE: We are only support basic authentication for now.
57 if auth_type.lower() == 'basic':
58 credentials = credentials.decode('base64').split(':', 1)
59 if len(credentials) == 2:
61 uname, passwd = credentials
63 if uname != username:
64 return auth_request()
66 if token == passwd:
67 return view(request, uname, *args, **kwargs)
69 return auth_request()
72 def auth_request(realm=''):
73 # Either they did not provide an authorization header or
74 # something in the authorization attempt failed. Send a 401
75 # back to them to ask them to authenticate.
76 response = HttpResponse()
77 response.status_code = 401
78 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
79 return response
82 #############################################################################
84 def require_token_auth(token_name):
85 def wrapper(protected_view):
87 @wraps(protected_view)
88 def tmp(request, username, *args, **kwargs):
89 return view_or_basicauth(protected_view, \
90 request, \
91 username, \
92 token_name, \
93 '', \
94 *args, \
95 **kwargs)
96 return tmp
97 return wrapper