46 lines
1.1 KiB
Elixir
46 lines
1.1 KiB
Elixir
defmodule ClacksWeb.Plug.WebAuthenticate do
|
|
import Plug.Conn
|
|
alias Clacks.{Repo, User}
|
|
alias ClacksWeb.Router.Helpers, as: Routes
|
|
alias ClacksWeb.Endpoint
|
|
|
|
def init([on_failure: on_failure_action] = opts)
|
|
when on_failure_action in [:redirect_to_login, :pass],
|
|
do: opts
|
|
|
|
def init(_opts) do
|
|
[on_failure: :redirect_to_login]
|
|
end
|
|
|
|
def call(%Plug.Conn{assigns: %{format: "html"}} = conn, on_failure: on_failure_action) do
|
|
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
|
|
|
|
def call(conn, _opts), do: conn
|
|
|
|
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
|