2023-08-14 02:08:08 +08:00
|
|
|
import logging
|
2023-11-22 21:52:18 +08:00
|
|
|
from typing import Annotated
|
2023-08-14 02:08:08 +08:00
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
from fastapi import Depends
|
2023-11-22 17:13:16 +08:00
|
|
|
from fastapi.security import OAuth2PasswordBearer
|
2023-09-12 18:45:22 +08:00
|
|
|
from graphql import GraphQLError
|
|
|
|
from jose import jwt
|
|
|
|
from pydantic import ValidationError
|
2023-11-22 21:52:18 +08:00
|
|
|
from strawberry.fastapi import BaseContext
|
2023-09-12 18:45:22 +08:00
|
|
|
from strawberry.types.info import Info as StrawberryInfo, RootValueType
|
2023-08-14 02:08:08 +08:00
|
|
|
|
|
|
|
from apps.common import schemas as core_schemas # noqa
|
|
|
|
from apps.user import models # noqa
|
2023-09-12 18:45:22 +08:00
|
|
|
from apps.user.models import User
|
2023-08-14 02:08:08 +08:00
|
|
|
from core import security # noqa
|
|
|
|
from core.config import settings # noqa
|
|
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2023-11-22 17:13:16 +08:00
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
|
|
|
2023-08-14 02:08:08 +08:00
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
async def _get_user(token: str):
|
2023-08-14 02:08:08 +08:00
|
|
|
if not token:
|
|
|
|
GraphQLError("No auth token")
|
|
|
|
try:
|
|
|
|
payload = jwt.decode(
|
|
|
|
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
|
|
|
|
)
|
|
|
|
token_data = core_schemas.TokenPayload(**payload)
|
|
|
|
except (jwt.JWTError, ValidationError) as e:
|
|
|
|
return None
|
|
|
|
|
|
|
|
return await models.User.get(uid=token_data.sub)
|
|
|
|
|
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> models.User | None:
|
|
|
|
return await _get_user(token)
|
|
|
|
|
|
|
|
|
2023-11-22 17:13:16 +08:00
|
|
|
async def get_current_active_user(token: Annotated[str, Depends(oauth2_scheme)]) -> models.User | None:
|
2023-11-22 21:52:18 +08:00
|
|
|
current_user = await _get_user(token)
|
2023-08-14 02:08:08 +08:00
|
|
|
if not current_user or not current_user.is_active:
|
|
|
|
return None
|
|
|
|
return current_user
|
|
|
|
|
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
class InfoContext(BaseContext):
|
|
|
|
async def user(self) -> User | None:
|
|
|
|
if not self.request:
|
|
|
|
return None
|
2023-08-14 02:08:08 +08:00
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
authorization = self.request.headers.get("Authorization", None)
|
2023-08-14 02:08:08 +08:00
|
|
|
if not authorization:
|
2023-11-22 21:52:18 +08:00
|
|
|
return None
|
|
|
|
|
|
|
|
token = authorization.split(" ")[1]
|
|
|
|
return await _get_user(token)
|
2023-08-14 02:08:08 +08:00
|
|
|
|
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
Info = StrawberryInfo[InfoContext, RootValueType]
|
2023-09-12 18:45:22 +08:00
|
|
|
|
|
|
|
|
2023-11-22 21:52:18 +08:00
|
|
|
async def get_gql_context() -> InfoContext:
|
|
|
|
return InfoContext()
|