28 lines
937 B
Python
28 lines
937 B
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.database import get_db
|
|
from app.services.auth_service import decode_access_token, get_user_by_id
|
|
|
|
security = HTTPBearer()
|
|
|
|
|
|
async def require_auth(
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
payload = decode_access_token(credentials.credentials)
|
|
user = await get_user_by_id(db, payload["sub"])
|
|
if not user or not user.is_active:
|
|
raise HTTPException(status_code=401, detail="Invalid or inactive user")
|
|
return user
|
|
|
|
|
|
def require_role(*roles: str):
|
|
async def role_check(user=Depends(require_auth)):
|
|
if user.role.value not in roles:
|
|
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
|
return user
|
|
return role_check
|