philomena/lib/philomena_web/plugs/session.ex

53 lines
1.1 KiB
Elixir
Raw Normal View History

2019-08-19 04:03:12 +02:00
defmodule PhilomenaWeb.Plugs.Session do
2019-08-17 20:58:36 +02:00
use Pow.Plug.Base
alias Plug.Conn
alias Philomena.{Repo, Users.User}
@session_key :philomena_session
def fetch(conn, _config) do
conn = Conn.fetch_session(conn)
user = Conn.get_session(conn, @session_key)
conn
|> maybe_load_user(user)
end
def create(conn, user, _config) do
2019-08-18 00:06:11 +02:00
value = session_value(user)
2019-08-17 20:58:36 +02:00
conn =
conn
|> Conn.fetch_session()
2019-08-18 00:06:11 +02:00
|> Conn.put_session(@session_key, value)
2019-08-17 20:58:36 +02:00
{conn, user}
end
def delete(conn, _config) do
conn
|> Conn.fetch_session()
|> Conn.delete_session(@session_key)
end
defp maybe_load_user(conn, {:ok, user}) do
with {:ok, [user_id, hash]} <- Jason.decode(user),
%User{} = user <- Repo.get(User, user_id),
2019-08-18 00:06:11 +02:00
true <- SecureCompare.compare(hash, binary_part(user.encrypted_password, 0, 25)) do
2019-08-17 20:58:36 +02:00
{conn, user}
else
_ ->
{conn, nil}
end
end
2019-08-18 00:06:11 +02:00
2019-08-17 20:58:36 +02:00
defp maybe_load_user(conn, _) do
{conn, nil}
end
defp session_value(user) do
Jason.encode([user.id, binary_part(user.encrypted_password, 0, 25)])
end
2019-08-18 00:06:11 +02:00
end