Add case for unknown token in Token.get/1

This commit is contained in:
Nat 2023-06-12 16:39:22 -07:00
parent 8524e90ac8
commit 7e16cd9ae0
Signed by: nat
GPG Key ID: B53AB05285D710D6
3 changed files with 28 additions and 9 deletions

View File

@ -48,15 +48,20 @@ defmodule Hostas.Token do
end end
@doc """ @doc """
Returns {:ok, struct} if the token hasn't expired. Otherwise, returns :expired Returns:
* `{:ok, struct}` if the token exists and is not expired
* `{:error, :unknown}` if the token was not found
* `{:error, :expired}` if the token exists, but is expired
""" """
def get(key) do def get(key) do
struct = Repo.one!(from t in Token, where: t.token == ^key) case Repo.one(from t in Token, where: t.token == ^key) do
nil -> {:error, :unknown}
unless expired?(struct) do struct ->
{:ok, struct} unless expired?(struct) do
else {:ok, struct}
:expired else
{:error, :expired}
end
end end
end end

View File

@ -33,12 +33,16 @@ defmodule Hostas.TokenTest do
test "indicates the token is expired" do test "indicates the token is expired" do
{:ok, struct} = Token.new(create_denizen().id, -30) {:ok, struct} = Token.new(create_denizen().id, -30)
assert Token.get(struct.token) == :expired assert Token.get(struct.token) == {:error, :expired}
end end
test "by key" do test "by key" do
{:ok, struct} = Token.new(create_denizen().id, -30) {:ok, struct} = Token.new(create_denizen().id, -30)
assert Token.expired?(struct.token) assert Token.get(struct.token) == {:error, :expired}
end
test "doesn't exist" do
assert Token.get("unknown token") == {:error, :unknown}
end end
end end

View File

@ -16,6 +16,9 @@ defmodule Hostas.DataCase do
use ExUnit.CaseTemplate use ExUnit.CaseTemplate
alias Hostas.Repo
alias Hostas.Denizen
using do using do
quote do quote do
alias Hostas.Repo alias Hostas.Repo
@ -55,4 +58,11 @@ defmodule Hostas.DataCase do
end) end)
end) end)
end end
def create_denizen(handle \\ "denizen") do
Repo.insert!(
Denizen.changeset(%Denizen{}, %{handle: handle, name: "Test Denizen", password: "password"})
)
end
end end