Fix authentication on posts page

This commit is contained in:
Logan Hunt 2022-04-06 14:41:19 -06:00
parent 5ad6bbfce7
commit 61c2c9370a
Signed by untrusted user who does not match committer: simponic
GPG Key ID: 52B3774857EB24B1
4 changed files with 21 additions and 5 deletions

View File

@ -4,6 +4,9 @@ defmodule AggieditWeb.LiveHelpers do
alias Phoenix.LiveView.JS alias Phoenix.LiveView.JS
alias Aggiedit.Accounts
alias Aggiedit.Accounts.User
@doc """ @doc """
Renders a live component inside a modal. Renders a live component inside a modal.
@ -57,4 +60,13 @@ defmodule AggieditWeb.LiveHelpers do
|> JS.hide(to: "#modal", transition: "fade-out") |> JS.hide(to: "#modal", transition: "fade-out")
|> JS.hide(to: "#modal-content", transition: "fade-out-scale") |> JS.hide(to: "#modal-content", transition: "fade-out-scale")
end end
def assign_socket_user(session, socket) do
with token when not is_nil(token) <- session["user_token"],
current_user=%User{} = Accounts.get_user_by_session_token(token) do
assign(socket, :current_user, current_user)
else
_ -> socket
end
end
end end

View File

@ -5,8 +5,12 @@ defmodule AggieditWeb.PostLive.Index do
alias Aggiedit.Rooms.Post alias Aggiedit.Rooms.Post
@impl true @impl true
def mount(_params, _session, socket) do def mount(_params, session, socket) do
{:ok, assign(socket, :posts, list_posts())} socket = assign_socket_user(session, socket)
case socket.assigns do
%{:current_user => user} -> {:ok, assign(socket, :posts, list_posts())}
_ -> {:ok, socket |> put_flash(:error, "You must log in to access this page.") |> redirect(to: Routes.user_session_path(socket, :new))}
end
end end
@impl true @impl true

View File

@ -21,7 +21,10 @@ defmodule AggieditWeb.Router do
pipe_through :browser pipe_through :browser
get "/", PageController, :index get "/", PageController, :index
end
scope "/", AggieditWeb do
pipe_through [:browser, :require_authenticated_user]
live "/posts", PostLive.Index, :index live "/posts", PostLive.Index, :index
live "/posts/new", PostLive.Index, :new live "/posts/new", PostLive.Index, :new
live "/posts/:id/edit", PostLive.Index, :edit live "/posts/:id/edit", PostLive.Index, :edit

View File

@ -21,9 +21,6 @@
</ul> </ul>
<%= render "_user_menu.html", assigns %> <%= render "_user_menu.html", assigns %>
</nav> </nav>
<a href="https://phoenixframework.org/" class="phx-logo">
<img src={Routes.static_path(@conn, "/images/phoenix.png")} alt="Phoenix Framework Logo"/>
</a>
</section> </section>
</header> </header>
<%= @inner_content %> <%= @inner_content %>