44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
|
|
from fastapi import Depends, HTTPException, status
|
||
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||
|
|
from jose import JWTError
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from app.core.database import get_db
|
||
|
|
from app.core.security import decode_token
|
||
|
|
|
||
|
|
bearer_scheme = HTTPBearer()
|
||
|
|
|
||
|
|
|
||
|
|
async def get_current_user(
|
||
|
|
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
|
||
|
|
db: AsyncSession = Depends(get_db),
|
||
|
|
):
|
||
|
|
from app.modules.auth.service import get_user_by_id
|
||
|
|
|
||
|
|
credentials_exception = HTTPException(
|
||
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
|
|
detail="Token inválido o expirado",
|
||
|
|
)
|
||
|
|
try:
|
||
|
|
payload = decode_token(credentials.credentials)
|
||
|
|
user_id: str = payload.get("sub")
|
||
|
|
if user_id is None:
|
||
|
|
raise credentials_exception
|
||
|
|
except JWTError:
|
||
|
|
raise credentials_exception
|
||
|
|
|
||
|
|
user = await get_user_by_id(db, int(user_id))
|
||
|
|
if user is None:
|
||
|
|
raise credentials_exception
|
||
|
|
return user
|
||
|
|
|
||
|
|
|
||
|
|
async def get_current_business(current_user=Depends(get_current_user)):
|
||
|
|
return current_user.business_id
|
||
|
|
|
||
|
|
|
||
|
|
def require_admin(current_user=Depends(get_current_user)):
|
||
|
|
if current_user.role != "admin":
|
||
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Acceso denegado")
|
||
|
|
return current_user
|