2021-02-24 07:49:39 -05:00
|
|
|
defmodule Bones73kWeb.LiveHelpers do
|
2020-09-14 10:17:47 -04:00
|
|
|
import Phoenix.LiveView
|
2021-02-24 07:49:39 -05:00
|
|
|
alias Bones73k.Accounts
|
|
|
|
alias Bones73k.Accounts.User
|
|
|
|
alias Bones73kWeb.Router.Helpers, as: Routes
|
|
|
|
alias Bones73kWeb.UserAuth
|
2020-09-14 12:22:25 -04:00
|
|
|
import Phoenix.LiveView.Helpers
|
|
|
|
|
|
|
|
@doc """
|
2021-02-24 07:49:39 -05:00
|
|
|
Renders a component inside the `Bones73kWeb.ModalComponent` component.
|
2020-09-14 12:22:25 -04:00
|
|
|
|
|
|
|
The rendered modal receives a `:return_to` option to properly update
|
|
|
|
the URL when the modal is closed.
|
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
2021-02-24 07:49:39 -05:00
|
|
|
<%= live_modal @socket, Bones73kWeb.PropertyLive.FormComponent,
|
2020-09-14 12:22:25 -04:00
|
|
|
id: @property.id || :new,
|
|
|
|
action: @live_action,
|
|
|
|
property: @property,
|
|
|
|
return_to: Routes.property_index_path(@socket, :index) %>
|
|
|
|
"""
|
|
|
|
def live_modal(socket, component, opts) do
|
|
|
|
path = Keyword.fetch!(opts, :return_to)
|
|
|
|
modal_opts = [id: :modal, return_to: path, component: component, opts: opts]
|
2021-02-24 07:49:39 -05:00
|
|
|
live_component(socket, Bones73kWeb.ModalComponent, modal_opts)
|
2020-09-14 12:22:25 -04:00
|
|
|
end
|
2020-09-14 10:17:47 -04:00
|
|
|
|
|
|
|
def assign_defaults(session, socket) do
|
2021-02-24 07:49:39 -05:00
|
|
|
Bones73kWeb.Endpoint.subscribe(UserAuth.pubsub_topic())
|
2020-09-28 05:06:15 -04:00
|
|
|
|
2020-09-14 10:17:47 -04:00
|
|
|
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
|