Elixir Digitalization Implementors/fukuoka.ex/kokura.exのpiacereです
ご覧いただいて、ありがとうございます
前回に引き続き、Phoenixユーザ認証ライブラリ「phx_gen_auth」のプロダクション向け改造ポイントとして、今回は、コントローラ内/テンプレート内に散らばっているエラー時などのメッセージのカスタマイズについて解説します

Elixir ranked second on the Qiita Advent calendar 
In the programming language category ranking, Rust was 1st, Elixir was 2nd, Golang was 3rd, and all were modern programming languages.
https://qiita.com/advent-calendar/2020/elixir
In addition, our Elixir community "fukuoka.ex" has won the top spot in the Web Technology category.
https://qiita.com/advent-calendar/2020/fukuokaex
本コラムの検証環境
本コラムは、以下環境で検証しています(Windowsで実施していますが、Linuxやmacでも動作する想定です)
- Windows 11
- Elixir 1.12.0 on WSL2 Ubuntu ※最新版のインストール手順はコチラ
- Phoenix 1.6.0 ※最新版のインストール手順はコチラ
- PostgreSQL 10.17 ※最新版のインストール手順はコチラ
なお、本コラム内で扱うPhoenix PJ名は「basic」、phx_gen_authのコンテキスト名は「Accounts」を前提にしています
⑤メッセージのカスタマイズ
④-1:コントローラ内のメッセージ
対象ファイルは、以下の通りです
ファイルパス | |
---|---|
lib/basic_web/controllers/account_auth.ex | 未ログイン時のメッセージを定義 |
lib/basic_web/controllers/account_confirmation_controller.ex | ユーザ仮登録後の本登録に関するメッセージを定義 |
lib/basic_web/controllers/account_registration_controller.ex | ユーザ登録時のメッセージを定義 |
lib/basic_web/controllers/account_reset_password_controller.ex | パスワードリマインダに関するメッセージを定義 |
lib/basic_web/controllers/account_session_controller.ex | ログインに関するメッセージを定義 |
lib/basic_web/controllers/account_settings_controller.ex | メールアドレス/パスワード変更に関するメッセージを定義 |
たとえば、未ログイン時のエラーメッセージを変更する場合は、下記のようにメッセージ変更します
…
def require_authenticated_account(conn, _opts) do
if conn.assigns[:current_account] do
conn
else
conn
# |> put_flash(:error, "You must log in to access this page.") # <-- comment-out here
|> put_flash(:error, "本ページにアクセスする際は、ログインを行ってください" ) # <-- add here
|> maybe_store_return_to()
|> redirect(to: Routes.account_session_path(conn, :new))
|> halt()
end
end
…
他ファイルのメッセージを変更する場合も、put_flash()内の文字列を更新してください
④-2:テンプレート内のメッセージ
対象ファイルは、以下の通りです
ファイルパス | 役割 |
---|---|
lib/basic_web/templates/account_registration/new.html.heex | ユーザ登録時エラーメッセージを定義 |
lib/basic_web/templates/account_reset_password/edit.html.heex | パスワードリマインダのパスワードリセット時エラーメッセージを定義 |
lib/basic_web/templates/account_session/new.html.heex | ログイン時エラーメッセージを定義 |
lib/basic_web/templates/account_settings/edit.html.heex | メールアドレス/パスワード変更時エラーメッセージを定義 |
たとえば、ユーザ登録時エラーメッセージを変更する場合は、下記のようにメッセージ変更します
<h1>Register</h1>
<.form let={f} for={@changeset} action={Routes.account_registration_path(@conn, :create)}>
<%= if @changeset.action do %>
<div class="alert alert-danger">
<!--<p>Oops, something went wrong! Please check the errors below.</p>-->
<p>ユーザ登録時にエラーが発生しました</p>
</div>
<% end %>
…
他ファイルのメッセージを変更する場合も、<div class="alert alert-danger">
配下の文字列を更新してください
最後に
今回は、「phx_gen_auth」のプロダクション向け改造ポイントのうち、コントローラ内/テンプレート内に散らばっているエラー時などのメッセージのカスタマイズを行いました
第1回で変更したバリデーションメッセージだけで無く、各ページ全体のエラーメッセージ等は、今回の対応が必要となるため、プロダクション時は見逃さないよう、注意ください
次回は最終回、ユーザ仮登録を有効にします