Skip to content
This repository was archived by the owner on Jul 25, 2024. It is now read-only.

How to do authentication and authorization in a Phoenix application with GraphQL

Sean Abrahams edited this page Mar 16, 2016 · 11 revisions

This guide assumes you've already setup plug_graphql.

Create a new plug: lib/plugs/authenticate.ex

defmodule YourApp.Plugs.Authenticate do
  import Plug.Conn
  import Phoenix.Controller

  def init(default), do: default

  def call(conn, _default) do
    user_id = get_session(conn, :user_id)
    if user_id do
      user = YourApp.Repo.get!(YourApp.User, user_id)
      # Set user in conn.assigns.graphql_options GraphQL queries/mutations
      conn = assign(conn, :current_user, user)
      graphql_options = Map.merge(conn.assigns[:graphql_options] || %{}, %{ root_value: %{ user: user } })
      conn = assign(conn, :graphql_options, graphql_options)
      conn
    else
      conn
        |> put_flash(:error, 'You need to be signed in to view this page.')
        |> redirect(to: "/")
    end
  end
end

Then in your GraphQL resolve functions (3rd argument), :user will be available in order to do authorization.

For example:

defmodule TestSchema do
  def schema do
    %GraphQL.Schema{
      query: %GraphQL.Type.ObjectType{
        name: "Hello",
        fields: %{
          greeting: %{
            type: %GraphQL.Type.String{},
            args: %{
              name: %{
                type: %GraphQL.Type.String{}
              }
            },
            resolve: fn(obj, args, info) -> 
              ### HERE
              info[:user]
            end
          }
        }
      }
    }
  end
end
Clone this wiki locally