Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow custom error messages on claim validation #221

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/joken.ex
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ defmodule Joken do
- Signer configuration
- Hooks

The portable token claims configuration is a map of binary keys to `Joken.Claim` structs and is used
The portable token claims configuration is a map of binary keys to `Joken.Claim` structs and is used
to dynamically generate and validate tokens.

A signer is an instance of `Joken.Signer` that encapsulates the algorithm and the key configuration
Expand Down Expand Up @@ -400,7 +400,8 @@ defmodule Joken do
"""
end)

{:halt, {:error, message: "Invalid token", claim: key, claim_val: claim_val}}
message = Keyword.get(config[key].options, :message, "Invalid token")
{:halt, {:error, message: message, claim: key, claim_val: claim_val}}
end
end)
|> case do
Expand Down
20 changes: 19 additions & 1 deletion test/joken_test.exs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
defmodule JokenTest do
use ExUnit.Case, async: true
import ExUnit.CaptureLog
import Joken.Config, only: [add_claim: 4, default_claims: 1]
import Joken.Config, only: [add_claim: 4, add_claim: 5, default_claims: 1]
alias Joken.CurrentTime.Mock

setup do
Expand Down Expand Up @@ -78,6 +78,24 @@ defmodule JokenTest do
"Claim %{\"iss\" => \"someone\"} did not pass validation.\n\nCurrent time: "
end

test "claim attaches custom error message" do
custom_error_message = "Someone should not be there"

token_config =
%{}
|> add_claim(
"iss",
fn -> "not someone" end,
fn val ->
val == "not someone"
end,
message: custom_error_message
)

assert {:error, [message: custom_error_message, claim: "iss", claim_val: "someone"]} ==
Joken.validate(token_config, %{"iss" => "someone"}, %{})
end

test "can make multi claim validation" do
token_config = %{} |> add_claim("claim1", nil, &(&1 == &2["claim2"]))

Expand Down