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