fargo/fargo/oauth2/utils.py

53 lines
1.8 KiB
Python

import cgi
from django.utils import six
from django.utils.http import unquote
from django.utils.timezone import now
from django.conf import settings
from .models import OAuth2Authorize
def authenticate_bearer(request):
authorization = request.META.get('HTTP_AUTHORIZATION')
if not authorization:
return False
splitted = authorization.split()
if len(splitted) < 2:
return False
if splitted[0] != 'Bearer':
return False
token = splitted[1]
try:
authorize = OAuth2Authorize.objects.get(access_token=token)
if (now() - authorize.creation_date).total_seconds() > settings.FARGO_ACCESS_TOKEN_LIFETIME:
return False
return authorize
except OAuth2Authorize.DoesNotExist:
return False
def get_content_disposition_value(request):
if 'HTTP_CONTENT_DISPOSITION' not in request.META:
return None, 'missing content-disposition header'
content_header = request.META['HTTP_CONTENT_DISPOSITION']
disposition_type, filename = cgi.parse_header(content_header)
if disposition_type != 'attachment':
return None, 'wrong disposition type: attachment expected'
if 'filename*' in filename:
encode, country, name = filename['filename*'].split("'")
if six.PY3:
return (unquote(name, encode), None)
# check accepted charset from rfc 5987
if encode == 'UTF-8':
return unquote(name).decode('utf8'), None
elif encode == 'ISO-8859-1':
return unquote(name).decode('iso-8859-1'), None
else:
return None, 'unknown encoding: UTF-8 or ISO-8859-1 allowed'
elif 'filename' in filename:
return filename['filename'], None
else:
# no filename in header
return None, 'missing filename(*) parameter in header'