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
+23 -3
View File
@@ -4,8 +4,8 @@ import os
from ..database import get_db
from ..dependencies import get_current_user
from ..models import User
from ..schemas import UserLogin, UserOut, UserRegister
from ..models import User, UserRole, UserStatus
from ..schemas import UserLogin, UserOut, UserRegister, UserApprove
from ..security import (
ACCESS_TOKEN_EXPIRE_MINUTES,
create_access_token,
@@ -42,16 +42,25 @@ def register(body: UserRegister, response: Response, db: Session = Depends(get_d
if db.query(User).filter(User.email == body.email).first():
raise HTTPException(status_code=400, detail="Email already registered.")
# Admin registers as approved immediately; others start as pending
initial_status = (
UserStatus.approved if body.role == UserRole.admin else UserStatus.pending
)
user = User(
username=body.username,
email=body.email,
password_hash=hash_password(body.password),
role=body.role,
status=initial_status,
)
db.add(user)
db.commit()
db.refresh(user)
_set_auth_cookie(response, user.id)
# Only set auth cookie if immediately approved (admin self-registration)
if user.status == UserStatus.approved:
_set_auth_cookie(response, user.id)
return user
@@ -68,6 +77,17 @@ def login(body: UserLogin, response: Response, db: Session = Depends(get_db)):
if not user or not password_ok:
raise HTTPException(status_code=401, detail="Invalid username or password.")
if user.status == UserStatus.pending:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Your account is pending admin approval.",
)
if user.status == UserStatus.rejected:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Your account has been rejected.",
)
_set_auth_cookie(response, user.id)
return user