File size: 1,366 Bytes
7c11a75 41eef54 7c11a75 41eef54 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from fastapi import Depends, HTTPException, status
from jose import jwt
from .Model import User
from .Constants import UserType
from fastapi.security import OAuth2PasswordBearer
SECRET_KEY = "your_secret_key_here"
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="user/login")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user = await User.get_or_none(phoneNumber=payload.get("sub"))
if user is None:
raise credentials_exception
except jwt.JWTError:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)):
return current_user
async def get_admin_user(current_user: User = Depends(get_current_active_user)):
print(current_user.user_type, current_user.name)
if current_user.user_type != UserType.ADMIN:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User does not have permission",
headers={"WWW-Authenticate": "Bearer"},
)
return current_user
|