Skip to content

Instantly share code, notes, and snippets.

@ssomnoremac
Created September 20, 2017 19:55
Show Gist options
  • Save ssomnoremac/be003df435f2c408621d3794881ca11e to your computer and use it in GitHub Desktop.
Save ssomnoremac/be003df435f2c408621d3794881ca11e to your computer and use it in GitHub Desktop.
defmodule BlogPhoenix.Context do
@moduledoc """
This module is just a regular plug that can look at the conn struct and build
the appropriate absinthe context.
"""
@behaviour Plug
import Plug.Conn
def init(opts), do: opts
def call(conn, _) do
case get_token(conn) do
{:ok, claims} ->
context = build_context(claims)
IO.inspect [context: context]
put_private(conn, :absinthe, %{context: context})
{:error, reason} ->
conn
|> put_resp_content_type("application/json")
|> send_resp(403, Poison.encode!(%{error: reason}))
|> halt
end
end
defp get_token(conn) do
with ["Bearer " <> token] <- get_req_header(conn, "authorization"),
{:ok, claims} <- BlogPhoenix.Guardian.decode_and_verify(token)
do
{:ok, claims}
else
_ -> {:error, "unauthorized"}
end
end
defp build_context(claims) do
with user <- Map.get(claims, "name") do
%{current_user: user}
else
_ -> %{}
end
end
defp get_user(data) do
IO.inspect(data)
BlogPhoenix.Repo.get_by(BlogPhoenix.User, id: id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment