-
-
Save sapandiwakar/cd6b988ae8f7d59db579f228fad63210 to your computer and use it in GitHub Desktop.
A plug that puts the user, token and conn into Absinthe context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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