frenzy/lib/frenzy_web/plug/authenticate.ex

34 lines
913 B
Elixir
Raw Permalink Normal View History

2019-03-23 23:42:38 +00:00
defmodule FrenzyWeb.Plug.Authenticate do
import Plug.Conn
alias Frenzy.{Repo, User}
alias FrenzyWeb.Router.Helpers, as: Routes
alias FrenzyWeb.Endpoint
def init(opts), do: opts
def call(conn, _opts) do
user_token = get_session(conn, :user_token)
case Phoenix.Token.verify(Endpoint, "user token", user_token, max_age: 24 * 60 * 60) do
{:error, _reason} ->
conn
2020-07-18 14:16:25 +00:00
|> Phoenix.Controller.redirect(
to: Routes.login_path(Endpoint, :login, continue: Phoenix.Controller.current_path(conn))
)
2019-03-23 23:42:38 +00:00
|> halt()
{:ok, user_id} ->
case Repo.get(User, user_id) do
nil ->
conn
|> Phoenix.Controller.redirect(to: Routes.login_path(Endpoint, :login))
|> halt()
user ->
user = Repo.preload(user, [:groups, :feeds])
2019-03-23 23:42:38 +00:00
assign(conn, :user, user)
end
end
end
end