check-to-slotPermissions

Check if a user has specific permissions for fine-grained access control.

circle-info

When to use: When you need action-level access control like "can user delete this document?"

chevron-rightPrerequisiteshashtag
  • Completed Login

  • Have a user object from authentication

5-Line Core

if user.has_permission("documents:delete"):
    delete_document(doc_id)
else:
    raise HTTPException(403, "Permission denied")

Step-by-Step

1

Check Single Permission

if user.has_permission("documents:read"):
    print("User can read documents")
2

Check All Permissions (AND)

if user.has_all_permissions(["documents:read", "documents:write"]):
    print("User has full document access")
3

Check Any Permission (OR)

if user.has_any_permission(["admin:all", "documents:manage"]):
    print("User can manage documents")
4

View User's Permissions

print(f"Permissions: {user.permissions}")
5

Expected Output

User can read documents
Permissions: ['documents:read', 'documents:write']
circle-check

Complete Example

Create permissions.py:

Run it:

Expected output:

Roles vs Permissions

Use Case
Check

Admin panel access

Role (has_standard_role)

Specific action

Permission (has_permission)

Feature flag

Permission

Billing access

Role or Permission

Common Pitfalls

Pitfall
Solution

Using permissions for everything

Use roles for coarse access, permissions for fine-grained

Not validating token first

Always validate session before checking permissions

Wrong status code

Permission denied is 403, invalid token is 401


circle-info

Found an issue on this page? Report it on our feedback formarrow-up-right.

Last updated

Was this helpful?