添加websocket auth middleware
This commit is contained in:
parent
c350c40941
commit
9776ef42cd
|
@ -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)
|
Loading…
Reference in New Issue