First commit
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from database import get_db
|
||||
from services import AuthService, UserService
|
||||
from models import User
|
||||
|
||||
# Configuración OAuth2
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/login")
|
||||
|
||||
# Dependencias de seguridad
|
||||
def get_current_user(
|
||||
db: Session = Depends(get_db),
|
||||
token: str = Depends(oauth2_scheme)
|
||||
) -> User:
|
||||
user_id = AuthService.verify_token(token)
|
||||
user_service = UserService(db)
|
||||
user = user_service.get_user_by_id(user_id)
|
||||
if not user or not user.active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token or inactive user",
|
||||
)
|
||||
return user
|
||||
|
||||
def get_current_active_user(current_user: User = Depends(get_current_user)):
|
||||
if not current_user.active:
|
||||
raise HTTPException(status_code=400, detail="Inactive user")
|
||||
return current_user
|
||||
|
||||
def require_admin(current_user: User = Depends(get_current_active_user)):
|
||||
if current_user.rol != 'admin':
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Insufficient permissions"
|
||||
)
|
||||
return current_user
|
||||
|
||||
def require_admin_or_owner(
|
||||
user_id: int,
|
||||
current_user: User = Depends(get_current_active_user)
|
||||
):
|
||||
if current_user.rol != 'admin' and current_user.id != user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Insufficient permissions"
|
||||
)
|
||||
return current_user
|
||||
Reference in New Issue
Block a user