Handle tokens for deleted users

This commit is contained in:
Peter Vacho 2024-12-31 14:49:15 +01:00
parent bb943c8e7e
commit a276399e59
Signed by: school
GPG key ID: 8CFC3837052871B4

View file

@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta
from enum import StrEnum from enum import StrEnum
from typing import Literal, NotRequired, TypedDict, cast, final from typing import Literal, NotRequired, TypedDict, cast, final
from beanie import Link
from jose import JWTError, jwt from jose import JWTError, jwt
from src.db.models import user from src.db.models import user
@ -34,6 +35,7 @@ class AuthErrState(StrEnum):
EXPIRED = "The provided token is expired." EXPIRED = "The provided token is expired."
UNTRACKED = "The provided token isn't tracked by the server" UNTRACKED = "The provided token isn't tracked by the server"
REVOKED = "The provided token was revoked" REVOKED = "The provided token was revoked"
NO_USER = "The provided token doesn't have a user linked to it"
@final @final
@ -123,6 +125,13 @@ async def resolve_jwt_token(token: str) -> tuple[TokenData, Token]:
# We'll definitely end up needing the user, so we might as well fetch it now # We'll definitely end up needing the user, so we might as well fetch it now
await db_token.fetch_link(Token.user) await db_token.fetch_link(Token.user)
# If we still get a link here, it means the user was deleted
# this shouldn't happen though, as with a user deletion, their tokens should
# also be deleted. Nevertheless, let's check it for sanity.
if isinstance(db_token.user, Link):
log.error(f"Got a token of a deleted user: {token=!r} user_id={db_token.user.ref.id!r}")
raise InvalidTokenError(AuthErrState.NO_USER, token)
return decoded, db_token return decoded, db_token