32 lines
843 B
Elixir
32 lines
843 B
Elixir
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
|
|
|> Phoenix.Controller.redirect(to: Routes.login_path(Endpoint, :login))
|
|
|> 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])
|
|
assign(conn, :user, user)
|
|
end
|
|
end
|
|
end
|
|
end
|