|
how to set permissions or roles to active @permission_required or @role_required? |
Answered by
GrandpaEJ
May 30, 2026
Replies: 2 comments 3 replies
|
The decorators read the values from the logged-in For roles, use the plural decorator For permissions, Example: from bustapi.auth import BaseUser, roles_required, permission_required
class User(BaseUser):
def __init__(self, id):
self.id = id
self.role = "admin"
self.permissions = ["posts:delete", "users:read"]
@app.get("/admin")
@roles_required("admin")
def admin():
return {"ok": True}
@app.post("/posts/delete")
@permission_required("posts:delete")
def delete_post():
return {"deleted": True}The important part is that your |
1 reply
|
I have tested cookesan's approach thoroughly — it works correctly. Here is a complete breakdown: ✅ How it works1. Create a user class with
|
| Test | Result |
|---|---|
roles_required with role (singular) |
✅ Pass |
roles_required role mismatch → 403 |
✅ Pass |
roles_required with roles (plural list) |
✅ Pass |
permission_required has permission |
✅ Pass |
permission_required missing → 403 |
✅ Pass |
permission_required multiple (ALL required) |
✅ Pass |
permission_required callable .permissions |
✅ Pass |
| Unauthenticated → 401 first | ✅ Pass |
| Real discussion #21 code example | ✅ Pass |
📝 Key notes
roles_requiredcheckscurrent_user.rolesfirst (as a list), then falls back tocurrent_user.role(single string → wrapped in list). Uses any match logic.permission_requiredcheckscurrent_user.permissions— supports list and callable. Uses all match logic (every permission must be present).- Both return 401 if not authenticated, 403 if role/permission missing.
Hope this helps!
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Information returned by
@login_manager.user_loader:The user loader must return a user object inheriting from
BaseUser(or implementing its interface). By default, it needs to provide the following attributes/properties:id: A unique identifier for the user session (string or integer).is_authenticated: A boolean property indicating if the user is authenticated (returnsTruefor active users,Falsefor anonymous/inactive users).is_active: A boolean property indicating if the user account is active.is_anonymous: A boolean property indicating if this is an anonymous user (returnsFalsefor real users).Dynamic Roles/Permissions and avoiding Circular Imports:
Dynamic determination: …