diff --git a/lib/hostas/token.ex b/lib/hostas/token.ex index 7211f8d..10bf1c8 100644 --- a/lib/hostas/token.ex +++ b/lib/hostas/token.ex @@ -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 diff --git a/lib/hostas_web/controllers/auth/token_controller.ex b/lib/hostas_web/controllers/auth/token_controller.ex index 1713b24..7593d99 100644 --- a/lib/hostas_web/controllers/auth/token_controller.ex +++ b/lib/hostas_web/controllers/auth/token_controller.ex @@ -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"})