remove unused imports of get_main_database
[mygpo.git] / mygpo / userfeeds / auth.py
blob8328623509beabebdc01ee47ce1153e4df2cbb16
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
23 from mygpo.log import log
26 #############################################################################
28 def view_or_basicauth(view, request, username, token_name, realm = "", *args, **kwargs):
30 user = User.get_user(username)
31 if not user:
32 raise Http404
34 token = getattr(user, token_name, '')
36 # check if a token is required at all
37 if token == '':
38 return view(request, username, *args, **kwargs)
40 # this header format is used when passing auth-headers
41 # from Aapache to fcgi
42 if 'AUTHORIZATION' in request.META:
43 auth = request.META['AUTHORIZATION']
45 elif 'HTTP_AUTHORIZATION' in request.META:
46 auth = request.META['HTTP_AUTHORIZATION']
48 else:
49 return auth_request()
52 auth = auth.split(None, 1)
54 if len(auth) == 2:
55 auth_type, credentials = auth
57 # NOTE: We are only support basic authentication for now.
58 if auth_type.lower() == 'basic':
59 credentials = credentials.decode('base64').split(':', 1)
60 if len(credentials) == 2:
62 uname, passwd = credentials
64 if uname != username:
65 return auth_request()
67 if token == passwd:
68 return view(request, uname, *args, **kwargs)
70 return auth_request()
73 def auth_request(realm=''):
74 # Either they did not provide an authorization header or
75 # something in the authorization attempt failed. Send a 401
76 # back to them to ask them to authenticate.
77 response = HttpResponse()
78 response.status_code = 401
79 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
80 return response
83 #############################################################################
85 def require_token_auth(token_name):
86 def wrapper(protected_view):
88 @wraps(protected_view)
89 def tmp(request, username, *args, **kwargs):
90 return view_or_basicauth(protected_view, \
91 request, \
92 username, \
93 token_name, \
94 '', \
95 *args, \
96 **kwargs)
97 return tmp
98 return wrapper