Skip to content

Instantly share code, notes, and snippets.

@sapandiwakar
Created May 19, 2023 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sapandiwakar/cd6b988ae8f7d59db579f228fad63210 to your computer and use it in GitHub Desktop.
Save sapandiwakar/cd6b988ae8f7d59db579f228fad63210 to your computer and use it in GitHub Desktop.
A plug that puts the user, token and conn into Absinthe context
defmodule MyAppWeb.Schema.Context do
@behaviour Plug
import Plug.Conn
def init(opts), do: opts
def call(conn, _default) do
Absinthe.Plug.put_options(conn, context: absinthe_context(conn))
end
@doc """
Gets the Absinthe Context from a conn. Returns a map with user, token and the conn.
"""
def absinthe_context(conn) do
%{conn: fetch_query_params(conn)}
|> put_user()
end
# Adds user if authentication token present on header/query
defp put_user(%{conn: conn} = context) do
with {:ok, token} <- fetch_access_token(conn),
{:ok, user} <- MyApp.Accounts.get_user_by_token(token) do
context |> Map.put(:user, user)
|> Map.put(:token, token)
else
_error -> context
end
end
defp fetch_access_token(conn) do
token = conn.query_params["token"]
if token do
{:ok, token}
else
case get_req_header(conn, "authorization") do
[token | _rest] -> {:ok, token}
_any -> :error
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment