thực hiện phân quyền admin giáo viên và học sinh xong

This commit is contained in:
2026-04-01 19:26:47 +07:00
parent 8546d41a26
commit 386871bd4a
14 changed files with 796 additions and 37 deletions
+32 -1
View File
@@ -3,7 +3,7 @@ from jose import JWTError
from sqlalchemy.orm import Session
from .database import get_db
from .models import User
from .models import User, UserRole, UserStatus
from .security import decode_access_token
@@ -33,4 +33,35 @@ def get_current_user(
if user is None:
raise credentials_exception
# Guard: approved users only (pending/rejected cannot use the API)
if user.status != UserStatus.approved:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Your account is pending admin approval.",
)
return user
def require_role(*roles: UserRole):
"""
Returns a FastAPI dependency that asserts the current user has one of the
given roles. Usage: Depends(require_role(UserRole.admin, UserRole.teacher))
"""
def _check(current_user: User = Depends(get_current_user)) -> User:
if current_user.role not in roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You do not have permission to perform this action.",
)
return current_user
return _check
def require_admin(current_user: User = Depends(get_current_user)) -> User:
if current_user.role != UserRole.admin:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin access required.",
)
return current_user