添加websocket auth middleware

This commit is contained in:
caoqianming 2023-02-20 09:03:51 +08:00
parent c350c40941
commit 9776ef42cd
1 changed files with 20 additions and 0 deletions

20
apps/utils/middlewares.py Normal file
View File

@ -0,0 +1,20 @@
from rest_framework_simplejwt.authentication import JWTAuthentication
from asgiref.sync import sync_to_async
@sync_to_async
def _get_user(token: str):
jwt = JWTAuthentication()
return jwt.get_user(jwt.get_validated_token(token))
class TokenAuthMiddleware:
def __init__(self, app) -> None:
self.app = app
async def __call__(self, scope, receive, send):
# Look up user from query string (you should also do things like
# checking if it is a valid user ID, or if scope["user"] is already
# populated).
from urllib.parse import parse_qs
token = parse_qs(str(scope["query_string"], 'UTF-8'))['token'][0]
scope['user'] = await _get_user(token)
return await self.app(scope, receive, send)