Custom Policies¶
Implement custom authorization logic beyond roles and scopes.
Custom Policy Example¶
def can_edit_post(user: UserData, post: Post) -> bool:
# Owner can always edit
if post.author_id == user.sub:
return True
# Admins can edit anything
if "admin" in user.roles:
return True
# Editors in same workspace can edit
if "editor" in user.roles and post.workspace_id == user.workspace_id:
return True
return False
@app.patch("/posts/{post_id}")
def update_post(
post_id: str,
user: UserData = Depends(authenticator)
):
post = db.posts.find_one({"id": post_id})
if not can_edit_post(user, post):
raise HTTPException(status_code=403)
# Update post
pass
Time-Based Policies¶
from datetime import datetime
def can_access_during_hours(user: UserData) -> bool:
hour = datetime.now().hour
# Only 9 AM to 5 PM
return 9 <= hour < 17
@app.get("/admin/panel")
def admin_panel(user: UserData = Depends(authenticator)):
if not can_access_during_hours(user):
raise HTTPException(status_code=403, detail="Outside business hours")
pass