2022-06-21 11:36:55 +03:00
|
|
|
from channels.db import database_sync_to_async
|
|
|
|
from django.core.exceptions import PermissionDenied
|
|
|
|
|
|
|
|
from game.models import Player
|
|
|
|
from game.services.jwt import read_jwt
|
|
|
|
|
|
|
|
|
|
|
|
@database_sync_to_async
|
2022-06-21 20:26:32 +03:00
|
|
|
def get_player(headers):
|
|
|
|
# WARNING headers type is bytes
|
|
|
|
if b"authorization" not in headers or not headers[b"authorization"]:
|
|
|
|
return False
|
|
|
|
|
|
|
|
jwt = headers[b"authorization"].decode()
|
2022-06-21 11:36:55 +03:00
|
|
|
payload = read_jwt(jwt)
|
2022-06-21 20:26:32 +03:00
|
|
|
|
|
|
|
if not payload or "id" not in payload:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return payload["id"]
|
2022-06-21 11:36:55 +03:00
|
|
|
|
|
|
|
|
2022-06-21 20:26:32 +03:00
|
|
|
class HeaderAuthMiddleware:
|
2022-06-21 11:36:55 +03:00
|
|
|
"""Custom middleware to read user auth token from string."""
|
|
|
|
|
|
|
|
def __init__(self, app):
|
|
|
|
# Store the ASGI application we were passed
|
|
|
|
self.app = app
|
|
|
|
|
|
|
|
async def __call__(self, scope, receive, send):
|
2022-06-21 20:26:32 +03:00
|
|
|
scope["player"] = await get_player(dict(scope["headers"]))
|
2022-06-21 11:36:55 +03:00
|
|
|
|
|
|
|
return await self.app(scope, receive, send)
|