diff options
Diffstat (limited to 'lib/lsg/auth_token.ex')
-rw-r--r-- | lib/lsg/auth_token.ex | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/lib/lsg/auth_token.ex b/lib/lsg/auth_token.ex new file mode 100644 index 0000000..0c5ba58 --- /dev/null +++ b/lib/lsg/auth_token.ex @@ -0,0 +1,59 @@ +defmodule LSG.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} -> + LSGWeb.Router.Helpers.login_path(LSGWeb.Endpoint, :token, id) + error -> + error + end + end + + def new_url(account, perks \\ nil) do + case new(account, perks) do + {:ok, id} -> + LSGWeb.Router.Helpers.login_url(LSGWeb.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 |