Separate token creation action into Hostas.Token

This commit is contained in:
Nat 2023-06-08 18:01:47 -07:00
parent 711353398c
commit 89eea2d4c1
Signed by: nat
GPG Key ID: B53AB05285D710D6
2 changed files with 26 additions and 12 deletions

View File

@ -2,6 +2,14 @@ defmodule Hostas.Token do
use Ecto.Schema
import Ecto.Changeset
alias Hostas.Token
alias Hostas.Repo
@doc """
The number of days a token lasts from the moment of its creation
"""
@duration_days 30
schema "tokens" do
field :denizen_id, :integer
field :expires, :utc_datetime
@ -19,4 +27,20 @@ defmodule Hostas.Token do
|> cast(attrs, [:denizen_id, :expires])
|> validate_required([:denizen_id, :expires])
end
@doc """
Creates a token
"""
def new(denizen_id) do
# Create a random token
token = Base.encode64(:crypto.strong_rand_bytes(256))
# Calculate the time of expiry
{:ok, time_now} = DateTime.now("Etc/UTC")
expiry = DateTime.add(time_now, @duration_days, :day)
|> DateTime.truncate(:second)
# Register the token
Repo.insert(changeset(%Token{}, %{denizen_id: denizen_id, token: token, expires: expiry}))
end
end

View File

@ -23,17 +23,7 @@ defmodule HostasWeb.Auth.TokenController do
%{id: denizen_id, password: real_password_hash} = denizen
if Bcrypt.verify_pass(given_password, real_password_hash) do
# Create a random token
token = Base.encode64(:crypto.strong_rand_bytes(256))
# Calculate when the token should expire
{:ok, time_now} = DateTime.now("Etc/UTC")
expiry = DateTime.add(time_now, 30, :day)
|> DateTime.truncate(:second)
# Register the token
{:ok, token_struct} = Repo.insert(
%Token{denizen_id: denizen_id, token: token, expires: expiry})
{:ok, token_struct} = Token.new(denizen_id)
conn
|> put_status(201)
@ -47,7 +37,7 @@ defmodule HostasWeb.Auth.TokenController do
end
end
def create(conn, params) do
def create(conn, _params) do
conn
|> put_status(422)
|> json(%{"error" => "Missing required parameters"})