27 lines
784 B
Python
27 lines
784 B
Python
# [[file:../localapi.org::*Local API Auth Middleware][Local API Auth Middleware:1]]
|
|
import re
|
|
from django.conf import settings
|
|
from django.http import HttpRequest, JsonResponse
|
|
|
|
def authenticate_request(request: HttpRequest):
|
|
r = re.compile(r'Bearer (\S+)')
|
|
bearer = request.headers.get("Authorization", "")
|
|
match = r.match(bearer)
|
|
if not match:
|
|
return False
|
|
|
|
tok = match.group(1)
|
|
if tok != settings.LOCALAPI_BEARER_TOKEN:
|
|
return False
|
|
|
|
return True
|
|
|
|
def authenticated(func):
|
|
def wrapper(*args, **kwargs):
|
|
request=args[0]
|
|
if not authenticate_request(request):
|
|
return JsonResponse(dict(state="no :("), status=401)
|
|
return func(*args, **kwargs)
|
|
return wrapper
|
|
# Local API Auth Middleware:1 ends here
|