How to Use Built-In Phoenix Authentication
From ElixirBlocks
This page is in progress
Phoenix has a built in authentication generator.
To use the feature, you can run the following command:
mix phx.gen.auth Accounts User users
You are asked to choose the form of authentication that you want. The 2 choices are LiveView authentication or Controller based authentication.
LiveView Authentication
How to Restrict a Route to an Authenticated User
In the example below is a route named /sandbox.
Route
scope "/", AppWeb do pipe_through [:browser, :require_authenticated_user] #:require_authenticated_user live "/sandbox", SandboxLive end
Component
defmodule AppWeb.SandboxLive do use AppWeb, :live_view on_mount {AppWeb.UserAuth, :ensure_authenticated} def mount(_params, _session, socket) do {:ok, socket} end def render(assigns) do ~H""" SANDBOX <div><% @current_user.id %></div> """ end end
Check for Authenticating of Individual Heex Modules
defmodule AppWeb.PageLive do use AppWeb, :live_view on_mount {AppWeb.UserAuth, :mount_current_user } def mount(_params, _session, socket) do {:ok, socket} end def child_panel(assigns) do ~H""" <div> <%= if @auth_check do %> <!--This works--> <p> This is only viewed if authenticated</p> <% end %> <p> THis is viewed to all users</p> </div> """ end def render(assigns) do ~H""" <div> <p> Hello World! Do you see the text below?</p> <%= if @current_user do %> <p> This is only viewed if authenticated</p> <% end %> <.child_panel auth_check={@current_user}></.child_panel> <!-- This works--> </div> """ end end