How to Use Built-In Phoenix Authentication: Difference between revisions

From ElixirBlocks
Jump to: navigation, search
(Created page with "{{In_progress}} <hr/> Phoenix has a built in authentication generator. To use the feature, you can run the following command: <source> mix phx.gen.auth Accounts User users </source> You are asked to choose the form of authentication that you want. The 2 choices are LiveView authentication or Controller based authentication. ==LiveView Authentication== ==Controller Based Authentication==")
 
No edit summary
Line 14: Line 14:


==LiveView Authentication==
==LiveView Authentication==
===How to Restrict a Route to an Authenticated User===
In the example below is a route named /sandbox.
'''Route'''
<source>
  scope "/", AppWeb do
    pipe_through [:browser, :require_authenticated_user]  #:require_authenticated_user
    live "/sandbox", SandboxLive
  end
</source>
'''Component'''
<source>
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
</source>


==Controller Based Authentication==
==Controller Based Authentication==

Revision as of 02:18, 3 December 2023

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


Controller Based Authentication