clacks/lib/clacks_web/plug/web_authenticate.ex

46 lines
1.1 KiB
Elixir
Raw Normal View History

2019-10-02 21:25:35 +00:00
defmodule ClacksWeb.Plug.WebAuthenticate do
import Plug.Conn
alias Clacks.{Repo, User}
alias ClacksWeb.Router.Helpers, as: Routes
alias ClacksWeb.Endpoint
2019-10-06 23:41:18 +00:00
def init([on_failure: on_failure_action] = opts)
2019-10-02 21:25:35 +00:00
when on_failure_action in [:redirect_to_login, :pass],
do: opts
2020-04-27 02:57:47 +00:00
def init(_opts) do
2019-10-06 23:41:18 +00:00
[on_failure: :redirect_to_login]
end
2019-10-02 21:25:35 +00:00
2019-10-06 23:41:18 +00:00
def call(%Plug.Conn{assigns: %{format: "html"}} = conn, on_failure: on_failure_action) do
2019-10-02 21:25:35 +00:00
user_token = get_session(conn, :user_token)
case Phoenix.Token.verify(Endpoint, "user token", user_token, max_age: 7 * 24 * 60 * 60) do
{:error, _reason} ->
on_failure(conn, on_failure_action)
{:ok, user_id} ->
case Repo.get(User, user_id) do
nil ->
on_failure(conn, on_failure_action)
user ->
user = Repo.preload(user, :actor)
assign(conn, :user, user)
end
end
end
2019-10-06 23:41:18 +00:00
def call(conn, _opts), do: conn
2019-10-02 21:25:35 +00:00
defp on_failure(conn, :redirect_to_login) do
conn
|> Phoenix.Controller.redirect(to: Routes.login_path(Endpoint, :login))
|> halt()
end
defp on_failure(conn, :pass) do
conn
end
end