1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
|