rename/move filters, validate_doc_update
[mygpo.git] / mygpo / userfeeds / auth.py
blob46c2293bb18a5a2d39baae4d7ea51442d831d7c3
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 try:
69 return view(request, uname, *args, **kwargs)
70 except Exception, e:
71 log(repr(e))
72 return HttpResponseBadRequest(e)
74 return auth_request()
77 def auth_request(realm=''):
78 # Either they did not provide an authorization header or
79 # something in the authorization attempt failed. Send a 401
80 # back to them to ask them to authenticate.
81 response = HttpResponse()
82 response.status_code = 401
83 response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
84 return response
87 #############################################################################
89 def require_token_auth(token_name):
90 def wrapper(protected_view):
92 @wraps(protected_view)
93 def tmp(request, username, *args, **kwargs):
94 return view_or_basicauth(protected_view, \
95 request, \
96 username, \
97 token_name, \
98 '', \
99 *args, \
100 **kwargs)
101 return tmp
102 return wrapper