r/FastAPI • u/predominant • Apr 22 '25
Question Column or Field based access control
I'm tasked with implementing a role based access system that would control access to records in the database at a column level.
For example, a Model called Project:
class Project(SQLModel):
id: int
name: str
billing_code: str
owner: str
Roles:
- Administrator: Can edit everything
- Operator: Can edit owner and billing_code
- Billing: Can edit only billing_code
- Viewer: Cannot edit anything
Is there a best practice or example of an approach that I could use to enforce these rules, while not having to create separate endpoints for each role, and eliminate duplicating code?
Bonus points if theres a system that would allow these restrictions/rules to be used from a frontend ReactJS (or similar) application.
10
Upvotes
7
u/AverageLiberalJoe Apr 22 '25
You can create a config file and export a settings class. Part of the class keeps a dictionary of arrays. And that dictionary is for your RBAC. In your endpoints you can add a 'Depends' that wraps a common function that checks user against endpoint access.
Or you can add a normalized table of roles and columns and join it in your query. If there is nothing to join the query can fail gracefully.
1
u/fueled_by_caffeine Apr 22 '25
I tend to implement things like this using Azure APIM over the endpoint to keep the policy and endpoint implementation decoupled
1
u/Vast_Ad_7117 Apr 22 '25
Maybe a simple lookup dictionary with Role: [allowed fields to edit]. Then check the current users role against this dictionary, and the user input pydantic model (or whatever the input is encapsulated in). Could create a dependency for this.
1
u/[deleted] Apr 22 '25
Update save method and in that one add condition that whoever doing the updatation check his role and based on that proceed .
Or against the endpoint add decorator which check for role before proceeding to save part