Rajska (Rajska v1.3.2) View Source

Rajska is an elixir authorization library for Absinthe.

It provides the following middlewares:

Installation

The package can be installed by adding rajska to your list of dependencies in mix.exs:

def deps do
  [
    {:rajska, "~> 1.3.2"},
  ]
end

Usage

Create your Authorization module, which will implement the Rajska.Authorization behaviour and contain the logic to validate user permissions and will be called by Rajska middlewares. Rajska provides some helper functions by default, such as Rajska.Authorization.role_authorized?/2 and Rajska.Authorization.has_user_access?/3, but you can override them with your application needs.

defmodule Authorization do
  use Rajska,
    valid_roles: [:user, :admin]
end

Available options and their default values:

valid_roles: [:admin],
super_role: :admin,
default_rule: :default

Add your Authorization module to your Absinthe.Schema context/1 callback and the desired middlewares to the middleware/3 callback:

def context(ctx), do: Map.put(ctx, :authorization, Authorization)

def middleware(middleware, field, %Absinthe.Type.Object{identifier: identifier})
when identifier in [:query, :mutation] do
  middleware
  |> Rajska.add_query_authorization(field, Authorization)
  |> Rajska.add_object_authorization()
end

def middleware(middleware, field, object) do
  Rajska.add_field_authorization(middleware, field, object)
end

The only exception is Object Scope Authorization, which isn't a middleware, but an Absinthe Phase. To use it, add it to your pipeline after the resolution:

# router.ex
alias Absinthe.Phase.Document.Execution.Resolution
alias Absinthe.Pipeline
alias Rajska.ObjectScopeAuthorization

forward "/graphql", Absinthe.Plug,
  schema: MyProjectWeb.Schema,
  socket: MyProjectWeb.UserSocket,
  pipeline: {__MODULE__, :pipeline} # Add this line

def pipeline(config, pipeline_opts) do
  config
  |> Map.fetch!(:schema_mod)
  |> Pipeline.for_document(pipeline_opts)
  |> Pipeline.insert_after(Resolution, ObjectScopeAuthorization)
end

Since Scope Authorization middleware must be used with Query Authorization, it is automatically called when adding the former.

Link to this section Summary

Link to this section Functions

Link to this function

add_field_authorization(middleware, field, object)

View Source

See Rajska.Schema.add_field_authorization/3.

Link to this function

add_object_authorization(middleware)

View Source

See Rajska.Schema.add_object_authorization/1.

Link to this function

add_query_authorization(middleware, field, authorization)

View Source

See Rajska.Schema.add_query_authorization/3.