Initial certificate system
This commit is contained in:
33
backend/app/api/deps.py
Normal file
33
backend/app/api/deps.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.security import decode_access_token
|
||||
from app.db.session import get_db
|
||||
from app.models import AdminUser
|
||||
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def get_current_admin(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> AdminUser:
|
||||
if credentials is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
||||
payload = decode_access_token(credentials.credentials)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
admin = db.get(AdminUser, int(payload["sub"]))
|
||||
if not admin or admin.status != "active":
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user")
|
||||
return admin
|
||||
|
||||
|
||||
def require_roles(*role_codes: str):
|
||||
def checker(admin: AdminUser = Depends(get_current_admin)) -> AdminUser:
|
||||
if admin.role_code not in role_codes:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Permission denied")
|
||||
return admin
|
||||
|
||||
return checker
|
||||
Reference in New Issue
Block a user