-
Notifications
You must be signed in to change notification settings - Fork 19
/
utils.py
62 lines (52 loc) · 2.03 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Do not modify this file. It is generated from the Swagger specification.
If you need to tweak the functionality in this file, you can replace it
with your own.
"""
import base64
import json
from functools import wraps
import jsonschema
from django.contrib.auth import authenticate, login
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponse
def body_to_dict(body, schema):
# type: (str, Dict) -> Dict
"""
:param body: The body content
:param schema: The expected JSONSchema
:return: A dictionary containing the parsed body
:raises SuspiciousOperation: If the body is not in JSON format, or does not
conform to the specified schema.
"""
try:
data = json.loads(body)
jsonschema.validate(data, schema=schema)
return data
except Exception as e:
# The SuspiciousOperation exception will result in an
# HttpResponseBadRequest response.
raise SuspiciousOperation(e)
def login_required_no_redirect(view_func):
"""
Helper function that returns an HTTP 401 response if the user making the
request is not logged in, or did not provide basic HTTP authentication in
the request.
"""
@wraps(view_func)
def wrapper(request, *args, **kwargs):
if request.user.is_authenticated:
return view_func(request, *args, **kwargs)
if "HTTP_AUTHORIZATION" in request.META:
auth = request.META["HTTP_AUTHORIZATION"].split()
if len(auth) == 2:
# NOTE: We are only support basic authentication for now.
if auth[0].lower() == "basic":
uname, passwd = base64.b64decode(auth[1]).split(":")
user = authenticate(username=uname, password=passwd)
if user and user.is_active:
login(request, user)
request.user = user
return view_func(request, *args, **kwargs)
return HttpResponse("Unauthorized", status=401)
return wrapper