Packages
guardian
0.10.1
2.4.0
2.3.2
2.3.1
2.3.0
2.2.4
2.2.3
2.2.2
2.2.1
2.2.0
2.1.2
2.1.1
2.0.0
1.2.1
1.2.0
retired
1.1.1
1.1.0
1.0.1
1.0.0
1.0.0-beta.1
1.0.0-beta.0
0.14.6
0.14.5
0.14.4
0.14.3
retired
0.14.2
0.14.1
0.14.0
0.13.0
0.12.0
0.11.1
0.10.1
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.4
0.7.2
0.7.1
0.7.0
0.6.3
0.6.2
0.6.1
0.6.0
0.5.2
0.5.0
0.4.1
0.4.0
0.3.1
0.3.0
0.2.0
0.1.1
0.1.0
Elixir Authentication framework
Current section
Files
Jump to
Current section
Files
lib/guardian/plug/error_handler.ex
defmodule Guardian.Plug.ErrorHandler do
@moduledoc """
A default error handler that can be used for failed authentication
"""
@callback unauthenticated(Plug.t, Map.t) :: Plug.t
@callback unauthorized(Plug.t, Map.t) :: Plug.t
import Plug.Conn
def unauthenticated(conn, _params) do
respond(conn, response_type(conn), 401, "Unauthenticated")
end
def unauthorized(conn, _params) do
respond(conn, response_type(conn), 403, "Unauthorized")
end
def already_authenticated(conn, _params) do
conn |> halt
end
defp respond(conn, :json, status, msg) do
try do
conn
|> configure_session(drop: true)
|> put_resp_content_type("application/json")
|> send_resp(status, Poison.encode!(%{errors: [msg]}))
rescue ArgumentError ->
conn
|> put_resp_content_type("application/json")
|> send_resp(status, Poison.encode!(%{errors: [msg]}))
end
end
defp respond(conn, :html, status, msg) do
try do
conn
|> configure_session(drop: true)
|> put_resp_content_type("text/plain")
|> send_resp(status, msg)
rescue ArgumentError ->
conn
|> put_resp_content_type("text/plain")
|> send_resp(status, msg)
end
end
defp response_type(conn) do
accept = accept_header(conn)
cond do
Regex.match?(~r/json/, accept) -> :json
true -> :html
end
end
defp accept_header(conn) do
value = conn
|> get_req_header("accept")
|> List.first
value || ""
end
end