(2026年10月29日 追記:記事どおりに再現できるよう、必要なコードと手順を追加しました)
見積・請求のデータは、取引先名や金額が並ぶ社内の大事な情報です。第1回で作った取引先・品目のマスタは、今のところURLを知っていれば誰でも開けて、消せてしまいます。この第2回では、Ruby on Rails 8標準の認証ジェネレータでログインを付け、さらに「見るだけの人」「登録できる人」「削除もできる人」を分ける権限を入れます。
前回の第1回:取引先と品目のマスタを作るの終わりで「ログインがないので、公開サーバーには置かないでください」と書きました。この回でその宿題を片づけます。
「社内システムだから、パスワードさえあれば誰でも同じように使えれば十分では? 権限まで分ける必要はありますか?」
先に結論です。ログインだけでは足りず、「誰が何をできるか」の線引きまで最初に決めておくのが安全です。Rails 8には認証の土台(ログイン・ログアウト・セッション管理)を作る bin/rails generate authentication が標準で入っており、外部ライブラリなしで作れます。一方で、権限の分け方は会社ごとに違うため、自分で作る部分になります。
この記事では、認証ジェネレータの出力を読み解き、3段階の権限(閲覧のみ/担当者/管理者)を実装して、自動テストで固めるところまでを解説します。
認証ジェネレータが作るもの、作らないもの
Rails 8の認証ジェネレータは、ログインに必要な最小限の部品を一式つくります。公式のRails 8紹介記事によると、Session と User のモデル、SessionsController、Authentication コンセルン(=複数の画面で共有する処理のまとまり)などが生成され、一方で新規ユーザーの登録画面(サインアップ)は「アプリごとに作りが違うため」あえて含まれません。
📰 出典:Ruby on Rails「Rails 8.0: No PaaS Required」
生成されるものを、役割ごとに整理します。
| 生成物 | 役割 |
|---|---|
User モデル | メールアドレスとパスワード(暗号化して保存)を持つ |
Session モデル | 「どの端末でログイン中か」を1行ずつ記録する(IPアドレス・ブラウザ情報つき) |
Authentication コンセルン | 全画面で「ログイン済みか」を確認し、未ログインならログイン画面へ送る |
SessionsController | ログイン・ログアウトの処理。連続した失敗を制限する仕組み(レート制限)つき |
| マイグレーション | users と sessions テーブルの作成 |
なお、生成時に「パスワード再設定」の機能(メール送信つき)も一緒に作られます。この連載ではメール送信を第6回で扱うため、今回は再設定の部品を取り除いて進めます(後から足す前提です)。
実装手順
1. ジェネレータを実行する
bin/rails generate authentication
bin/rails db:migrate
パスワードを安全に保存する has_secure_password が使う bcrypt というライブラリが、Gemfile で有効になります。これは、パスワードそのものではなく「元に戻せない形(ハッシュ)」に変換して保存する仕組みです。万一データベースが漏れても、パスワードがそのまま読まれることはありません。
ジェネレータは Gemfile の bcrypt の行を有効にして bundle install まで行い、test/test_helpers/session_test_helper.rb(テストでログインする sign_in_as)も作ります。パスワード再設定の部品は今回は使わないので、次のコマンドで消します。
rm app/controllers/passwords_controller.rb app/mailers/passwords_mailer.rb
rm -r app/views/passwords app/views/passwords_mailer test/mailers/previews
rm test/controllers/passwords_controller_test.rb
あわせて、ルートからも外します。config/routes.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,6 +1,5 @@
Rails.application.routes.draw do
resource :session
- resources :passwords, param: :token
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
2. 全画面を「ログイン必須」にする
app/controllers/application_controller.rb に Authentication が差し込まれます。これで、すべての画面が既定でログイン必須になります。次の手順で作る権限チェックもここで読み込むので、app/controllers/application_controller.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,5 +1,7 @@
class ApplicationController < ActionController::Base
include Authentication
+ include Authorization
+
# Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
allow_browser versions: :modern
「基本は全部ログイン必須で、開けてよい画面だけ例外にする」という向きが重要です。逆(基本は誰でも開けて、守る画面だけ指定する)だと、新しい画面を作るたびに守り忘れが起きます。ログイン画面だけが例外で、生成された SessionsController に allow_unauthenticated_access only: %i[ new create ] の1行があります。メッセージを日本語にするため、app/controllers/sessions_controller.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,6 +1,7 @@
class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[ new create ]
- rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." }
+ rate_limit to: 10, within: 3.minutes, only: :create,
+ with: -> { redirect_to new_session_path, alert: "試行回数が多すぎます。しばらくしてからやり直してください。" }
def new
end
@@ -10,12 +11,13 @@ class SessionsController < ApplicationController
start_new_session_for user
redirect_to after_authentication_url
else
- redirect_to new_session_path, alert: "Try another email address or password."
+ # メールアドレスとパスワードのどちらが違うかは教えない
+ redirect_to new_session_path, alert: "メールアドレスまたはパスワードが違います。"
end
end
def destroy
terminate_session
- redirect_to new_session_path, status: :see_other
+ redirect_to new_session_path, status: :see_other, notice: "ログアウトしました。"
end
end
3. ユーザーに「権限」を持たせる
users テーブルに role(権限)の列を足します。マイグレーションを生成し、ファイル名を記事に合わせて読み替えてください(数字は実行した日時になります)。
bin/rails generate migration AddRoleToUsers role:string
生成された db/migrate/20261002124428_add_role_to_users.rb に次の変更を加え、bin/rails db:migrate を実行します(+ が追加、- が削除)。
--- a/db/migrate/20261002124428_add_role_to_users.rb
+++ b/db/migrate/20261002124428_add_role_to_users.rb
@@ -1,5 +1,5 @@
class AddRoleToUsers < ActiveRecord::Migration[8.1]
def change
- add_column :users, :role, :string
+ add_column :users, :role, :string, null: false, default: "viewer"
end
end
既定値を「閲覧のみ(viewer)」にしているのがポイントです。権限の設定を忘れたユーザーが、うっかり強い権限を持つことを防げます。
モデルでは、Railsの enum で3つの権限を定義し、「何ができるか」をメソッドにします。生成された app/models/user.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -2,5 +2,14 @@ class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
+ # viewer: 閲覧のみ / staff: 登録・更新ができる / admin: 削除もできる
+ enum :role, { viewer: "viewer", staff: "staff", admin: "admin" }, default: :viewer
+
normalizes :email_address, with: ->(e) { e.strip.downcase }
+
+ validates :email_address, presence: true, uniqueness: true
+ validates :password, length: { minimum: 8 }, allow_nil: true
+
+ def can_edit? = staff? || admin?
+ def can_destroy? = admin?
end
「権限の名前」ではなく「できること(can_edit?)」で判定する形にしておくと、後から「経理担当」のような権限を足しても、画面側の判定を書き換えずに済みます。
4. 権限チェックを1か所にまとめる
各画面に if を散らさず、コンセルンにまとめます。app/controllers/concerns/authorization.rb を新しく作ります。
# app/controllers/concerns/authorization.rb
# ログインしているユーザーの権限(role)で操作を制限する
module Authorization
extend ActiveSupport::Concern
class_methods do
# 例: require_permission :can_edit?, except: %i[ index show ]
def require_permission(permission, **options)
before_action(**options) { forbid unless Current.user.public_send(permission) }
end
end
private
def forbid
redirect_back_or_to root_path, alert: "この操作を行う権限がありません。", status: :see_other
end
end
そのうえで、取引先・品目の画面に次の2行を足すだけで制限できます。app/controllers/customers_controller.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/controllers/customers_controller.rb
+++ b/app/controllers/customers_controller.rb
@@ -1,4 +1,6 @@
class CustomersController < ApplicationController
+ require_permission :can_edit?, except: %i[ index show ]
+ require_permission :can_destroy?, only: :destroy
before_action :set_customer, only: %i[ show edit update destroy ]
def index
app/controllers/items_controller.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/controllers/items_controller.rb
+++ b/app/controllers/items_controller.rb
@@ -1,4 +1,6 @@
class ItemsController < ApplicationController
+ require_permission :can_edit?, except: %i[ index show ]
+ require_permission :can_destroy?, only: :destroy
before_action :set_item, only: %i[ show edit update destroy ]
def index
Current.user は、リクエストごとに「いまログインしている人」を引き出すRailsの仕組み(Current)を使っています。ジェネレータが作る Current モデル(app/models/current.rb)に delegate :user, to: :session が入っているので、そのまま使えます。
5. 画面も権限に合わせる
ボタンを隠すだけでは安全になりませんが(URLを直接開かれると防げません)、押せないボタンが並ぶと使う人が混乱します。制限の本体は手順4のサーバー側で、画面の出し分けは親切のためと考えてください。取引先・品目の一覧と詳細で、権限のない人にはボタンを出さないようにします。
app/views/customers/index.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/customers/index.html.erb
+++ b/app/views/customers/index.html.erb
@@ -5,7 +5,7 @@
<%= form_with url: customers_path, method: :get, class: "actions" do |form| %>
<%= form.search_field :q, value: params[:q], placeholder: "取引先名・カナで検索" %>
<%= form.submit "検索", name: nil %>
- <%= link_to "新規登録", new_customer_path %>
+ <% if Current.user.can_edit? %><%= link_to "新規登録", new_customer_path %><% end %>
<% end %>
<table>
app/views/customers/show.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/customers/show.html.erb
+++ b/app/views/customers/show.html.erb
@@ -9,7 +9,9 @@
</dl>
<div class="actions">
- <%= link_to "編集", edit_customer_path(@customer) %>
+ <%= link_to "編集", edit_customer_path(@customer) if Current.user.can_edit? %>
<%= link_to "一覧へ戻る", customers_path %>
+ <% if Current.user.can_destroy? %>
<%= button_to "削除", @customer, method: :delete, form: { data: { turbo_confirm: "この取引先を削除しますか?" } } %>
+ <% end %>
</div>
app/views/items/index.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/items/index.html.erb
+++ b/app/views/items/index.html.erb
@@ -5,7 +5,7 @@
<%= form_with url: items_path, method: :get, class: "actions" do |form| %>
<%= form.search_field :q, value: params[:q], placeholder: "品目コード・品目名で検索" %>
<%= form.submit "検索", name: nil %>
- <%= link_to "新規登録", new_item_path %>
+ <% if Current.user.can_edit? %><%= link_to "新規登録", new_item_path %><% end %>
<% end %>
<table>
app/views/items/show.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/items/show.html.erb
+++ b/app/views/items/show.html.erb
@@ -10,7 +10,9 @@
</dl>
<div class="actions">
- <%= link_to "編集", edit_item_path(@item) %>
+ <%= link_to "編集", edit_item_path(@item) if Current.user.can_edit? %>
<%= link_to "一覧へ戻る", items_path %>
+ <% if Current.user.can_destroy? %>
<%= button_to "削除", @item, method: :delete, form: { data: { turbo_confirm: "この品目を削除しますか?" } } %>
+ <% end %>
</div>
ヘッダーには、ログイン中の人と権限、ログアウトのボタンを出します。権限名の日本語と、パスワードの長さのエラー文も辞書に足します。
app/views/layouts/application.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -19,10 +19,16 @@
<body>
<header class="site-header">
<%= link_to "見積・請求管理", root_path, class: "brand" %>
- <nav>
- <%= link_to "取引先", customers_path %>
- <%= link_to "品目", items_path %>
- </nav>
+ <% if authenticated? %>
+ <nav>
+ <%= link_to "取引先", customers_path %>
+ <%= link_to "品目", items_path %>
+ </nav>
+ <div class="account">
+ <%= Current.user.email_address %>(<%= User.human_attribute_name("role.#{Current.user.role}") %>)
+ <%= button_to "ログアウト", session_path, method: :delete, class: "link-button" %>
+ </div>
+ <% end %>
</header>
<main>
<% if notice %><p class="notice"><%= notice %></p><% end %>
app/assets/stylesheets/application.css に次の変更を加えます(+ が追加、- が削除)。
--- a/app/assets/stylesheets/application.css
+++ b/app/assets/stylesheets/application.css
@@ -13,3 +13,8 @@ td.num, th.num { text-align: right; }
.field input[type=text], .field input[type=number], .field input[type=email], .field select, .field textarea { width: 100%; padding: .4rem; box-sizing: border-box; }
.actions { display: flex; gap: 1rem; align-items: center; }
.muted { color: #777; }
+.site-header .account { margin-left: auto; color: #fff; font-size: .9rem; display: flex; gap: .5rem; align-items: center; }
+.link-button { background: none; border: 1px solid #fff; color: #fff; border-radius: 4px; cursor: pointer; }
+.login-form { max-width: 24rem; }
+.login-form label { display: block; font-weight: bold; }
+.login-form input[type=email], .login-form input[type=password] { width: 100%; }
config/locales/ja.yml に次の変更を加えます(+ が追加、- が削除)。
--- a/config/locales/ja.yml
+++ b/config/locales/ja.yml
@@ -12,6 +12,14 @@ ja:
email: メールアドレス
phone: 電話番号
note: 備考
+ user:
+ email_address: メールアドレス
+ password: パスワード
+ role: 権限
+ user/role:
+ viewer: 閲覧のみ
+ staff: 担当者
+ admin: 管理者
item:
code: 品目コード
name: 品目名
@@ -22,6 +30,7 @@ ja:
errors:
format: "%{attribute}%{message}"
messages:
+ too_short: は%{count}文字以上にしてください
blank: を入力してください
taken: はすでに使われています
invalid: の形式が正しくありません
ログイン画面は、メールアドレスとパスワードの2項目だけのシンプルな形にします。生成された app/views/sessions/new.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/sessions/new.html.erb
+++ b/app/views/sessions/new.html.erb
@@ -1,11 +1,15 @@
-<%= tag.div(flash[:alert], style: "color:red") if flash[:alert] %>
-<%= tag.div(flash[:notice], style: "color:green") if flash[:notice] %>
+<% content_for :title, "ログイン" %>
-<%= form_with url: session_path do |form| %>
- <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", placeholder: "Enter your email address", value: params[:email_address] %><br>
- <%= form.password_field :password, required: true, autocomplete: "current-password", placeholder: "Enter your password", maxlength: 72 %><br>
- <%= form.submit "Sign in" %>
-<% end %>
-<br>
+<h1>ログイン</h1>
-<%= link_to "Forgot password?", new_password_path %>
+<%= form_with url: session_path, class: "login-form" do |form| %>
+ <p>
+ <%= form.label :email_address, "メールアドレス" %>
+ <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", value: params[:email_address] %>
+ </p>
+ <p>
+ <%= form.label :password, "パスワード" %>
+ <%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72 %>
+ </p>
+ <%= form.submit "ログイン" %>
+<% end %>
ログイン失敗の文言は「メールアドレスまたはパスワードが違います」とし、どちらが違うのかは教えません。「このメールアドレスは登録されていない」と分かると、第三者が登録済みのアドレスを探る手がかりになるためです。
動作確認:自動テストで権限の線引きを固める
権限の仕組みは、画面を目で確認するだけだと必ず抜けが出ます。そこで、「誰が何をできて、何をできないか」を自動テストにしておきます。まず、テスト用のユーザー(3つの権限)を用意します。生成された test/fixtures/users.yml に次の変更を加えます(+ が追加、- が削除)。
--- a/test/fixtures/users.yml
+++ b/test/fixtures/users.yml
@@ -1,9 +1,16 @@
-<% password_digest = BCrypt::Password.create("password") %>
+<% password_digest = BCrypt::Password.create("password", cost: 4) %>
-one:
- email_address: one@example.com
+admin:
+ email_address: admin@example.com
password_digest: <%= password_digest %>
+ role: admin
-two:
- email_address: two@example.com
+staff:
+ email_address: staff@example.com
password_digest: <%= password_digest %>
+ role: staff
+
+viewer:
+ email_address: viewer@example.com
+ password_digest: <%= password_digest %>
+ role: viewer
権限の線引きのテストです。test/controllers/authorization_test.rb を新しく作ります。
# test/controllers/authorization_test.rb
require "test_helper"
class AuthorizationTest < ActionDispatch::IntegrationTest
test "閲覧のみの権限は一覧を見られるが登録はできない" do
sign_in_as users(:viewer)
get customers_url
assert_response :success
assert_select "a", text: "新規登録", count: 0
assert_no_difference "Customer.count" do
post customers_url, params: { customer: { name: "新規商事" } }
end
assert_redirected_to root_path
end
test "担当者は登録・更新できるが削除はできない" do
sign_in_as users(:staff)
assert_difference "Item.count", 1 do
post items_url, params: { item: { code: "NEW-001", name: "新品目", unit: "式", unit_price: 1000, tax_rate: 10, active: true } }
end
assert_no_difference "Item.count" do
delete item_url(items(:design))
end
assert_equal "この操作を行う権限がありません。", flash[:alert]
end
test "管理者は削除もできる" do
sign_in_as users(:admin)
assert_difference "Item.count", -1 do
delete item_url(items(:design))
end
end
end
ログインそのものについても、「正しい組み合わせで入れる」「パスワードが違うと入れない」「未ログインで業務画面を開くとログイン画面へ移り、ログイン後に元の画面へ戻る」をテストにします。ジェネレータが作ったテストに、次の変更を加えます(+ が追加、- が削除)。
test/controllers/sessions_controller_test.rb に次の変更を加えます(+ が追加、- が削除)。
test/controllers/sessions_controller_test.rb の差分(51行)
--- a/test/controllers/sessions_controller_test.rb
+++ b/test/controllers/sessions_controller_test.rb
@@ -1,33 +1,35 @@
require "test_helper"
class SessionsControllerTest < ActionDispatch::IntegrationTest
- setup { @user = User.take }
-
- test "new" do
+ test "ログイン画面は未ログインでも開ける" do
get new_session_path
assert_response :success
end
- test "create with valid credentials" do
- post session_path, params: { email_address: @user.email_address, password: "password" }
-
+ test "正しいメールアドレスとパスワードでログインできる" do
+ post session_path, params: { email_address: "staff@example.com", password: "password" }
assert_redirected_to root_path
assert cookies[:session_id]
end
- test "create with invalid credentials" do
- post session_path, params: { email_address: @user.email_address, password: "wrong" }
-
+ test "パスワードが違うとログインできない" do
+ post session_path, params: { email_address: "staff@example.com", password: "wrong" }
assert_redirected_to new_session_path
assert_nil cookies[:session_id]
end
- test "destroy" do
- sign_in_as(User.take)
-
+ test "ログアウトできる" do
+ sign_in_as users(:staff)
delete session_path
-
assert_redirected_to new_session_path
assert_empty cookies[:session_id]
end
+
+ test "未ログインで業務画面を開くとログイン画面へ移り、ログイン後に元の画面へ戻る" do
+ get customers_url
+ assert_redirected_to new_session_url
+
+ post session_url, params: { email_address: "staff@example.com", password: "password" }
+ assert_redirected_to customers_url
+ end
end
test/models/user_test.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -1,8 +1,21 @@
require "test_helper"
class UserTest < ActiveSupport::TestCase
- test "downcases and strips email_address" do
+ test "メールアドレスは前後の空白を除き小文字にそろえる" do
user = User.new(email_address: " DOWNCASED@EXAMPLE.COM ")
- assert_equal("downcased@example.com", user.email_address)
+ assert_equal "downcased@example.com", user.email_address
+ end
+
+ test "パスワードは8文字以上" do
+ user = User.new(email_address: "a@example.com", password: "short")
+ assert_not user.valid?
+ assert_includes user.errors[:password].join, "8文字以上"
+ end
+
+ test "権限ごとにできる操作が違う" do
+ assert_not users(:viewer).can_edit?
+ assert users(:staff).can_edit?
+ assert_not users(:staff).can_destroy?
+ assert users(:admin).can_destroy?
end
end
第0回・第1回のテストは、ログインしてから画面を開くように直します。
test/controllers/home_controller_test.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/test/controllers/home_controller_test.rb
+++ b/test/controllers/home_controller_test.rb
@@ -1,10 +1,13 @@
require "test_helper"
class HomeControllerTest < ActionDispatch::IntegrationTest
+ setup { sign_in_as users(:staff) }
+
test "トップページが表示される" do
get root_url
assert_response :success
assert_select "h1", "見積・請求管理システム"
+ assert_select ".account", /staff@example.com(担当者)/
end
test "ヘルスチェックが応答する" do
test/controllers/items_controller_test.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/test/controllers/items_controller_test.rb
+++ b/test/controllers/items_controller_test.rb
@@ -1,6 +1,8 @@
require "test_helper"
class ItemsControllerTest < ActionDispatch::IntegrationTest
+ setup { sign_in_as users(:admin) }
+
test "一覧に単価が桁区切りで表示される" do
get items_url
assert_response :success
test/controllers/customers_controller_test.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/test/controllers/customers_controller_test.rb
+++ b/test/controllers/customers_controller_test.rb
@@ -1,6 +1,8 @@
require "test_helper"
class CustomersControllerTest < ActionDispatch::IntegrationTest
+ setup { sign_in_as users(:admin) }
+
test "一覧が表示され検索できる" do
get customers_url
assert_response :success
検証は次のコマンドで行い、今回の変更後は30件のテストがすべて通り、RuboCop(コードの書き方の自動チェック)も指摘なしでした。
bin/rails test && bundle exec rubocop
※ この回はブラウザでの目視確認ではなく、自動テストで動作を確認しています(開発環境での確認)。メール送信が必要なパスワード再設定は、第6回以降に扱うため未実装です。
開発用の確認アカウントは db/seeds.rb に、開発環境(Rails.env.development?)の場合だけ作る形で入れています。本番環境に共通のパスワードのアカウントを残さないためで、本番の最初の管理者は、サーバー上で一度だけコマンドを実行して作る想定です(第9回で扱います)。db/seeds.rb に次の変更を加え、bin/rails db:seed を実行すると、admin@example.com・staff@example.com・viewer@example.com(パスワードはいずれも password123)でログインできます(+ が追加、- が削除)。
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -9,3 +9,17 @@
{ code: "DEV-001", name: "開発費(人月)", unit: "人月", unit_price: 800_000, tax_rate: 10 },
{ code: "FOOD-001", name: "打合せ用弁当", unit: "個", unit_price: 1_000, tax_rate: 8 }
].each { |attrs| Item.find_or_create_by!(code: attrs[:code]) { |i| i.assign_attributes(attrs) } }
+
+# 開発用ログインユーザー(本番では使わない。パスワードは開発環境専用)
+if Rails.env.development?
+ [
+ { email_address: "admin@example.com", role: :admin },
+ { email_address: "staff@example.com", role: :staff },
+ { email_address: "viewer@example.com", role: :viewer }
+ ].each do |attrs|
+ User.find_or_create_by!(email_address: attrs[:email_address]) do |u|
+ u.password = "password123"
+ u.role = attrs[:role]
+ end
+ end
+end
つまずきやすい点・セキュリティ上の注意
- サインアップ画面は作っていない:社内システムでは、管理者がユーザーを登録するのが一般的です。誰でも自分で登録できる形にすると、外部の人が入り込めてしまいます
- パスワードの長さ:今回は8文字以上のチェックを入れました。
maxlength: 72は bcrypt が扱える長さの上限に合わせたものです - レート制限は入口の対策のひとつ:ジェネレータが入れる連続失敗の制限は有効ですが、「これで絶対に破られない」という意味ではありません。本番では、アクセスの制限やログの監視も併せて検討します
- 権限を増やすときは、先にテストを書く:「管理者だけが使える画面」を増やすたびに、閲覧のみ・担当者で拒否されるテストを足しておくと、守り忘れに気づけます
- この連載で省略していること:二段階認証、パスワード再設定、ログイン履歴の画面、アカウントのロックなどは扱いません。必要な場合は別途の費用になります
発注者向けメモ:ログインと権限を頼むときの確認点
ログイン機能は「どこまで作るか」で費用が大きく変わります。開発会社に頼むときは、次を確認してください。
- ☐ 誰がシステムを使うか(社員だけか、取引先も入るか)を一覧にして伝えたか
- ☐ 権限の種類(見るだけ/登録できる/削除できる/承認できる など)を、実際の業務に沿って決めたか
- ☐ ユーザーの追加・退職者の無効化を、誰が・どの画面でするか決めたか
- ☐ パスワードを忘れたときの再設定の流れ(メール送信を含む)が見積に入っているか
- ☐ 二段階認証やシングルサインオン(=会社の共通IDでログインする仕組み)が必要か、必要なら見積に含まれているか
- ☐ 「いつ・誰が・何を変更したか」の記録(操作ログ)が必要か
開発会社への質問例
- 「権限は何段階を想定していますか。見るだけの人と、削除できる人を分けられますか」
- 「ログイン機能は自社で作りますか、既存の仕組み(認証サービスなど)を使いますか。それぞれの運用上の違いは何ですか」
- 「退職者のアカウントを止める手順は、画面からできますか。それとも開発会社への依頼が必要ですか」
- 「ログインに失敗し続けた場合や、パスワードが漏れた場合の対策は、どこまで含まれていますか」
工数が増えやすいのは、権限の種類が多い場合と、取引先の画面ごとに見せる範囲が違う場合(「A社の担当者はA社のデータだけ見える」など)、そして二段階認証やシングルサインオンです。最初のリリースでは3段階程度の権限で始め、使いながら増やす進め方も現実的です。
「権限の分け方は、あとから変えると画面もテストも直すことになります。最初に『誰が何をするか』を一緒に書き出しておくのが、いちばん安くつきます」
まとめと次回予告
第2回では、Rails 8標準の認証ジェネレータでログインを付け、権限(閲覧のみ/担当者/管理者)をサーバー側で制限し、自動テストで線引きを固めました。外部のライブラリやサービスを使わずに、業務システムに必要な入口の守りの土台ができました。
次回の第3回は「見積書と明細を作る」です。見積書(親)と明細行(子)の関係をモデルで表し、Hotwire(=画面の一部だけを書き換える仕組み)で、明細行をその場で追加できる画面を作ります。
この連載の記事一覧
この記事は連載「Railsで作る見積・請求管理システム」の1回です。連載のほかの回は次のとおりです(連載の一覧ページ)。
- 【Railsで作る見積・請求管理システム 第0回】Rails 8の雛形を動かして、Excel見積からの脱却を始める
- 【Railsで作る見積・請求管理システム 第1回】取引先と品目のマスタを作る(scaffoldと入力チェック)
- 【Railsで作る見積・請求管理システム 第2回】ログインを付ける(Rails 8標準の認証と権限の分け方)(この記事)
- 【Railsで作る見積・請求管理システム 第3回】見積書と明細を作る(Hotwireで明細行をその場で追加)
- 【Railsで作る見積・請求管理システム 第4回】金額・消費税・端数処理を正しく計算する(税率ごとに1回だけ丸める)
- 【Railsで作る見積・請求管理システム 第5回】見積書をPDFで出力する(Prawnで日本語フォントを扱う)
- 【Railsで作る見積・請求管理システム 第6回】見積書をメールで送る(Solid Queueで送信を非同期にする)
- 【Railsで作る見積・請求管理システム 第7回】受注から請求書へ変換する(状態遷移と請求番号、インボイスの記載事項)
- 【Railsで作る見積・請求管理システム 第8回】入金管理と督促の一覧を作る(一部入金・期限超過の抽出)
- 【Railsで作る見積・請求管理システム 第9回】Kamalでサーバーに配備する(Dockerイメージ・SSL・秘密情報・運用の注意)










コメント
コメント一覧 (5件)
[…] 前回の第2回:ログインを付けるで、ログインと3段階の権限(閲覧のみ/担当者/管理者)を入れました。今回の見積書の画面も、その権限の仕組みにそのまま乗せます。 […]
[…] […]
[…] […]
[…] […]
[…] […]