Skip to content

Instantly share code, notes, and snippets.

@sjchmiela
Created November 16, 2016 20:27
Show Gist options
  • Save sjchmiela/cbf2ba06c755ce52e8c42e9e2a360e99 to your computer and use it in GitHub Desktop.
Save sjchmiela/cbf2ba06c755ce52e8c42e9e2a360e99 to your computer and use it in GitHub Desktop.
defmodule Sheetly.Schema.Phase do
@custom_phases [
Sheetly.Schema.Phase.Authorization,
]
def pipeline(config, opts) do
@custom_phases
|> Enum.reduce(Absinthe.Plug.default_pipeline(config, opts), &pipe_through_phase/2)
end
defp pipe_through_phase(phase, pipeline), do: phase.pipeline(pipeline)
end
forward "/", Absinthe.Plug, schema: Sheetly.Schema, pipeline: {Sheetly.Schema.Phase, :pipeline}
defmodule Sheetly.Schema.Phase.Authorization do
import Canada, only: [can?: 2]
use Absinthe.Phase
alias Absinthe.{
Resolution,
Blueprint,
Pipeline,
Type,
}
def pipeline(pipeline) do
Pipeline.insert_before(pipeline, Absinthe.Phase.Document.Execution.Resolution, __MODULE__)
end
def run(input, _options \\ []) do
authorized_blueprint =
Blueprint.prewalk(input, &do_prewalk/1)
{:ok, authorized_blueprint}
end
defp do_prewalk(%{schema_node: %Type.Field{} = field} = node) do
private = Keyword.put(field.__private__, __MODULE__, resolve: &__MODULE__.authorize/1)
field = %{field | __private__: private}
%{node | schema_node: field}
end
defp do_prewalk(node), do: node
def authorize(resolution_fun) do
fn parent, args, info ->
if can?(info.context, read(String.to_atom(info.definition.name))) do
Resolution.call(resolution_fun, parent, args, info)
else
{:ok, nil}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment