SQL Relations Filter for User Permissions
The sqlRelationsFilter function provides an efficient way to apply row-level filters across related entities directly within SQL, streamlining access control for related rows. In this lesson, we’ll use sqlRelationsFilter to apply permissions based on user access to Task entities in the TimeEntry entity.
Defining User Permission Filters
In this example, we want to ensure that users can only access TimeEntry rows associated with Task entities they have permission to view.
TimeEntry Entity Setup
import { Entity, Fields, Relations } from 'remult'import { sqlRelationsFilter } from 'remult/internals'import { Task } from './Task'
@Entity<TimeEntry>('timeEntries', { allowApiCrud: true, apiPrefilter: () => sqlRelationsFilter(TimeEntry).task.some(Task.allowedTasks()),})export class TimeEntry {15 collapsed lines
@Fields.id() id = ''
@Fields.string({ required: true }) taskId = ''
@Relations.toOne<TimeEntry, Task>(() => Task, 'taskId') task?: Task
@Fields.date() startTime!: Date
@Fields.date() endTime!: Date}Explanation of the Code
-
Using
sqlRelationsFilter:- The
sqlRelationsFilterfunction is designed to apply row-level filtering logic directly within the database. - Here, we use it to filter
TimeEntryrows based on the associatedTaskrows that meet certain user permissions.
- The
-
Relation-Specific Filtering with
.some():- The
.some()method is used to matchTimeEntryrows with relatedTaskrows that satisfy the filter inTask.allowedTasks(). - By passing
Task.allowedTasks()to.some(), we enforce permissions onTimeEntryrows linked to tasks the user is authorized to view.
- The
-
Simplified Filtering Logic:
sqlRelationsFilterenables us to express complex filtering conditions for related entities with a clear and concise API.- This approach is not only efficient but also significantly reduces code complexity by handling filtering at the SQL level.
Try It Out
- Sign in as Different Users: Test with various users (e.g., users with and without admin roles) to observe how access to
TimeEntryrecords changes based on the user’s permissions for relatedTaskentities. - Experiment with Permissions: Modify the
allowedTasksfilter logic inTaskto see how different rules impact the visibility ofTimeEntryentries.
By leveraging sqlRelationsFilter, you can create highly performant and intuitive access control that directly uses SQL to enforce row-level permissions across related entities.
Files
Preparing Environment
- Installing dependencies
- Starting http server