39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlmodel import Session, select
|
|
from app.db.session import get_session
|
|
from app.models.music import User, UserRole
|
|
from app.core.security import decode_access_token
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
payload = decode_access_token(token)
|
|
if not payload:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
username = payload.get("sub")
|
|
user = session.exec(select(User).where(User.username == username)).first()
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return user
|
|
|
|
class RoleChecker:
|
|
def __init__(self, allowed_roles: list[UserRole]):
|
|
self.allowed_roles = allowed_roles
|
|
|
|
def __call__(self, user: User = Depends(get_current_user)):
|
|
if user.role not in self.allowed_roles:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="You do not have permission to perform this action"
|
|
)
|
|
return user
|