chess_rpg_backend/game/authentication.py

36 lines
1.1 KiB
Python
Raw Normal View History

from jwt import DecodeError
2022-06-05 13:09:27 +03:00
from rest_framework import authentication
from rest_framework import exceptions
from .models import Player
from .services.jwt import read_jwt
class PlayerAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
2022-06-05 21:28:20 +03:00
2022-06-06 20:15:45 +03:00
if "Authorization" not in request.headers or not (
token := request.headers["Authorization"]
):
2022-06-05 13:09:27 +03:00
raise exceptions.AuthenticationFailed("No credentials provided.")
try:
t = read_jwt(token)
except DecodeError:
raise exceptions.AuthenticationFailed("Token is incorrect")
2022-06-05 13:09:27 +03:00
if not t:
raise exceptions.AuthenticationFailed("Token is incorrect of expired")
if "id" not in t and "type" not in t:
2022-06-05 13:09:27 +03:00
raise exceptions.AuthenticationFailed("No user data")
if t["type"] != "access":
raise exceptions.AuthenticationFailed("Incorrect token type")
2022-06-05 13:09:27 +03:00
try:
user = Player.objects.get(id=int(t["id"]))
except Player.DoesNotExist:
raise exceptions.AuthenticationFailed("No such user")
return user, None