defmodule Nola.AuthToken do
use GenServer
def start_link() do
GenServer.start_link(__MODULE__, [], [name: __MODULE__])
end
def lookup(id) do
GenServer.call(__MODULE__, {:lookup, id})
end
def new_path(account, perks \\ nil) do
case new(account, perks) do
{:ok, id} ->
NolaWeb.Router.Helpers.login_path(NolaWeb.Endpoint, :token, id)
error ->
error
end
end
def new_url(account, perks \\ nil) do
case new(account, perks) do
{:ok, id} ->
NolaWeb.Router.Helpers.login_url(NolaWeb.Endpoint, :token, id)
error ->
error
end
end
def new(account, perks \\ nil) do
GenServer.call(__MODULE__, {:new, account, perks})
end
def init(_) do
{:ok, Map.new}
end
def handle_call({:lookup, id}, _, state) do
IO.inspect(state)
with \
{account, date, perks} <- Map.get(state, id),
d when d > 0 <- DateTime.diff(date, DateTime.utc_now())
do
{:reply, {:ok, account, perks}, Map.delete(state, id)}
else
x ->
IO.inspect(x)
{:reply, {:error, :invalid_token}, state}
end
end
def handle_call({:new, account, perks}, _, state) do
id = IRC.UserTrack.Id.token()
expire = DateTime.utc_now()
|> DateTime.add(15*60, :second)
{:reply, {:ok, id}, Map.put(state, id, {account, expire, perks})}
end
end