はじめに
- mix_phx_gen_auth_demoを動かしてみます
- そのうち
mix phx.gen.auth
コマンドが使えるようになることでしょう - ElixirのSlackで知り合いになった方とDMをやりとりしていて、An upcoming authentication solution for Phoenixという記事を教えてもらいました
An upcoming authentication solution for Phoenix に書いてあること(私がポイントだとおもったところ)
-
Elixirの作者であるJosé Valimさんは、authenticationにも精通している
I am no stranger to authentication.
-
Ruby on RailsのauthenticationソリューションDeviseは、最も多くダウンロードされたもので、キャリアパスを変えたもの(Elixir界隈に専念するようになった)
- torifukukaiouはElixirやPhoenixよりもRuby on Railsのほうを先に使ったことがあって、Deviseも使ったことがあります
- ずいぶん前からJosé Valimさんにはずいぶんお世話になっていたことに気づきました
- Phoenix向けのDeviseを作らないのかとよくきかれた
- いろいろ考えた、試行錯誤した
Therefore, with all things considered, there is very little space for an authentication
framework. So what does it mean? Everyone has to write their
authentication system from scratch?
Not really. My proposed solution is to provide generators to inject all
relevant authentication code into your application.
- すべてのことを考慮すると、Webアプリケーションフレームワークの中においてauthenticationフレームワークに残された余地はほとんどない。ということはつまり、誰もが自分のauthenticationシステムをスクラッチで開発しないといけないのだろうか?
- いいえ、そんなことはない。ここで提案する解決策は、関連するすべてのauthenticationコードをアプリケーションに注入するジェネレータを提供することだ!
mix phx.gen.auth
- これを決心したから3ステップのとりくみがあって、その3番目は
- あとはPhoenixのつまらない(!?)アプリケーションコードを書くだけなのである :-)
Then all that is left is to write plain and boring Phoenix application code :-)
- そうして書いたのがa pull request to a bare Phoenix applicationである
- 以下、この↑プロジェクトを動かしてみます
必要なもの
-
Elixir 1.10.2
- 違うバージョンでもいいのかも、とりあえず私が使ったバージョン
- PostgreSQL
- Node.js
- Would you refer to Installation ?
動かしてみる
% git clone https://github.com/dashbitco/mix_phx_gen_auth_demo.git
% git checkout -b auth origin/auth
- masterブランチにはないので、authブランチに切り替えます
mix.exsのdepsを書き直す
mix.exs
defp deps do
[
{:bcrypt_elixir, "~> 2.0"},
#{:phoenix, github: "phoenixframework/phoenix", override: true},
{:phoenix, "1.5.0-rc.0", override: true},
- 私の環境の問題だけかもしれませんが、
mix deps.get
がうまく進まなかったので書き換えました
% mix local.hex # 要らないのかも?
% mix archive.install hex phx_new 1.5.0-rc.0 # 要らないのかも?
% mix deps.get
- PostgreSQLの
postgres
にSuperuser
のロールがあることを確認する
% psql postgres
psql (12.2)
Type "help" for help.
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser, Create DB | {}
root | Create DB | {}
torifuku | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
- もし
Superuser
のロールがない場合にはつけてください- PostgreSQLでユーザのロールを変更する
- ありがとうございます!
postgres=# ALTER ROLE postgres WITH SUPERUSER;
- なぜ
Superuser
のロールが必要なのかは正確にはわかっていませんが、無いとあとで怒られます-
priv/repo/migrations/20200316103722_create_users_auth_tables.exs
の中に、execute "CREATE EXTENSION IF NOT EXISTS citext", ""
行があって、これを実行するのにSuperuser
のロールが必要なのだそうです - citextは、大文字小文字の区別がない文字列型 のことだそうです
-
% mix ecto.setup
% npm install --prefix assets
% mix phx.server

Yay!
Wrapping Up
-
mix_phx_gen_auth_demoプロジェクトで、
mix phx.gen.auth
で注入されることになるであろうコードを確認できます - まだチラ見しかしていませんがそんなに長くないです
- authenticationのコードを注入できるようにしたからあとは、お好みで各自カスタマイズしてねってことだとおもいます
- 楽しんでいきましょう!