Advertisement
Guest User

Untitled

a guest
Feb 26th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. defmodule BasicAuth do
  2. import Plug.Conn
  3.  
  4. @realm "Basic realm=\"Thou Shalt not pass\""
  5.  
  6. def init(opts) do
  7. Keyword.fetch!(opts, :username)
  8. Keyword.fetch!(opts, :password)
  9. opts
  10. end
  11.  
  12. def call(conn, [username: username, password: password]) do
  13. case get_req_header(conn, "authorization") do
  14. ["Basic " <> auth] ->
  15. if auth == encode(username, password) do
  16. conn
  17. else
  18. unauthorized(conn)
  19. end
  20. _ ->
  21. unauthorized(conn)
  22. end
  23. end
  24.  
  25. defp encode(username, password), do: Base.encode64(username <> ":" <> password)
  26.  
  27. defp unauthorized(conn) do
  28. conn
  29. |> put_resp_header("www-authenticate", @realm)
  30. |> send_resp(401, "unauthorized")
  31. |> halt()
  32. end
  33. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement