Packages
joken
1.3.0
2.6.2
2.6.1
2.6.0
2.5.0
2.4.1
2.4.0
2.3.0
2.2.0
2.1.0
2.0.1
2.0.0
2.0.0-rc3
2.0.0-rc2
2.0.0-rc1
2.0.0-rc0
1.5.0
1.4.1
1.4.0
1.3.2
1.3.1
1.3.0
1.2.2
1.2.1
1.2.0
1.1.1
1.1.0
1.0.1
1.0.0
0.16.1
0.16.0
0.15.0
0.14.1
0.14.0
0.13.1
0.13.0
0.12.0
0.11.0
0.10.1
0.10.0
0.8.1
0.8.0
0.7.0
0.6.2
0.6.1
0.6.0
0.5.0
0.1.0
JWT (JSON Web Token) library for Elixir.
Current section
Files
Jump to
Current section
Files
lib/joken/claims.ex
defprotocol Joken.Claims do
@moduledoc """
Handles turning data into claims when using the `with_claims` function in the
`Joken` module.
There is a default implementation for maps.
Implementing `to_claims` expects a map to be returned.
Structs can derive from `Joken.Claims` to be used as claims
defmodule FullDerive do
@derive Joken.Claims
defstruct [:a, :b, :c]
end
derive supports using the `only` or `exclude` option as well
"""
@spec to_claims(any) :: map
def to_claims(data)
end
defimpl Joken.Claims, for: Any do
defmacro __deriving__(module, struct, options) do
deriving(module, struct, options)
end
def deriving(module, _struct, options) do
extractor = cond do
options[:only] && options[:exclude] ->
raise ArgumentError, message: "Cannot use both :only and :exclude"
only = options[:only] ->
quote(do: Map.take(data, unquote(only)))
exclude = options[:exclude] ->
quote(do: Map.drop(data, [:__struct__ | unquote(exclude)]))
true ->
quote(do: :maps.remove(:__struct__, data))
end
quote do
defimpl Joken.Claims, for: unquote(module) do
def to_claims(data) do
Joken.Claims.Map.to_claims(unquote(extractor))
end
end
end
end
def to_claims(data) do
raise Protocol.UndefinedError, value: data
end
end
defimpl Joken.Claims, for: Map do
defmacro __deriving__(module, struct, options) do
Joken.Claims.Any.deriving(module, struct, options)
end
def to_claims(data) do
Enum.reduce data, %{}, fn({key, value}, acc) ->
case key do
key when is_atom(key) ->
Map.put(acc, Atom.to_string(key), value)
key when is_binary(key) ->
Map.put(acc, key, value)
_ ->
raise "Claim keys must be binaries"
end
end
end
end