Advertisement
Guest User

Untitled

a guest
Nov 10th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. from functools import wraps
  2.  
  3. def basic_auth_required(func):
  4. @wraps(func)
  5. def _decorator(request, *args, **kwargs):
  6.     from django.conf import settings
  7.     from django.core.exceptions import PermissionDenied
  8.     from django.http import HttpResponse
  9.     from newjazzwebservice import NewJazzConnector
  10.     import base64, binascii
  11.     HTTP_HEADER_ENCODING = 'iso-8859-1'
  12.     if request.META.has_key('HTTP_AUTHORIZATION'):
  13.         auth = request.META['HTTP_AUTHORIZATION'].split()
  14.         if not auth or auth[0].lower() != b'basic':
  15.             return None
  16.  
  17.         if len(auth) == 1:
  18.             # 'Invalid basic header. No credentials provided.'
  19.             raise PermissionDenied
  20.         elif len(auth) > 2:
  21.             # 'Invalid basic header. Credentials string should not contain spaces.'
  22.             raise PermissionDenied
  23.  
  24.         try:
  25.             auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
  26.         except (TypeError, UnicodeDecodeError, binascii.Error):
  27.             # 'Invalid basic header. Credentials not correctly base64 encoded.'
  28.             raise PermissionDenied
  29.  
  30.         userid, password = auth_parts[0], auth_parts[2]
  31.  
  32.         nwjz = NewJazzConnector(userid, password, settings.ENTORNO_NJ)
  33.         valid_user = nwjz.authenticate()
  34.  
  35.         if valid_user:
  36.             return func(request, *args, **kwargs)
  37.         else:
  38.             return PermissionDenied
  39.     res = HttpResponse()
  40.     res.status_code = 401
  41.     res['WWW-Authenticate'] = 'Basic'
  42.     return res
  43. return _decorator
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement