diff --git a/lib/real_estate_web.ex b/lib/real_estate_web.ex index fbc50ffa..441b3bc2 100644 --- a/lib/real_estate_web.ex +++ b/lib/real_estate_web.ex @@ -48,6 +48,7 @@ defmodule RealEstateWeb do layout: {RealEstateWeb.LayoutView, "live.html"} unquote(view_helpers()) + import RealEstateWeb.LiveHelpers end end diff --git a/lib/real_estate_web/live/live_helpers.ex b/lib/real_estate_web/live/live_helpers.ex new file mode 100644 index 00000000..7bbc9f62 --- /dev/null +++ b/lib/real_estate_web/live/live_helpers.ex @@ -0,0 +1,29 @@ +defmodule RealEstateWeb.LiveHelpers do + import Phoenix.LiveView + alias RealEstate.Accounts + alias RealEstate.Accounts.User + alias RealEstateWeb.Router.Helpers, as: Routes + + def assign_defaults(session, socket) do + socket = + assign_new(socket, :current_user, fn -> + find_current_user(session) + end) + + case socket.assigns.current_user do + %User{} -> + socket + + _other -> + socket + |> put_flash(:error, "You must log in to access this page.") + |> redirect(to: Routes.user_session_path(socket, :new)) + end + end + + defp find_current_user(session) do + with user_token when not is_nil(user_token) <- session["user_token"], + %User{} = user <- Accounts.get_user_by_session_token(user_token), + do: user + end +end diff --git a/lib/real_estate_web/live/page_live.ex b/lib/real_estate_web/live/page_live.ex index 420c1ec4..681915e2 100644 --- a/lib/real_estate_web/live/page_live.ex +++ b/lib/real_estate_web/live/page_live.ex @@ -2,7 +2,8 @@ defmodule RealEstateWeb.PageLive do use RealEstateWeb, :live_view @impl true - def mount(_params, _session, socket) do + def mount(_params, session, socket) do + socket = assign_defaults(session, socket) {:ok, assign(socket, query: "", results: %{})} end