Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. defmodule BlogPhoenix.Context do
  2. @moduledoc """
  3. This module is just a regular plug that can look at the conn struct and build
  4. the appropriate absinthe context.
  5. """
  6.  
  7. @behaviour Plug
  8. import Plug.Conn
  9.  
  10. def init(opts), do: opts
  11.  
  12. def call(conn, _) do
  13. case get_token(conn) do
  14. {:ok, claims} ->
  15. context = build_context(claims)
  16. IO.inspect [context: context]
  17. put_private(conn, :absinthe, %{context: context})
  18. {:error, reason} ->
  19. conn
  20. |> put_resp_content_type("application/json")
  21. |> send_resp(403, Poison.encode!(%{error: reason}))
  22. |> halt
  23. end
  24. end
  25.  
  26. defp get_token(conn) do
  27. with ["Bearer " <> token] <- get_req_header(conn, "authorization"),
  28. {:ok, claims} <- BlogPhoenix.Guardian.decode_and_verify(token)
  29. do
  30. {:ok, claims}
  31. else
  32. _ -> {:error, "unauthorized"}
  33. end
  34. end
  35.  
  36. defp build_context(claims) do
  37. with user <- Map.get(claims, "name") do
  38. %{current_user: user}
  39. else
  40. _ -> %{}
  41. end
  42. end
  43.  
  44. defp get_user(data) do
  45. IO.inspect(data)
  46. BlogPhoenix.Repo.get_by(BlogPhoenix.User, id: id)
  47. end
  48.  
  49. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement