4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Routerでのphx.gen.auth権限設定

Last updated at Posted at 2024-09-10

目的

ログインしているユーザーのみ参照できるページを作る

プロジェクト作成

$ mix phx.new auth_experiment --database sqlite3
$ cd auth_experiment
$ mix ecto.create

認証を作る

$ mix phx.gen.auth Accounts User users
$ mix deps.get
$ mix ecto.migrate

認証済みの時のページ作成

lib/auth_experiment_web/live/page_ok_live.ex
defmodule AuthExperimentWeb.PageOkLive do
  use AuthExperimentWeb, :live_view

  @impl Phoenix.LiveView
  def mount(_params, _session, socket) do
    {:ok, socket}
  end
end
lib/auth_experiment_web/live/page_ok_live.html.heex
<h1>認証済みページ</h1>

Routerでのphx.gen.auth権限設定

lib/auth_experiment_web/router.ex
defmodule AuthExperimentWeb.Router do
  # 〜省略〜
  scope "/", AuthExperimentWeb do
    pipe_through [:browser, :require_authenticated_user]

    live_session :require_authenticated_user,
      on_mount: [{AuthExperimentWeb.UserAuth, :ensure_authenticated}] do
+     live "/pageok", PageOkLive, :index
      live "/users/settings", UserSettingsLive, :edit
      live "/users/settings/confirm_email/:token", UserSettingsLive, :confirm_email
    end
  end
  # 〜省略〜
end

実行

$ mix phx.server

http://localhost:4000/users/register でアカウントをつくる

http://localhost:4000/pageok にアクセス

ログインし認証済み
image.png

未認証
image.png

ソース(github)

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?