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
@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
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}
struct ->
unless expired?(struct) do
{:ok, struct}
else
:expired
{:error, :expired}
end
end
end

View File

@ -33,12 +33,16 @@ defmodule Hostas.TokenTest do
test "indicates the token is expired" do
{:ok, struct} = Token.new(create_denizen().id, -30)
assert Token.get(struct.token) == :expired
assert Token.get(struct.token) == {:error, :expired}
end
test "by key" do
{: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

View File

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