from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.orm import Session from app.db.session import get_db from app.core.security import verify_token from app.models.users import User from app.models.employees import Employee security = HTTPBearer() def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db) ) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) payload = verify_token(credentials.credentials) if payload is None: raise credentials_exception email: str = payload.get("sub") if email is None: raise credentials_exception user = db.query(User).filter(User.email == email).first() if user is None: raise credentials_exception return user def get_current_employee( current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ) -> Employee: employee = db.query(Employee).filter(Employee.user_id == current_user.id).first() if not employee: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Employee profile not found" ) return employee def require_role(required_roles: list): def role_checker(current_user: User = Depends(get_current_user)): if current_user.role not in required_roles: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions" ) return current_user return role_checker