mirror of
https://github.com/samsonjs/grape-active_model_serializers.git
synced 2026-04-26 14:47:42 +00:00
add support for 'current_user'
This commit is contained in:
parent
4b474ef8f2
commit
beb9057b97
2 changed files with 42 additions and 2 deletions
31
README.md
31
README.md
|
|
@ -99,6 +99,37 @@ namespace 'foo', :serializer => :bar do
|
||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### current_user
|
||||||
|
|
||||||
|
One of the nice features of ActiveModel::Serializers is that it
|
||||||
|
provides access to the authorization context via the `current_user`.
|
||||||
|
|
||||||
|
In Grape, you can get the same behavior by defining a `current_user`
|
||||||
|
helper method:
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
helpers do
|
||||||
|
def current_user
|
||||||
|
@current_user ||= User.where( :access_token => params[:token]).first
|
||||||
|
end
|
||||||
|
|
||||||
|
def authenticate!
|
||||||
|
error!('401 Unauthenticated', 401) unless current_user
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, in your serializer, you could show or hide some elements
|
||||||
|
based on the current user's permissions:
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
class PostSerializer < ActiveModel::Serializer
|
||||||
|
...
|
||||||
|
def include_admin_comments?
|
||||||
|
current_user.roles.member? :admin
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
### Full Example
|
### Full Example
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,9 +16,18 @@ module Grape
|
||||||
options[:route_options]
|
options[:route_options]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.included(base)
|
||||||
|
mattr_accessor :_serialization_scope
|
||||||
|
self._serialization_scope = :current_user
|
||||||
|
|
||||||
|
base.class_eval do
|
||||||
|
def serialization_scope
|
||||||
|
send(_serialization_scope) if _serialization_scope && respond_to?(_serialization_scope, true)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def default_serializer_options; end
|
def default_serializer_options; end
|
||||||
def serialization_scope; end
|
|
||||||
def _serialization_scope; end
|
|
||||||
def url_options; end
|
def url_options; end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue