Packages
guardian
0.13.0
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/load_resource.ex
defmodule Guardian.Plug.LoadResource do
@moduledoc """
Fetches the resource specified in a set of claims.
The current resource is loaded by calling `from_token/1` on your
`Guardian.Serializer` with the value of the `sub` claim. See the `:serializer`
option for more details.
If the the resource is loaded successfully, it is accessible by calling
`Guardian.Plug.current_resource/2`.
If there is no valid JWT in the request so far (`Guardian.Plug.VerifySession`
/ `Guardian.Plug.VerifyHeader`) did not find a valid token
then nothing will occur, and `Guardian.Plug.current_resource/2` will be nil.
## Options
* `:serializer` - The serializer to use to load the current resource from
the subject claim of the token. Defaults to the result of
`Guardian.serializer/0`.
"""
@doc false
def init(opts \\ %{}), do: Enum.into(opts, %{})
@doc false
def call(conn, opts) do
key = Map.get(opts, :key, :default)
case Guardian.Plug.current_resource(conn, key) do
nil ->
case Guardian.Plug.claims(conn, key) do
{:ok, claims} ->
claims |> load_resource(opts) |> put_current_resource(conn, key)
{:error, _} -> Guardian.Plug.set_current_resource(conn, nil, key)
end
_ -> conn
end
end
defp put_current_resource({:ok, resource}, conn, key) do
Guardian.Plug.set_current_resource(conn, resource, key)
end
defp put_current_resource({:error, _}, conn, key) do
Guardian.Plug.set_current_resource(conn, nil, key)
end
defp load_resource(claims, opts) do
serializer = get_serializer(opts)
claims |> Map.get("sub") |> serializer.from_token
end
defp get_serializer(opts) do
Map.get(opts, :serializer, Guardian.serializer)
end
end