Merge pull request #793 from gpodder/remove-advertise
[mygpo.git] / mygpo / userfeeds / auth.py
blobea7e1a5978b00615f38a441cf26fe434b903270a
1 from functools import wraps
3 from django.http import HttpResponse, HttpResponseBadRequest, Http404
4 from django.shortcuts import get_object_or_404
5 from django.contrib.auth import get_user_model
8 #############################################################################
10 def view_or_basicauth(view, request, username, token_name, realm="", *args, **kwargs):
12 User = get_user_model()
13 user = get_object_or_404(User, username=username)
15 token = getattr(user, token_name, "")
17 # check if a token is required at all
18 if token == "":
19 return view(request, username, *args, **kwargs)
21 # this header format is used when passing auth-headers
22 # from Aapache to fcgi
23 if "AUTHORIZATION" in request.META:
24 auth = request.META["AUTHORIZATION"]
26 elif "HTTP_AUTHORIZATION" in request.META:
27 auth = request.META["HTTP_AUTHORIZATION"]
29 else:
30 return auth_request()
32 auth = auth.split(None, 1)
34 if len(auth) == 2:
35 auth_type, credentials = auth
37 # NOTE: We are only support basic authentication for now.
38 if auth_type.lower() == "basic":
39 credentials = credentials.decode("base64").split(":", 1)
40 if len(credentials) == 2:
42 uname, passwd = credentials
44 if uname != username:
45 return auth_request()
47 if token == passwd:
48 return view(request, uname, *args, **kwargs)
50 return auth_request()
53 def auth_request(realm=""):
54 # Either they did not provide an authorization header or
55 # something in the authorization attempt failed. Send a 401
56 # back to them to ask them to authenticate.
57 response = HttpResponse()
58 response.status_code = 401
59 response["WWW-Authenticate"] = 'Basic realm="%s"' % realm
60 return response
63 #############################################################################
65 def require_token_auth(token_name):
66 def wrapper(protected_view):
67 @wraps(protected_view)
68 def tmp(request, username, *args, **kwargs):
69 return view_or_basicauth(
70 protected_view, request, username, token_name, "", *args, **kwargs
73 return tmp
75 return wrapper