Scoping to Current User
Given a
Post
model withhidden
attribute, only allow administrators to view hiddenPosts
.
Let’s start by adding a visible
scope to Post
, so we can easily
retrive only Post
s where hidden
is false
:
As you know, we would typically use the base scope Post.all
like so:
Let’s instead use the base scope Post.visible
when the user is not an
administrator:
That’s it! Now only administrators can view hidden Post
s.
Of course, this logic would only apply to the /posts
endpoint and
would not apply when we are sideloading from /blogs?include=posts
. To
ensure this logic runs all the time, add a default filter:
Privileged Writes
Given
Post
s that have aninternal
attribute, only allow internal users to publish internal posts.
Our controller context is available in our resource. Let’s override
Resource#create
to ensure correct privileging:
Guarding Filters
Given
Employee
s with attributeunder_performance_review
, do not allow clients to find all employees under performance review.
Occasionally you need to guard filters based on the current user. Use
the :if
option on allow_filter
. This will execute in the context of
your controller: