How do I authenticate CRUD functions with absinthe/graphql?

I hope my explanation makes sense. I am a newb who followed this tutorial which is the 3rd in a series on building a graphql in phoenix. In it we are shown how to authenticate the all(read all) function but none of the crud functions. The long and short of it is I’m trying to check for the user id in the post resolver and make sure it matches the user id that is currently logged in. This code is from the original repo’s post resolver is below.

defmodule Graphical.PostResolver do
  alias Graphical.Posts
  import Ecto.Query, only: [where: 2]
  alias Graphical.Posts.Post
  alias Graphical.Repo
  

  def all(_args, %{context: %{current_user: %{id: id}}}) do
    posts =
      Post
      |> where(user_id: ^id)
      |> Graphical.Repo.all

    {:ok, posts}
  end
  def all(_args, _info) do
    {:error, "Not Authorized"}
  end

  def create(args, _info) do
    Posts.create_post(args)
  end

  def update(%{id: id, post: post_params}, _info) do
    Posts.get_post!(id)
    |> Posts.update_post(post_params)
  end

  def delete(%{id: id}, _info) do
    Posts.get_post!(id)
    |> Posts.delete_post
  end

My hope to authenticate say the create function is with something like the below

def create(args, %{context: %{current_user: %{id: id}}}) do
    if user_id: id do
      Posts.create_post(args)
    end
  end

It gives me a “no function clause matching” as an error for this function when executed in the graphql window.

I hope this long question makes any sense to anyone. lol Any suggestions how to authenticate the create or any other functions?

I assume you have replaced the create function above with your own? In that case, the Elixir system would not know what function clause to use when there is no user. You will want something like:

def create(args, %{context: %{current_user: %{id: id}}}) do
    if user_id: id do
      Posts.create_post(args)
    end
end

def create(args, _info) do 
  {:error, "Not Authorized"}
end

the system will hit the authenticated user case if the authentication info is in context. Otherwise it will hit the error clause of create

If I’m off base, we may need more info about your setup.

1 Like