Rails: 認証gem 'rodauth-rails' README(翻訳)
rodauth-railsは、Rodauth認証フレームワークのRails統合を提供します。
関連リソース
🔗 リンク:
🎥 Screencasts/ストリーム:
- Multifactor Authentication via TOTP with Rodauth [4:36]
- Multifactor Authentication via Recovery Codes with Rodauth [4:24]
- Adding Admin Accounts with Rodauth [1:25:55]
- Integrating Passkeys into Rails with Rodauth [59:47]
📚 記事:
- Rodauth: A Refreshing Authentication Solution for Ruby
- Rails Authentication with Rodauth
- Multifactor Authentication in Rails with Rodauth
- How to build an OIDC provider using rodauth-oauth on Rails
- Rails: 認証gem ‘Rodauth’を統合するrodauth-railsを開発しました
- Social Login in Rails with Rodauth
- Passkey Authentication with Rodauth
🔗 Rodauthを使う理由
Railsには、既に有名な認証ソリューションがいくつもあります(Devise、Sorcery、Clearance、Authlogic)が、Rodauthを選ぶ理由は何でしょうか?特に大きな理由を以下に示します。
- 多要素認証が使える
- 標準化されたJSON APIをあらゆる機能でサポート(JWTなど)
- エンタープライズ向けセキュリティ機能
- パスワードレス認証(メール認証、パスキー)
- あらゆる操作の監査ログ出力
- SQLインジェクション攻撃時でもパスワードハッシュを保護 (詳細)
- 統一された設定用DSL(あらゆるものに実行前・実行後、実行前後のフックをかけられる)
🔗 Sequelについて
Railsの他の認証フレームワークを使っていた方がよく気にするのは、RodauthがデータベースとのやりとりにActive RecordではなくSequelを使っています。
rodauth-railsは、Active Recordを用いるRailsアプリ向けに、SequelがActive Recordのデータベースコネクションを再利用する形でSequelを設定します。これによってrodauth-railsはActive Recordとスムーズに連携し、Rodauthの設定内からActive Recordのコードを呼び出すことも可能になっています。Sequelは、単にRodauthの実装詳細として扱えます。
🔗 インストール
プロジェクトにrodauth-rails gemを追加します。
$ bundle add rodauth-rails
続いてインストールジェネレータを実行します。
$ rails generate rodauth:install
このジェネレーターは、一般的な認証機能が有効になったRodauthアプリと設定、それらの機能に必要なテーブルを含むデータベースマイグレーション、その他いくつかのファイルを作成します。不要な機能とそれに対応するテーブルは削除しても構いません。
続いて、マイグレーションを実行します。
$ rails db:migrate
🔗 オプションをインストールする
インストールジェネレータは、デフォルトでaccountsテーブルを利用します。別のテーブル名を指定するには、以下のようにします。
$ rails generate rodauth:install users
RodauthのエンドポイントをJSON APIで公開したい場合は、以下を実行します。
# cookieベースの認証
$ rails generate rodauth:install --json
# または
# トークンベースの認証
$ rails generate rodauth:install --jwt
$ bundle add jwt
パスワードのハッシュにbcryptではなくArgon2を使う場合は以下を実行します。
$ rails generate rodauth:install --argon2
訳注
rails generate rodauth:installでインストールジェネレータを実行すると、以下のようなメッセージが表示されます(rodauth-rails 1.6.2の場合)。
(大意)
アプリケーションの設定によってはいくつかの手動セットアップが必要になる場合があります。
- 1: config/environments/のファイルにデフォルトURLオプションを設定すること。以下はconfig/environments/development.rbにおけるdevelopment環境向けの適切な
default_url_optionsの例です。
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
production環境では、:hostにアプリケーションの実際のホストを設定すること。
(1はすべてのアプリケーションで必須)
- 2: config/routes.rbの
root_urlに以下のような「何らかの」ルーティングを設定すること。
root to: "home#index"
(2はAPI専用アプリケーションでは不要)
- 3: app/views/layouts/application.html.erbで、たとえば以下のようにflashメッセージを表示できるようにしておくこと。
<% if notice %>
<div class="alert alert-success"><%= notice %></div>
<% end %>
<% if alert %>
<div class="alert alert-danger"><%= alert %></div>
<% end %>
(3はAPI専用アプリケーションでは不要)
- 4: Rodauthページのタイトルはデフォルトで
@page_titleインスタンス変数で利用できるので、レイアウトファイルで以下のようにタイトルを表示できます。
<head>
<title><%= @page_title || "Default title" %></title>
...
</head>
(4は必須ではありません)
- 5: 以下を実行すると、Rodauthのビューをコピーしてカスタマイズできるようになります。
rails g rodauth:views
(5は必須ではありません)
🔗 利用法
Rodauthアプリは、Railsルーターに到達する前にリクエストごとに呼び出されます。これによってRodauthのエンドポイントへのリクエストを処理し、メインルートの前に追加のコードを呼び出せるようになります。
$ rails middleware
# ...
# use Rodauth::Rails::Middleware (calls your Rodauth app)
# run YourApp::Application.routes
🔗 ルーティング
RodauthのエンドポイントへのリクエストはRodaによって処理されるため、rails routesではRodauthのルートが表示されない点にご注意ください。
現在読み込まれている機能に基づいてエンドポイントのリストを表示するには、rodauth:routesというrakeタスクを利用できます。
$ rails rodauth:routes
Routes handled by RodauthApp:
login GET|POST /login rodauth.login_path
create_account GET|POST /create-account rodauth.create_account_path
verify_account_resend GET|POST /verify-account-resend rodauth.verify_account_resend_path
verify_account GET|POST /verify-account rodauth.verify_account_path
change_password GET|POST /change-password rodauth.change_password_path
change_login GET|POST /change-login rodauth.change_login_path
logout GET|POST /logout rodauth.logout_path
remember GET|POST /remember rodauth.remember_path
reset_password_request GET|POST /reset-password-request rodauth.reset_password_request_path
reset_password GET|POST /reset-password rodauth.reset_password_path
verify_login_change GET|POST /verify-login-change rodauth.verify_login_change_path
close_account GET|POST /close-account rodauth.close_account_path
この情報を元に、アプリのナビゲーションで以下のように基本的な認証をいくつか追加できます。
<% if rodauth.logged_in? %>
<%= button_to "Sign out", rodauth.logout_path, method: :post %>
<% else %>
<%= link_to "Sign in", rodauth.login_path %>
<%= link_to "Sign up", rodauth.create_account_path %>
<% end %>
これらのルーティングは完全に機能するので、自由にアクセスしてページを移動してみてください。Rodauthに付属するテンプレートは完全な認証を体験可能にすることを目的としており、フォームではBootstrapのマークアップが使われています。
🔗 現在のアカウント
Rodauthオブジェクトは#rails_accountメソッドを定義します。このメソッドはアカウントに現在ログインしているアカウントのモデルインスタンスを返します。コントローラやビューから手軽にアクセスできるヘルパーメソッドを作成できます。
class ApplicationController < ActionController::Base
private
def current_account
rodauth.rails_account
end
helper_method :current_account # ActionController::APIから継承する場合はスキップ
end
🔗 認証を必須にする
Rodauthアプリのルーティングブロックでは、ルーティングの認証をミドルウェアレベルで必須にできます。これにより、認証ロジックのカプセル化を維持できるようになります。
# app/misc/rodauth_app.rb
class RodauthApp < Rodauth::Rails::App
route do |r|
r.rodauth # rodauthリクエストのルーティング
if r.path.start_with?("/dashboard") # /dashboard/* routes
rodauth.require_account # 認証されていない場合はログインページにリダイレクトする
end
end
end
認証は以下のようにコントローラ層でも要求できます。
class ApplicationController < ActionController::Base
private
def authenticate
rodauth.require_account # 認証されていない場合はログインページにリダイレクトする
end
end
class DashboardController < ApplicationController
before_action :authenticate
end
また、Railsのルーターレベルで認証を行うことも可能です。
# config/routes.rb
Rails.application.routes.draw do
constraints Rodauth::Rails.authenticate do
# ... このルーティングでは認証が必須になる ...
end
constraints Rodauth::Rails.authenticate { |rodauth| rodauth.uses_two_factor_authentication? } do
# ... このルーティングは2FAがセットアップ済みの場合にのみ利用可能になる ...
constraints Rodauth::Rails.authenticate(:admin) do
# このルーティングは、セカンダリの"admin"設定で認証される
constraints -> (r) { !r.env["rodauth"].logged_in? } do # or env["rodauth.admin"]
# config/routes.rb
Rails.application.routes.draw do
constraints Rodauth::Rails.authenticate do
# ... このルーティングでは認証が必須になる ...
end
constraints Rodauth::Rails.authenticate { |rodauth| rodauth.uses_two_factor_authentication? } do
# ... このルーティングは2FAがセットアップ済みの場合にのみ利用可能になる ...
end
constraints Rodauth::Rails.authenticate(:admin) do
# このルーティングは、セカンダリの"admin"設定で認証される
end
constraints -> (r) { !r.env["rodauth"].logged_in? } do # or env["rodauth.admin"]
# ... このルーティングは、認証されていない場合にのみ利用可能になる ...
end
end
🔗 コントローラ
Rodauthの設定は Railsコントローラにリンクされます。これは主にビューのレンダリングやCSRF保護の処理に使われますが、Rodauthエンドポイントの周囲で定義されているコールバックやrescueハンドラーも実行します。
# app/misc/rodauth_main.rb
class RodauthMain < Rodauth::Rails::Auth
configure do
rails_controller { RodauthController }
end
end
class RodauthController < ApplicationController
before_action :verify_captcha, only: :login, if: -> { request.post? } # Rodauthエンドポイントの直前に実行される
rescue_from("SomeError") { |exception| ... } # Rodauthエンドポイント前後をrescueする
end
Rodauthコンフィグから以下のようにさまざまなコントローラーメソッドを呼び出すことが可能です。
class RodauthMain < Rodauth::Rails::Auth
configure do
# コントローラのメソッドを呼び出す
after_create_account do
rails_controller_eval { some_controller_method(account_id) }
end
# RailsのURLヘルパーにアクセスする
login_redirect { rails_routes.dashboard_path }
# Railsのリクエストオブジェクトにアクセスする
after_change_password do
if rails_request.format.turbo_stream?
return_response rails_render(turbo_stream: [turbo_stream.replace(...)])
end
end
# Railsのcookieにアクセスする
after_login { rails_cookies.permanent[:last_account_id] = account_id }
end
end
🔗 ビュー
Rodauthに組み込まれているビューテンプレートは使い始めのうちは便利ですが、そのうちマークアップを編集したくなるでしょう。以下のコマンドを実行すればRodauthのビューテンプレートをRailsアプリにコピーできます。
$ rails generate rodauth:views
メインの設定ファイルでRodauthControllerが設定されていれば、上のコマンドによって現在有効なRodauth機能のビューテンプレートがapp/views/rodauth/ディレクトリに生成されます。
Rodauthで利用したい機能のリストをジェネレータに渡せば、それらの機能が使えるビューを作成できます(既存のビューは削除されません)。
# ビューをTailwindマークアップ付きで生成する(@tailwindcss/formsプラグインが必要)
$ rails generate rodauth:views --css=tailwind
# ビューで生成するRodauth機能を指定する
$ rails generate rodauth:views login create_account lockout otp
# ビューでRodauth機能をすべて生成する
$ rails generate rodauth:views --all
# 別のRodauth設定を指定する
$ rails generate rodauth:views webauthn two_factor_base --name admin
🔗 メーラー
デフォルトのメールテンプレートを変更して、バックグラウンドジョブで安全に配信する準備ができたら、以下のコマンドを実行してメーラー統合を生成できます。
$ rails generate rodauth:mailer
これにより、RodauthMailerクラスとメールテンプレートが作成され、認証クラスにコピーするのに必要な設定が出力されます。
# app/misc/rodauth_main.rb
class RodauthMain < Rodauth::Rails::Auth
configure do
create_verify_account_email do
RodauthMailer.verify_account(self.class.configuration_name, account_id, verify_account_key_value)
end
create_reset_password_email do
RodauthMailer.reset_password(self.class.configuration_name, account_id, reset_password_key_value)
end
create_verify_login_change_email do |_login|
RodauthMailer.verify_login_change(self.class.configuration_name, account_id, verify_login_change_key_value)
end
end
end
メールリンクを有効にするには、環境ファイルごとにconfig.action_mailer.default_url_optionsを設定する必要があります。
# config/environments/development.rb
config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
このジェネレータでは、以下のようなさまざまなオプションが利用できます。
# 特定機能向けのメーラー統合を生成
$ rails generate rodauth:mailer email_auth lockout webauthn_modify_email
# Rodauth全機能のメーラー統合を生成
$ rails generate rodauth:mailer --all
# Rodauthの別設定を指定して特定の機能を選択する
$ rails generate rodauth:mailer --name admin
生成されたRodauth設定では、Active Jobを使用してバックグラウンドジョブでメールを配信する#deliver_laterが呼び出されていることにご注意ください。メールを同期的に配信したい場合は、設定を変更して#deliver_nowを呼び出すことも可能です。
Active Jobアダプタを使わないバックグラウンド処理ライブラリを使う場合や、サードパーティのトランザクショナルなメール送信サービスを使う場合は、このWikiページでセットアップ方法を参照してください。
🔗 マイグレーション
インストールジェネレータは、デフォルトで有効になっているRodauth機能が利用するテーブルのマイグレーションを作成します。Rodauthの追加機能については、必要なテーブルを以下のようにマイグレーションジェネレータで作成できます。
$ rails generate rodauth:migration otp sms_codes recovery_codes
# db/migration/*_create_rodauth_otp_sms_codes_recovery_codes.rb
class CreateRodauthOtpSmsCodesRecoveryCodes < ActiveRecord::Migration
def change
create_table :account_otp_keys do |t| ... end
create_table :account_sms_codes do |t| ... end
create_table :account_recovery_codes do |t| ... end
end
end
アカウントのレコードをaccounts以外のテーブルに保存している場合は、新しいマイグレーションを生成するときに、以下のように正しいテーブルプレフィックスを指定する必要があります。
$ rails generate rodauth:migration base active_sessions --prefix user
# Add the following to your Rodauth configuration:
#
# accounts_table :users
# active_sessions_table :user_active_session_keys
# active_sessions_account_id_column :user_id
# db/migration/*_create_rodauth_user_base_active_sessions.rb
class CreateRodauthUserBaseActiveSessions < ActiveRecord::Migration
def change
create_table :users do |t| ... end
create_table :user_active_session_keys do |t| ... end
end
end
デフォルトのマイグレーション名は以下のオプションでカスタマイズできます。
$ rails generate rodauth:migration email_auth --name create_account_email_auth_keys
# db/migration/*_create_account_email_auth_keys.rb
class CreateAccountEmailAuthKeys < ActiveRecord::Migration
def change
create_table :account_email_auth_keys do |t| ... end
end
end
🔗 モデル
rodauth-model gemは、アカウントモデルにincludeできるRodauth::Modelミックスインを提供します。このミックスインは、password属性と、有効な認証機能で使われるテーブルの関連付けを定義します。
class Account < ActiveRecord::Base # Sequel::Model
include Rodauth::Rails.model # または`Rodauth::Rails.model(:admin)`
end
# パスワードハッシュを設定
account = Account.create!(email: "user@example.com", password: "secret123")
account.password_hash #=> "$2a$12$k/Ub1I2iomi84RacqY89Hu4.M0vK7klRnRtzorDyvOkVI.hKhkNw."
# パスワードハッシュをクリアする
account.password = nil
account.password_hash #=> nil
# 関連付け
account.remember_key #=> #<Account::RememberKey> (record from `account_remember_keys` table)
account.active_session_keys #=> [#<Account::ActiveSessionKey>,...] (records from `account_active_session_keys` table)
🔗 複数の設定を使い分ける
複数のアカウント種別ごとに異なる認証ロジックを使い分ける必要がある場合は、そのための新しい設定を作成できます。これは、Rodauth::Rails::Authのサブクラスを新たに作成し、名前をつけて登録することで行なえます。
# app/misc/rodauth_app.rb
class RodauthApp < Rodauth::Rails::App
configure RodauthMain # プライマリ設定
configure RodauthAdmin, :admin # セカンダリ設定
route do |r|
r.rodauth # プライマリRodauthリクエストへのルーティング
r.rodauth(:admin) # セカンダリRodauthリクエストへのルーティング
if request.path.start_with?("/admin")
rodauth(:admin).require_account
end
end
end
# app/misc/rodauth_admin.rb
class RodauthAdmin < Rodauth::Rails::Auth
configure do
# ... 機能を有効にする ...
prefix "/admin"
session_key_prefix "admin_"
remember_cookie_key "_admin_remember" # パスワード保存機能を使う場合
# `app/views/admin/rodauth`ディレクトリのビューを探索する
rails_controller { Admin::RodauthController }
end
end
# app/controllers/admin/rodauth_controller.rb
class Admin::RodauthController < ApplicationController
end
これで、アプリケーション内でセカンダリのRodauthインスタンスを参照できるようになります。
rodauth(:admin).authenticated? # "admin_account_id"セッション値をチェックする
rodauth(:admin).login_path #=> "/admin/login"
原注
どのアカウントがどのコンフィグに属しているかという情報もデータベースに保存したいことがよくあります。詳しくはこのガイドを参照してください。なお、コンフィグを継承で共有することも可能です。
🔗 リクエスト外部での利用
internal_requestやpath_class_methods機能がサポートされており、config.action_mailer.default_url_optionsから取得したデフォルト値が使われます。
# 内部リクエスト
RodauthApp.rodauth.create_account(login: "user@example.com", password: "secret123")
RodauthApp.rodauth(:admin).verify_account(account_login: "admin@example.com")
# パスやURLのメソッド
RodauthApp.rodauth.close_account_path #=> "/close-account"
RodauthApp.rodauth(:admin).otp_setup_url #=> "http://localhost:3000/admin/otp-setup"
````
#### <a id="calling_imethods" href="#calling_imethods">🔗</a> インスタンスメソッドを呼び出す
内部リクエストとして公開されていないRodauthメソッドにアクセスする必要がある場合は、`Rodauth::Rails.rodauth`を利用すれば、`internal_request`機能を有効にするのに必要なRodauthインスタンスを取得できます。
```rb
account = Account.find_by!(email: "user@example.com")
rodauth = Rodauth::Rails.rodauth(account: account) #=> #<RodauthMain::InternalRequest ...>
rodauth.compute_hmac("token") #=> "TpEJTKfKwqYvIDKWsuZhkhKlhaBXtR1aodskBAflD8U"
rodauth.open_account? #=> true
rodauth.two_factor_authentication_setup? #=> true
rodauth.password_meets_requirements?("foo") #=> false
rodauth.locked_out? #=> false
Rodauth::Rails.rodauthメソッドは、:accountオプションの他に、internal_request機能でサポートされている任意のオプションを受け取れます。
# プライマリ設定
Rodauth::Rails.rodauth(env: { "HTTP_USER_AGENT" => "programmatic" })
Rodauth::Rails.rodauth(session: { two_factor_auth_setup: true })
# セカンダリ設定
Rodauth::Rails.rodauth(:admin, params: { "param" => "value" })
以下のように#rails_url_optionsを変更することで、デフォルトURLオプションをアドホックに変更できます。
rodauth.base_url #=> "https://example.com"
rodauth.rails_url_options[:host] = "subdomain.example.com"
rodauth.base_url #=> "https://subdomain.example.com"
🔗 ライブラリとして利用する
Rodauthは、リクエストをルーティングする用途ではなく、ライブラリとして([内部リクエスト][内部リクエスト]経由で)利用したい場合のために、Rodauth.libメソッドを提供します。このgemは、Railsと統合された同様の機能を持つRodauth::Rails.libメソッドを提供します。
# 起動時の`require`をスキップする(Rodauthミドルウェアの挿入を避けるため)
gem "rodauth-rails", require: false
# app/misc/rodauth_main.rb
require "rodauth/rails"
require "sequel/core"
RodauthMain = Rodauth::Rails.lib do
enable :create_account, :login, :close_account
db Sequel.postgres(extensions: :activerecord_connection, keep_reference: false)
# ...
end
RodauthMain.create_account(login: "email@example.com", password: "secret123")
RodauthMain.login(login: "email@example.com", password: "secret123")
RodauthMain.close_account(account_login: "email@example.com")
🔗 テスト
ミドルウェアスタック全体を実行するシステムテストや統合テストでは、HTTPエンドポイントで通常通り認証をテストできます。
たとえば以下のコントローラがあるとします。
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
before_action -> { rodauth.require_account }
def index
# ...
end
end
以下のようにActionDispatch::IntegrationTestのテストヘルパーを作成することで、Rodauthエンドポイントへのリクエストを行う形でloginやlogoutを行えるようになります。
# test/controllers/articles_controller_test.rb
class ArticlesControllerTest < ActionDispatch::IntegrationTest
def login(email, password)
post "/login", params: { email: email, password: password }
assert_redirected_to "/"
end
def logout
post "/logout"
assert_redirected_to "/"
end
test "required authentication" do
get :index
assert_response 302
assert_redirected_to "/login"
assert_equal "Please login to continue", flash[:alert]
account = Account.create!(email: "user@example.com", password: "secret123", status: "verified")
login(account.email, "secret123")
get :index
assert_response 200
logout
get :index
assert_response 302
assert_equal "Please login to continue", flash[:alert]
end
end
Rodauthによるテストの情報やこの他のサンプルコードについては、このWikiページを参照してください。
🔗 設定方法
rodauth-railsが読み込むrails機能では、以下の設定メソッドが提供されます。
| メソッド名 | 説明 |
|---|---|
rails_render(**options) |
指定のレンダリングオプションでテンプレートをレンダリングする |
rails_csrf_tag |
CSRFトークンを含む隠しフィールドをRodauthテンプレートに追加する |
rails_csrf_param |
CSRFタグのname属性の値 |
rails_csrf_token |
CSRFタグのvalue属性の値 |
rails_check_csrf! |
現在のリクエストで認証トークンを検証する |
rails_controller_instance |
リクエストのenvコンテキストを持つコントローラのインスタンス |
rails_controller |
レンダリングやCSRF保護に用いるコントローラのクラス |
rails_account_model |
accountsテーブルに接続するモデルのクラス |
rails_url_options |
リクエストの外でURLを生成するためのオプション(デフォルトは config.action_mailer.default_url_options) |
class RodauthMain < Rodauth::Rails::Auth
configure do
rails_account_model { MyApp::Account }
rails_controller { MyApp::RodauthController }
end
end
🔗 ミドルウェアを手動で挿入する
Rodauthミドルウェアは、以下のようにRailsルーターより前の位置にも挿入できます。
# config/initializers/rodauth.rb
Rodauth::Rails.configure do |config|
config.middleware = false # 自動挿入を無効にする
end
Rails.configuration.middleware.insert_before AnotherMiddleware, Rodauth::Rails::Middleware
🔗 Tiltをスキップする
Rodauthでは、組み込みのビューやメールテンプレートをレンダリングするのにTilt gemを使っています。Tiltに依存したくない場合は、アプリにすべてのビューとメールテンプレートをインポート済みであれば無効化できます。
# config/initializers/rodauth.rb
Rodauth::Rails.configure do |config|
config.tilt = false # Tilt gemの読み込みをスキップ
end
🔗 rodauth-railsのしくみ
🔗 Rackミドルウェア
RailsのrailtieはRackミドルウェアスタックの末尾にRodauth::Rails::Middlewareを挿入します。これはRodauthアプリの単なるラッパーです。
$ rails middleware
# ...
# use Rodauth::Rails::Middleware
# run MyApp::Application.routes
原注
Rodauthルーティングの前に呼び出されるミドルウェアを使っている場合は、そのミドルウェアが必ずRodauthよりも前に挿入されるようにしてください。
たとえば、サインアップを制限するためにRack::Attackミドルウェアを使っている場合は、Gemfile内でrack-attack gemをrodauth-railsの上に配置し、そのミドルウェアが最初に挿入されるようにしてください。
🔗 Rodaアプリ
Rodauth::Rails::Appクラスは、Rodaに有用な層をRodauthに提供するサブクラスです。
🔗 ブロックを渡して設定する
configure呼び出しは:rodauthプラグインのラッパーです。規約としては、この呼び出しは認証クラスと設定名(それぞれプラグインの:auth_classオプションと:nameオプションに変換されます)を位置引数として受け取ります。また、匿名の認証クラス用のブロックを受け取り、プラグインの任意の追加オプションも受け取ります。
class RodauthApp < Rodauth::Rails::App
# 名前を持つ認証クラス
configure(RodauthMain)
configure(RodauthAdmin, :admin)
# 匿名の認証クラス
configure { ... }
configure(:admin) { ... }
# プラグインのオプション
configure(RodauthMain, json: :only, render: false)
end
🔗 ブロックを渡してルーティングする
routeに渡したブロックは、Railsルーターに到達する前にリクエストごとに呼び出されてリクエストオブジェクトをyieldします。
class RodauthApp < Rodauth::Rails::App
route do |r|
# 各リクエストの前に呼び出される
end
end
🔗 Rackのenv
アプリは、Rack envに登録された設定ごとにRodauthオブジェクトを設定し、Railsルーター、コントローラー、ビューから下流にアクセスできるようにします。
request.env["rodauth"] #=> #<RodauthMain>
request.env["rodauth.admin"] #=> #<RodauthAdmin> (if using multiple configurations)
🔗 Authクラス
Rodauth::Rails::AuthクラスはRodauth::Authのサブクラスで、Rodauthのrails機能をプリロードしてHMACのsecretをRailsのsecretキーベースに設定し、いくつかのデフォルト設定を変更します。
class RodauthMain < Rodauth::Rails::Auth
configure do
# 認証の設定
end
end
🔗 Rodauthの機能
Rodauth::Rails::Authで読み込まれるRodauthのrails機能は、RodauthをRailsに統合するうえで主要な部分を提供します。
- テンプレートのレンダリングにAction Viewを利用する
- CSRF保護にAction Dispatchを利用する
- Action Controllerコールバックと、Rodauthリクエストの前後のブロックからの
rescueを実行する - メール作成と配信にAction Mailerを利用する
- Rodauthリクエストの前後でAction Controllerのinstrumentationを利用する
- リクエストの外でRodauthを呼ぶときにAction MailerのデフォルトURLオプションを利用する
ライセンス
The gem is available as open source under the terms of the MIT License.
Code of Conduct
Everyone interacting in the rodauth-rails project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
概要
MITライセンスに基づいて翻訳・公開いたします。
見出しの深さは変えてあります。
rodauth-railsにはRails 7ベースの設定済みデモアプリもあります。
rodauth-rails作者のjanko氏による以下の記事もどうぞ。