Performance: Role-based access control
This affects the server response time and user interaction speed by controlling access checks before processing requests.
from fastapi import Depends, HTTPException from fastapi import Depends def role_checker(required_role: str): def checker(user=Depends(get_current_user)): if required_role not in user.roles: raise HTTPException(status_code=403) return checker @app.get('/data') async def get_data(role_check=Depends(role_checker('admin'))): # fetch sensitive data pass
def get_data(user): if 'admin' in user.roles: # fetch sensitive data pass elif 'user' in user.roles: # fetch limited data pass else: raise HTTPException(status_code=403) # role check repeated in every endpoint
| Pattern | CPU Usage | Request Latency | Code Duplication | Verdict |
|---|---|---|---|---|
| Repeated inline role checks | High | Increased | High | [X] Bad |
| Centralized role checks with dependencies | Low | Reduced | Low | [OK] Good |
async def get_admin_data(admin: None = Depends(admin_required)):
return {"data": "secret"}
What happens if a user with role 'user' calls this endpoint?def check_admin(user: User = Depends(get_current_user)):
if user.role == 'admin':
return True
else:
return False
@app.get('/admin')
async def admin_panel(is_admin: bool = Depends(check_admin)):
if not is_admin:
raise HTTPException(status_code=403)
return {"msg": "Welcome admin"}Pass the test and this pattern moves unknown