62 lines
1.9 KiB
Python
62 lines
1.9 KiB
Python
from fastapi import Depends, status, HTTPException
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import jwt
|
|
from motor.motor_asyncio import AsyncIOMotorDatabase
|
|
from pydantic import ValidationError
|
|
|
|
import crud
|
|
import schemas
|
|
import utils
|
|
from core import security
|
|
from core.config import settings
|
|
from db import get_database
|
|
|
|
reusable_oauth2 = OAuth2PasswordBearer(
|
|
tokenUrl=f"{settings.API_V1_STR}/user/login"
|
|
)
|
|
|
|
|
|
def get_current_user(token: str = Depends(reusable_oauth2)
|
|
) -> schemas.UserDB:
|
|
# def get_current_user(token: str
|
|
# ) -> schemas.UserDBBase:
|
|
try:
|
|
payload = jwt.decode(
|
|
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
|
|
)
|
|
user = schemas.UserDB(**payload)
|
|
except (jwt.JWTError, ValidationError):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Could not validate credentials",
|
|
)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return user
|
|
|
|
|
|
def get_current_user2(token: str) -> schemas.UserDB:
|
|
try:
|
|
payload = jwt.decode(
|
|
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
|
|
)
|
|
user = schemas.UserDB(**payload)
|
|
except (jwt.JWTError, ValidationError):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Could not validate credentials",
|
|
)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return user
|
|
|
|
|
|
async def get_game_project(game: str, db: AsyncIOMotorDatabase = Depends(get_database)) -> str:
|
|
is_exists = await crud.project.find_one(db, {'game': game}, {'_id': True})
|
|
if not is_exists:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail='没有该项目'
|
|
)
|
|
return game
|