Skip to content

Instantly share code, notes, and snippets.

@moroz
Created February 4, 2021 01:42
Show Gist options
  • Select an option

  • Save moroz/a7f3c74d47fffe01f279adff2e4457a4 to your computer and use it in GitHub Desktop.

Select an option

Save moroz/a7f3c74d47fffe01f279adff2e4457a4 to your computer and use it in GitHub Desktop.
Per-action authorization in Absinthe schema with Bodyguard
defmodule MyAppWeb.Api.Middleware.Authorize do
@behaviour Absinthe.Middleware
@moduledoc """
Absinthe middleware to deny access based on Bodyguard ACLs.
The field name is passed to the policy module as string, as I haven't found
any better way to get the field name from the resolution object.
"""
def call(%{context: %{current_user: user}} = res, module) when is_atom(module) do
with as_atom <- String.to_existing_atom(Macro.underscore(res.definition.name)),
:ok <- Bodyguard.permit(module, as_atom, user, res.arguments) do
res
else
_ ->
%{res | errors: ["You are not allowed to perform this action."], state: :resolved}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment