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
)
33 token
= getattr(user
, token_name
, '')
35 # check if a token is required at all
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']
51 auth
= auth
.split(None, 1)
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
67 return view(request
, uname
, *args
, **kwargs
)
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
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
, \