satom99

satom99

It’s been a couple days of tinkering already and I cannot seem to
find a way to do permissions within Absinthe that fully satisfies me.

I am essentially looking for a mechanism that handles roles and future
user-specific permissions the simplest way possible. At first I figured a
middleware would be the way to go, because one may grab the query
or mutation’s name directly from the passed resolution struct and work
from there - so basically grab the user previously stored within the context
and perform whatever checks both with the action name and the user struct.

Now, that would indeed do the trick but that is not quite a clean solution.
The reason being we only work with an action name and a user struct, as
well as possibly the arguments that were passed in from the resolution, and
therefore we’d pretty much end up having a single centralized module needing a
per-action specific definition to delegate pertinent permission checks to elsewhere.

Let me also include that the reason I am looking for a solution within the lines of
the above is because I would rather not do permission checks directly within the
resolving functions. Mainly because of readability concerns and code repetition.

Another concern to discuss would be resource fetching. In a regular phoenix setup one
could set-up their own plug that fetches a resource from an Ecto schema of sorts before
even reaching the controller’s function and then have a second plug right after that does
permission checks taking into account all the resources fetched prior. Ideally, one could
want to mimic this behaviour within Absinthe. For which an obvious solution would be to
call the resolving function manually, of course only in case of queries, and then in case of
a successful return pass the returned object down to the permission checks to determine
whether the resolution result should be set to an error or the actual successful response.
Of course when doing this we would ideally want to process all middlewares that go before
resolution, because otherwise we’d be losing the functionality provided by other middlewares.
And this is bad, real bad in fact. Because we would be recreating internal behaviour manually.

So to wrap up… I would love to hear how others have tackled these things to hopefully untangle. :slight_smile:

Showing Posts 1 to 6

OvermindDL1

OvermindDL1

For note, I do do permission checks in the resolving functions, because it specifically limits the amount of information as well, not just overall access. I have very fine grained permissions so I don’t see any other way of doing this.

hlx

hlx

Maybe passing options to middleware/2 macro will help.

Example:

field :update_user, :user do
  middleware MyAppAPI.Authentication, role: :admin, scope: :api, hello: :world
  (...)
end

My personal opinion though is that your GraphQL (or any other API) layer is your client app and should not do permission checking. In our case the MyApp app is the logic app which contains all the app logic. MyAppAPI is a client app (GraphQL) that will handle the schema parsing and resolving and MyAppWeb is the Phoenix app which basically just handles the routing and Plug stuff. This way we can add another client app, a REST API for example, and not have to reimplement the permissions mechanism in that app as well.

In our app a plug (located in my_app_api/lib/my_app_api/context.ex still fetches the access token from the request, looks up the correct token in the database and places that in the private absinthe context before the schema is parsed.

Example:

defmodule MyAppWeb.Router do
  @moduledoc """

  """

  use MyAppWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
    plug MyAppAPI.Context
  end

  scope "/" do
    pipe_through :api

    forward "/graphql", Absinthe.Plug, schema: MyAppAPI.Schema
    forward "/graphiql", Absinthe.Plug.GraphiQL, schema: MyAppAPI.Schema
  end
end
defmodule MyAppAPI.Context do
  @moduledoc """
  A plug which builds the GraphQL context for MyAppAPI.
  """

  use Plug.Builder

  alias MyApp.Accounts

  @spec init(any) :: any
  def init(opts), do: opts

  @spec call(Plug.Conn.t(), any) :: Plug.Conn.t()
  def call(conn, _opts) do
    with ["Bearer " <> access_token] <- get_req_header(conn, "authorization"),
         {:ok, token} <- Accounts.find_token_by(access_token: access_token) do
      put_private(conn, :absinthe, %{context: %{token: token}})
    else
      _ -> conn
    end
  end
end
jstlroot

jstlroot

Hi @OvermindDL1,

I’m trying to do the same thing you did, for exactly the same reasons.

However, I’m not yet able to figure out a way to use Absinthe.Resolution.put_result(resolution, {:error, "forbidden"}) (for example) in a resolver function, probably because, contrary to a middleware, resolver functions are meant to return data, not a resolution.

One way I can think of would be to use a middleware in my schema after resolution but it seems very redundant.

Did you find a better approach?

Thank you in advance.
Cheers! :beers:

jstlroot

jstlroot

Bingo!

Wow, was I thinking about this the wrong way!

The resolution function’s return becomes the absinthe resolution’s result! Therefore, returning {:error, "forbidden"} from the resolver function is the same as doing Absinthe.Resolution.put_result(resolution, {:error, "forbidden"}) in a middleware.

It’s so stupidly simple and obvious now that I see it! I’ll leave this here anyway in case it could help someone.

Cheers! :beers:

OvermindDL1

OvermindDL1

Yep. ^.^

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Simply return this value from your resolver. Absinthe.Resolution.put_result exists to map resolver tuples on to middleware. If you are in a resolver, just return the tuple.

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

CodeSync
Just a reminder for anyone still on the fence: early bird pricing for Code BEAM Europe closes on 8 September at 23:59 CEST. This is the l...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews