Rajska v0.2.1 Rajska.ObjectScopeAuthorization View Source
Absinthe middleware to perform object scoping.
Authorizes all Absinthe's objects requested in a query by checking the value of the field defined in each object meta scope
.
Usage
Create your Authorization module and add it and ObjectScopeAuthorization to your Absinthe.Schema. Then set the scope of an object:
object :user do
meta :scope, User # Same as meta :scope, {User, :id}
field :id, :integer
field :email, :string
field :name, :string
field :company, :company
end
object :company do
meta :scope, {Company, :user_id}
field :id, :integer
field :user_id, :integer
field :name, :string
field :wallet, :wallet
end
object :wallet do
meta :scope, Wallet
field :total, :integer
end
To define custom rules for the scoping, use Rajska.Authorization.has_user_access?/3
. For example:
defmodule Authorization do
use Rajska,
roles: [:user, :admin]
def has_user_access?(%{role: :admin}, User, _id), do: true
def has_user_access?(%{id: user_id}, User, id) when user_id === id, do: true
def has_user_access?(_current_user, User, _id), do: false
end
Keep in mind that the field_value
provided to has_user_access?/3
can be nil
. This case can be handled as you wish.
For example, to not raise any authorization errors and just return nil
:
defmodule Authorization do
use Rajska,
roles: [:user, :admin]
def has_user_access?(_user, _, nil), do: true
def has_user_access?(%{role: :admin}, User, _id), do: true
def has_user_access?(%{id: user_id}, User, id) when user_id === id, do: true
def has_user_access?(_current_user, User, _id), do: false
end
Link to this section Summary
Functions
This is the main middleware callback.
Link to this section Functions
call(resolution, config) View Source
This is the main middleware callback.
It receives an %Absinthe.Resolution{}
struct and it needs to return an
%Absinthe.Resolution{}
struct. The second argument will be whatever value
was passed to the middleware
call that setup the middleware.
Callback implementation for Absinthe.Middleware.call/2
.