Created
July 15, 2016 18:11
-
-
Save frvannes16/d2a34abef73bcd53427f4c32a7291231 to your computer and use it in GitHub Desktop.
Authentication decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def basic_authentication(request): | |
''' | |
Returns LazyUser object if Basic authentication from the GET request can be authenticated. | |
Returns None if it cannot. | |
''' | |
if 'HTTP_AUTHORIZATION' not in request.META and request.user: | |
feed_user = request.user | |
elif 'HTTP_AUTHORIZATION' in request.META: | |
auth_header = request.META.get('HTTP_AUTHORIZATION') | |
# Retrieve credentials | |
encoded_credentials = auth_header.split(' ')[1] | |
username, password = base64.b64decode(encoded_credentials).decode('utf-8').split(':') | |
# Verify credentials | |
feed_user = authenticate(username=username, password=password) | |
else: | |
feed_user = None | |
return feed_user | |
def feed_authorization(authenticated_user, feed_user_username): | |
''' | |
Checks the authorization of the authenticated user acceessing the feed. | |
Args: | |
authenticated_user: (User LazyObject) User that is verfied as having credentials | |
for the website | |
feed_user_username: (str) The username belonging to the owner of the feed. | |
Returns: | |
Product_Feed_User: If the authenticated_user is staff or is otherwise authorized to | |
access this feed. The specified product feed user is returned. | |
HttpResponse: If the authenticated_user is not authorized to access this feed | |
and is not staff. | |
''' | |
if authenticated_user is not None: | |
# Confirmed as site user credentials. | |
# Allows staff to access feed. | |
if authenticated_user.is_staff or authenticated_user.username == feed_user_username: | |
try: | |
product_feed_user = Product_Feed_User.objects \ | |
.get(user__username=feed_user_username) | |
except: | |
return None | |
else: | |
return None | |
return product_feed_user | |
def request_passes_test(test_func): | |
""" | |
Decorator for views that checks that the request passes the given test. | |
The test should be a callable that takes the user object and returns True | |
or an object if the request passes, and None or False if the request fails. | |
""" | |
def decorator(view_func): | |
@wraps(view_func, assigned=available_attrs(view_func)) | |
def _wrapped_view(request, *args, **kwargs): | |
if test_func(request): | |
return view_func(request, *args, **kwargs) | |
else: | |
return HttpResponseForbidden() | |
return _wrapped_view | |
return decorator |
Author
frvannes16
commented
Jul 15, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment