Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement