In a tenant-portal app already running Devise 5, what does adding :confirmable and :lockable to User take, and what breaks for existing tenants?
answer
- required columns per module and strategy
- confirmed_at nil means inactive
- allow_unconfirmed_access_for defaults to 0.days
- maximum_attempts 20, unlock_strategy :both
- backfill before the model change ships
basics
~20 sAdd the confirmable and lockable columns in a migration, enable the modules, and backfill confirmed_at for existing users. Otherwise every current tenant is unconfirmed, and with the default 0.days grace Devise signs them out and refuses them.
solid answer
~40 sConfirmable needs `confirmation_token`, `confirmed_at`, `confirmation_sent_at` and, because the generated initializer sets `reconfirmable = true`, `unconfirmed_email`. Lockable with the default `lock_strategy :failed_attempts` and `unlock_strategy :both` needs `failed_attempts` (integer, default 0), `unlock_token` and `locked_at`. The trap is existing rows: their `confirmed_at` is `nil`, `allow_unconfirmed_access_for` defaults to `0.days`, so `active_for_authentication?` is false and the after_set_user hook signs every tenant out with `:unconfirmed`. Backfill `confirmed_at` in the same migration and deploy the schema before the model change. Then tune lockable: `maximum_attempts` is 20 and `unlock_in` 1 hour by default, and both can be set per model. Devise mails with `deliver_now`, so confirmation and unlock mail is sent inside the request unless you override `send_devise_notification`.
code
ruby · 25 linesclass AddConfirmableAndLockableToUsers < ActiveRecord::Migration[8.1]
def up
change_table :users, bulk: true do |t|
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email
t.integer :failed_attempts, default: 0, null: false
t.string :unlock_token
t.datetime :locked_at
end
add_index :users, :confirmation_token, unique: true
add_index :users, :unlock_token, unique: true
# Existing tenants count as confirmed, or they are all signed out
User.update_all(confirmed_at: Time.current)
end
def down
remove_index :users, :unlock_token
remove_index :users, :confirmation_token
remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at,
:unconfirmed_email, :failed_attempts, :unlock_token, :locked_at
end
endgo deeper
Remember that confirmable and lockable each need their own columns, and that unconfirmed users cannot sign in by default.
List the columns per module and strategy, explain the allow_unconfirmed_access_for and maximum_attempts defaults, and how unlock_strategy chooses the unlock path.
Plan the rollout: backfill confirmed_at, order the migration before the code, move mail off the request, and fix fixtures before CI fails.
Decide whether confirmation and lockout pay for themselves against support load, and who owns the lockout threshold and unlock policy.
## The scenario A **tenant portal** (each customer company's staff sign in to manage their account) has run Devise with the generator's five default modules for a year. The team now wants **email confirmation** for new sign-ups and **account lockout** after repeated wrong passwords: the `confirmable` and `lockable` modules. Turning them on is one line in the model, but each module expects columns, and `confirmable` changes who may sign in at all. ## Step 1: the columns each module requires Each Devise module declares `required_fields`, and the generator's migration template lists them as commented lines: | Module and setting | Columns | |---|---| | `confirmable` | `confirmation_token`, `confirmed_at`, `confirmation_sent_at` | | `confirmable` with `reconfirmable = true` | plus `unconfirmed_email` | | `lockable` with `lock_strategy :failed_attempts` | `failed_attempts` (integer, `default: 0, null: false`) | | `lockable` with `unlock_strategy :email` or `:both` | `unlock_token` | | `lockable` with `unlock_strategy :time` or `:both` | `locked_at` | The generated initializer sets `config.reconfirmable = true`, and the library defaults are `lock_strategy :failed_attempts` and `unlock_strategy :both`, so a default setup needs all seven columns. Add unique indexes on `confirmation_token` and `unlock_token`, since Devise looks users up by them. ## Step 2: do not lock out every existing tenant This is the part that bites in production: 1. Existing rows get `confirmed_at = nil`. 2. `confirmable` overrides `active_for_authentication?` to require `confirmed?` or a valid grace period, and `allow_unconfirmed_access_for` defaults to `0.days`, which means no grace at all. 3. Devise's activatable hook runs `after_set_user` on **every** request, including when the user is fetched from the session. On the first request after the deploy it calls `warden.logout` and throws with the `:unconfirmed` message. 4. Every signed-in tenant is bounced to the sign-in page with "You have to confirm your email address before continuing", and no confirmation email exists for them: the token is generated `before_create`, so only new records get one. The fix is a **backfill**: set `confirmed_at` for all existing users in the same migration (for example `User.update_all(confirmed_at: Time.current)`), and make sure the migration runs before the code that enables `:confirmable` serves requests. Shipping the model change first also fails differently: the module calls attributes that do not exist yet. ## Step 3: tune lockable - `maximum_attempts` defaults to **20**; `unlock_in` to **1 hour**; `last_attempt_warning` to `true` (the flash warns on the final try). - `unlock_strategy :both` emails an unlock link **and** unlocks automatically after `unlock_in`; `:email` or `:time` keep one path, `:none` leaves unlocking to you (`unlock_access!`). - Options can be global (`config.maximum_attempts = 10`) or per model (`devise ..., :lockable, maximum_attempts: 10`). - With `config.paranoid = true` the failure message stops saying "locked", so the form does not reveal that an account exists. Choosing the threshold, and whether a lockout keyed on the account can be abused, is lockout policy rather than Devise configuration. ## What you get without extra code Once the modules are enabled, `devise_for :users` draws the confirmation and unlock routes itself (`/users/confirmation`, `/users/unlock`, each with a `new` page for resending instructions), and the gem's built-in views and mailer templates serve them. The sign-in form needs no change: a wrong password now increments `failed_attempts` through `valid_for_authentication?`, and an unconfirmed or locked user receives the matching flash message from the failure app. If the app has already copied Devise's views, copy the new folders too (`rails generate devise:views -v confirmations unlocks mailer`) so they match the rest of the design. ## Step 4: mail and the tests - Devise sends confirmation, reset and unlock mail through `send_devise_notification`, which calls `deliver_now`. Override it in the model to queue the mail instead of sending during the request. - `confirmable` sends instructions from an `after_commit` on create, so new tenants get mail only once their row is committed. - Test fixtures and factories must set `confirmed_at` (or call `skip_confirmation!`), otherwise signed-in test users are rejected exactly like production users were. ## Summary checklist 1. Migration: seven columns, two unique indexes, `confirmed_at` backfilled. 2. Model: `devise ..., :confirmable, :lockable`, with per-model options if needed. 3. Initializer: review `allow_unconfirmed_access_for`, `confirm_within`, `maximum_attempts`, `unlock_strategy`, `unlock_in`, `paranoid`. 4. Mail delivery and test data updated before the deploy.
- Why does a tenant who changes their email keep receiving mail at the old address?With `reconfirmable = true`, set by the generated initializer, Devise writes the new address to `unconfirmed_email` and sends a confirmation to it; `email` changes only when that link is clicked. Until then the old address stays current, which is the point: an attacker with a session cannot silently move the account to their own mailbox.
- How would you give new tenants three days to use the portal before confirming?Set `config.allow_unconfirmed_access_for = 3.days` (or pass it to the `devise` macro). `confirmation_period_valid?` then lets an unconfirmed user stay active while `confirmation_sent_at` is within that window; `nil` would allow unconfirmed access forever. `confirm_within` is different: it expires the token, not the access.
- A tenant was locked out with unlock_strategy :both; what are the ways back in?Clicking the emailed unlock link, which calls `unlock_access_by_token`; waiting until `locked_at` is older than `unlock_in` (1 hour by default), after which the next sign-in attempt clears the lock; or support calling `user.unlock_access!`, which resets `locked_at`, `failed_attempts` and `unlock_token`.
- Existing users are treated as confirmed automatically when confirmable is added
- allow_unconfirmed_access_for defaults to a few days of grace
- lockable locks an account after five failed attempts by default
- unlock_strategy :both still needs only the locked_at column
- Devise queues its emails with deliver_later out of the box