rails_authentication 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +100 -10
  3. data/lib/generators/authentication/authentication_generator.rb +135 -8
  4. data/lib/generators/authentication/features/confirmable.rb +5 -5
  5. data/lib/generators/authentication/features/invitable.rb +5 -5
  6. data/lib/generators/authentication/features/lockable.rb +5 -5
  7. data/lib/generators/authentication/features/magic_link.rb +5 -5
  8. data/lib/generators/authentication/features/ott.rb +5 -5
  9. data/lib/generators/authentication/features/recoverable.rb +8 -6
  10. data/lib/generators/authentication/features/rememberable.rb +8 -3
  11. data/lib/generators/authentication/templates/app/controllers/concerns/authentication.rb.tt +67 -15
  12. data/lib/generators/authentication/templates/app/controllers/confirmations_controller.rb.tt +11 -7
  13. data/lib/generators/authentication/templates/app/controllers/invitations_controller.rb.tt +14 -5
  14. data/lib/generators/authentication/templates/app/controllers/magic_links_controller.rb.tt +10 -8
  15. data/lib/generators/authentication/templates/app/controllers/otts_controller.rb.tt +18 -15
  16. data/lib/generators/authentication/templates/app/controllers/passkey_sessions_controller.rb.tt +9 -7
  17. data/lib/generators/authentication/templates/app/controllers/passwords_controller.rb.tt +22 -9
  18. data/lib/generators/authentication/templates/app/controllers/registrations_controller.rb.tt +8 -6
  19. data/lib/generators/authentication/templates/app/controllers/sessions_controller.rb.tt +11 -9
  20. data/lib/generators/authentication/templates/app/controllers/unlocks_controller.rb.tt +8 -6
  21. data/lib/generators/authentication/templates/app/controllers/webauthn_credentials_controller.rb.tt +8 -4
  22. data/lib/generators/authentication/templates/app/mailers/confirmations_mailer.rb.tt +4 -2
  23. data/lib/generators/authentication/templates/app/mailers/invitations_mailer.rb.tt +3 -1
  24. data/lib/generators/authentication/templates/app/mailers/magic_links_mailer.rb.tt +3 -1
  25. data/lib/generators/authentication/templates/app/mailers/otts_mailer.rb.tt +3 -1
  26. data/lib/generators/authentication/templates/app/mailers/passwords_mailer.rb.tt +3 -1
  27. data/lib/generators/authentication/templates/app/mailers/unlocks_mailer.rb.tt +3 -1
  28. data/lib/generators/authentication/templates/app/models/concerns/confirmable_concern.rb.tt +16 -11
  29. data/lib/generators/authentication/templates/app/models/concerns/invitable_concern.rb.tt +13 -2
  30. data/lib/generators/authentication/templates/app/models/concerns/lockable_concern.rb.tt +8 -0
  31. data/lib/generators/authentication/templates/app/models/concerns/magic_link_concern.rb.tt +2 -0
  32. data/lib/generators/authentication/templates/app/models/concerns/ott_concern.rb.tt +2 -0
  33. data/lib/generators/authentication/templates/app/models/concerns/passkey_concern.rb.tt +2 -0
  34. data/lib/generators/authentication/templates/app/models/concerns/recoverable_concern.rb.tt +8 -0
  35. data/lib/generators/authentication/templates/app/models/concerns/timeoutable_concern.rb.tt +2 -0
  36. data/lib/generators/authentication/templates/app/models/concerns/trackable_concern.rb.tt +2 -0
  37. data/lib/generators/authentication/templates/app/models/concerns/validatable_concern.rb.tt +6 -4
  38. data/lib/generators/authentication/templates/app/models/session.rb.tt +45 -0
  39. data/lib/generators/authentication/templates/app/models/user_auth.rb.tt +5 -3
  40. data/lib/generators/authentication/templates/app/models/webauthn_credential.rb.tt +2 -0
  41. data/lib/generators/authentication/templates/app/views/confirmations/new.html.erb.tt +3 -3
  42. data/lib/generators/authentication/templates/app/views/confirmations_mailer/confirmation_instructions.html.erb.tt +3 -3
  43. data/lib/generators/authentication/templates/app/views/confirmations_mailer/confirmation_instructions.text.erb.tt +2 -2
  44. data/lib/generators/authentication/templates/app/views/invitations/edit.html.erb.tt +4 -4
  45. data/lib/generators/authentication/templates/app/views/invitations/new.html.erb.tt +3 -3
  46. data/lib/generators/authentication/templates/app/views/invitations_mailer/invitation_instructions.html.erb.tt +3 -3
  47. data/lib/generators/authentication/templates/app/views/invitations_mailer/invitation_instructions.text.erb.tt +2 -2
  48. data/lib/generators/authentication/templates/app/views/magic_links/new.html.erb.tt +4 -4
  49. data/lib/generators/authentication/templates/app/views/magic_links_mailer/magic_link.html.erb.tt +3 -3
  50. data/lib/generators/authentication/templates/app/views/magic_links_mailer/magic_link.text.erb.tt +2 -3
  51. data/lib/generators/authentication/templates/app/views/otts/edit.html.erb.tt +7 -7
  52. data/lib/generators/authentication/templates/app/views/otts_mailer/ott.html.erb.tt +3 -3
  53. data/lib/generators/authentication/templates/app/views/otts_mailer/ott.text.erb.tt +3 -3
  54. data/lib/generators/authentication/templates/app/views/passwords/edit.html.erb.tt +9 -0
  55. data/lib/generators/authentication/templates/app/views/passwords/new.html.erb.tt +8 -0
  56. data/lib/generators/authentication/templates/app/views/passwords_mailer/reset.html.erb.tt +3 -3
  57. data/lib/generators/authentication/templates/app/views/passwords_mailer/reset.text.erb.tt +2 -2
  58. data/lib/generators/authentication/templates/app/views/registrations/edit.html.erb.tt +7 -7
  59. data/lib/generators/authentication/templates/app/views/registrations/new.html.erb.tt +6 -6
  60. data/lib/generators/authentication/templates/app/views/sessions/new.html.erb.tt +20 -16
  61. data/lib/generators/authentication/templates/app/views/unlocks/new.html.erb.tt +3 -3
  62. data/lib/generators/authentication/templates/app/views/unlocks_mailer/unlock_instructions.html.erb.tt +3 -3
  63. data/lib/generators/authentication/templates/app/views/unlocks_mailer/unlock_instructions.text.erb.tt +3 -3
  64. data/lib/generators/authentication/templates/app/views/webauthn_credentials/index.html.erb.tt +5 -5
  65. data/lib/generators/authentication/templates/app/views/webauthn_credentials/new.html.erb.tt +12 -6
  66. data/lib/generators/authentication/templates/config/initializers/webauthn.rb.tt +2 -0
  67. data/lib/generators/authentication/templates/config/locales/authentication.en.yml.tt +421 -0
  68. data/lib/generators/authentication/templates/db/migrate/add_confirmable_to_users.rb.tt +1 -1
  69. data/lib/generators/authentication/templates/db/migrate/add_rememberable_to_sessions.rb.tt +5 -0
  70. data/lib/generators/authentication/templates/db/migrate/remove_remember_created_at_from_users.rb.tt +11 -0
  71. data/lib/rails_authentication/version.rb +1 -1
  72. metadata +8 -3
  73. data/lib/generators/authentication/templates/app/models/concerns/rememberable_concern.rb.tt +0 -15
  74. data/lib/generators/authentication/templates/db/migrate/add_rememberable_to_users.rb.tt +0 -5
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fcff113ea0549fb291f38ebe6d9ef6d7306bb2c4a444cb01d7f2bd99a21626ef
4
- data.tar.gz: 33fb15023005e91589fb07fe846748e7c7af9876fae8b517bef98dee41994ebf
3
+ metadata.gz: e22bc37be667fc7d313ce7dbd03fa15af737e2db2b970d278d22dfe08de0d104
4
+ data.tar.gz: 002c05612493987e996f05f7619eefb1ad35af7e9d1e3200bae1a2ab6ab3762c
5
5
  SHA512:
6
- metadata.gz: 0c0849f4c52e57761a6d43a555b2c70712be764c96dc205ec10805ba983637777e53d1326e1b41b106c4ad7baeae258680e073aec19e47a42f08d9fce2b731f9
7
- data.tar.gz: 8f1021d0c9e8c7a7ef71f791a83b24948af32b628154671b1dce31ad8cfe2299d5234a278412a45cff9b11fdc81201281ebbdd89ea391a49d7a41664bba14e03
6
+ metadata.gz: 3424cdf674403e45779bd49fce73bd28936e479d61a69ef6b104f6532dbcaf7168272ceeef7e2c2831d6b8995b94380d08a3f9389fa17cc1dd74be4ae559c627
7
+ data.tar.gz: 265cebd163520740f80e04006c67641c24f879d35b574678a0a82d0b5ee6bcabc479396cbe173e5525cd58678a159061d8a38145f7db8f3b81fcbf7ce2a48e55
data/README.md CHANGED
@@ -11,7 +11,7 @@ gem extends that same command to also install:
11
11
  | **Confirmable** | Emails confirmation instructions; blocks sign-in until the email address is confirmed |
12
12
  | **Recoverable** | Password reset with DB-backed, revocable, expiring tokens (replaces the base stateless tokens) |
13
13
  | **Registerable** | Sign-up, plus account editing and deletion |
14
- | **Rememberable** | "Remember me" checkbox — persistent cookie only when checked |
14
+ | **Rememberable** | Per-browser "Remember me" checkbox — persistent cookie only when checked, stamped on that session (`sessions.remembered_at`) so other devices are unaffected |
15
15
  | **Trackable** | Records every sign-in attempt (success and failure) in a `user_auths` table: IP, user agent, referrer, failure reason |
16
16
  | **Timeoutable** | Expires sessions after 30 minutes of inactivity |
17
17
  | **Validatable** | Email format/uniqueness, password length, and password complexity validations |
@@ -58,6 +58,29 @@ Available flags: `--skip-confirmable`, `--skip-recoverable`, `--skip-registerabl
58
58
  `--skip-lockable`, `--skip-invitable`, and `--reconfirmable` (Confirmable: postpone email address
59
59
  changes until the new address is confirmed, via an `unconfirmed_email` column).
60
60
 
61
+ To call the email column something other than Rails' `email_address`, pass `--email-attribute`:
62
+
63
+ ```sh
64
+ bin/rails generate authentication --email-attribute=email
65
+ ```
66
+
67
+ The name goes into the `users` migration, fixtures, and tests from Rails' own generator, and into
68
+ one method at the top of `User`:
69
+
70
+ ```ruby
71
+ class User < ApplicationRecord
72
+ def self.authentication_email_column_name = :email
73
+ ```
74
+
75
+ Every controller, view, mailer, and concern this gem generates reads the column name from there
76
+ instead of naming it: controllers and views through `authentication_email_column_name` on the
77
+ `Authentication` concern, models and mailers through `User.authentication_email_column_name`. To
78
+ rename the column later, change that line and write the migration; Rails' own generated tests and
79
+ fixtures, and its password-reset files if you `--skip-recoverable`, name the column directly and
80
+ need updating by hand. Reconfirmable's column is named once, at generation time, as
81
+ `unconfirmed_<name>` with a trailing `_address` dropped (`email` and `email_address` both give
82
+ `unconfirmed_email`; `login_email` gives `unconfirmed_login_email`).
83
+
61
84
  MagicLink, Ott, and Passkey are **opt-in** features — they change the sign-in UX, so you have to
62
85
  ask for them:
63
86
 
@@ -92,12 +115,68 @@ register any number of passkeys, each stored as its own row in `webauthn_credent
92
115
  All three flows honor the other enabled features: locked, unconfirmed, or invitation-pending
93
116
  accounts still can't sign in, and Trackable records the attempt.
94
117
 
118
+ Signed-out pages (sign-in, sign-up, password reset, confirmation and unlock requests, invitation
119
+ acceptance, magic link and one-time code sign-in) redirect an already-signed-in user to the root
120
+ path with "You are already signed in." The emailed confirmation link stays reachable so a
121
+ signed-in user can confirm an email change.
122
+
123
+ Every controller requires a signed-in user unless it says otherwise. Three class methods, all
124
+ taking `before_action`'s `only:`/`except:` options, declare access:
125
+
126
+ | Method | Who can access |
127
+ |---|---|
128
+ | `allow_unauthenticated_access` | Everyone, signed in or not |
129
+ | `require_unauthenticated_access` | Signed-out visitors only; signed-in users are redirected to the root path |
130
+ | `require_authenticated_access` | Signed-in users only (the default; use it to be explicit, or to re-protect actions a parent controller opened) |
131
+
132
+ After signing in by any method, a user returns to the page they were sent away from (page visits
133
+ only, not form submissions or JSON requests). With no such page they land on
134
+ `default_after_authentication_url`, which is `root_url` unless you override it in
135
+ `ApplicationController`; already-signed-in users redirected away from signed-out pages land there
136
+ too:
137
+
138
+ ```ruby
139
+ class ApplicationController < ActionController::Base
140
+ include Authentication
141
+
142
+ private
143
+
144
+ def default_after_authentication_url
145
+ dashboard_url
146
+ end
147
+ end
148
+ ```
149
+
95
150
  Each feature adds a single `include <Feature>Concern` line to `app/models/user.rb`; all of its
96
- model behavior lives in `app/models/concerns/<feature>_concern.rb`. Tunables are plain constants in
97
- the generated concerns — e.g. `TimeoutableConcern::TIMEOUT_IN`, `LockableConcern::MAXIMUM_ATTEMPTS`,
151
+ model behavior lives in `app/models/concerns/<feature>_concern.rb`. Rememberable is the exception:
152
+ "remember me" belongs to one browser, not the user, so it's a `remembered_at` column on `sessions`
153
+ and `Session#remembered?`, with no User concern. Checking or unchecking it, or signing out, on one
154
+ device never changes another device's session. Magic link and passkey sign-ins aren't remembered.
155
+ Apps generated before this change get a `remove_remember_created_at_from_users` migration that
156
+ drops the old `users.remember_created_at` column (a no-op where it doesn't exist); previously
157
+ remembered users simply need to check "Remember me" again.
158
+ Each feature's concern adds scopes that match its checks: `User.confirmed` / `unconfirmed`,
159
+ `User.locked` / `not_locked` (a lock expires after `LockableConcern::UNLOCK_IN`, as at sign-in), and
160
+ `User.pending` / `not_pending` / `accepted` for invitations (users who signed up without one are
161
+ never `pending`). `User.available` combines the enabled ones into "can sign in" (confirmed, not locked,
162
+ no outstanding invitation) and `User.unavailable` is everyone else. The instance versions are
163
+ `user.available?` (also `active_for_authentication?`, Devise's name) and `user.unavailable?`.
164
+
165
+ Session expiry lives in the generated `app/models/session.rb`: `Session#expired?` (checked on
166
+ every request) and a `Session.expired` scope you can use to purge stale rows, e.g. from a
167
+ recurring job (`Session.expired.delete_all`). Remembered sessions are exempt from Timeoutable's
168
+ inactivity timeout but still expire after `Session::REMEMBERED_TIMEOUT_IN` (90 days) of inactivity. Tunables are plain constants in
169
+ the generated concerns — e.g. `TimeoutableConcern::TIMEOUT_IN`, `Session::REMEMBERED_TIMEOUT_IN`, `LockableConcern::MAXIMUM_ATTEMPTS`,
98
170
  `LockableConcern::UNLOCK_IN`, `ConfirmableConcern::CONFIRMATION_TOKEN_EXPIRES_IN`,
99
171
  `ValidatableConcern::PASSWORD_LENGTH`, `ValidatableConcern::PASSWORD_MINIMUM_COMPLEXITY`,
100
172
  `OttConcern::OTT_CODE_LENGTH` — edit them there. Concerns keep the model clean.
173
+ `PASSWORD_LENGTH` also sets the `maxlength` of the new-password fields; its upper bound can't
174
+ exceed 72, bcrypt's limit (`ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED`).
175
+
176
+ All user-facing text in the generated code (views, flash messages, passkey error messages, email
177
+ subjects, and validation messages) lives in `config/locales/authentication.en.yml`, so you can
178
+ reword it or add other locales without touching the code. The file only contains translations for
179
+ the features you generated.
101
180
 
102
181
  ### Inviting users
103
182
 
@@ -111,7 +190,8 @@ User.invite!({ email_address: "new@example.com" }, invited_by: Current.user)
111
190
  User.invite!({ email_address: "new@example.com", name: "Ada Lovelace" }, invited_by: Current.user)
112
191
  ```
113
192
 
114
- `invite!` accepts symbol or string keys, or permitted `ActionController::Parameters`. It
193
+ The examples use the default `email_address` column; with `--email-attribute`, use your column's
194
+ name. `invite!` accepts symbol or string keys, or permitted `ActionController::Parameters`. It
115
195
  returns the user either way, so check `persisted?` and `errors` to see whether it worked.
116
196
 
117
197
  - **New email address**: the user is built from the attributes and gets a random temporary
@@ -132,14 +212,14 @@ permitted. Never pass raw `params`.
132
212
  a hash: `User.invite!({ email_address: email_address }, invited_by: ...)`.
133
213
 
134
214
  **Requiring more than an email address.** The generated `InvitationsController` passes
135
- `invitation_params` (`params.permit(:email_address)`) to `invite!`. To collect more fields, add
215
+ `invitation_params` (`params.permit(authentication_email_column_name)`) to `invite!`. To collect more fields, add
136
216
  them in three places: the `permit` list, the inputs in `app/views/invitations/new.html.erb`, and
137
217
  the validations on your model:
138
218
 
139
219
  ```ruby
140
220
  # app/controllers/invitations_controller.rb
141
221
  def invitation_params
142
- params.permit(:email_address, :name)
222
+ params.permit(authentication_email_column_name, :name)
143
223
  end
144
224
  ```
145
225
 
@@ -164,8 +244,9 @@ resources :passwords, param: :token # from the base generator
164
244
  Confirmable to an app with existing users:
165
245
  `User.update_all(confirmed_at: Time.current)`.
166
246
  - **Recoverable** replaces the base generator's `PasswordsController`/`PasswordsMailer` (which use
167
- stateless signed tokens) with DB-token versions. If you `--skip-recoverable`, the base flow is
168
- left untouched.
247
+ stateless signed tokens) with DB-token versions, and its password pages with translated ones. If
248
+ you `--skip-recoverable`, the base flow is left untouched, including Rails' English-only password
249
+ pages and messages.
169
250
  - The generator overwrites the base generator's `SessionsController`, `Authentication` concern, and
170
251
  sessions view with versions tailored to the features you selected. Run the generator once, up
171
252
  front — re-running it after you've customized those files will prompt to overwrite them.
@@ -177,11 +258,16 @@ bundle install
177
258
  bundle exec rake spec:generators # generator specs (fast, no app boot)
178
259
  bundle exec rake dummy:prepare # build spec/dummy by running the real generator
179
260
  bundle exec rake spec:requests # request specs against spec/dummy
180
- bundle exec rspec spec/generators/lockable_spec.rb:12 # a single example
261
+ bundle exec rake spec:i18n # i18n-tasks checks on spec/dummy's generated locale file
262
+ bundle exec rspec spec/generators/rails_authentication/generators/features/lockable_spec.rb:12 # a single example
263
+ bundle exec rubocop # lint
181
264
  ```
182
265
 
183
266
  `spec/dummy` is generated (and gitignored), never hand-maintained, so the request specs always
184
- exercise exactly what the templates produce.
267
+ exercise exactly what the templates produce. The i18n checks (configured in `config/i18n-tasks.yml`)
268
+ run against the same generated app, so fix any failures in
269
+ `lib/generators/authentication/templates/config/locales/authentication.en.yml.tt`, not in
270
+ `spec/dummy`.
185
271
 
186
272
  To run the app using the dummy app generated in `spec/dummy`, run `bin/dev`
187
273
 
@@ -206,18 +292,22 @@ Run a specific Appraisal test
206
292
  bundle exec appraisal rails-8.0-json-2 rake spec:generators
207
293
  bundle exec appraisal rails-8.0-json-2 rake dummy:prepare
208
294
  bundle exec appraisal rails-8.0-json-2 rake spec:requests
295
+ bundle exec appraisal rails-8.0-json-2 rake spec:i18n
209
296
  # rails-8.0-json-3
210
297
  bundle exec appraisal rails-8.0-json-3 rake spec:generators
211
298
  bundle exec appraisal rails-8.0-json-3 rake dummy:prepare
212
299
  bundle exec appraisal rails-8.0-json-3 rake spec:requests
300
+ bundle exec appraisal rails-8.0-json-3 rake spec:i18n
213
301
  # rails-8.1-json-2
214
302
  bundle exec appraisal rails-8.1-json-2 rake spec:generators
215
303
  bundle exec appraisal rails-8.1-json-2 rake dummy:prepare
216
304
  bundle exec appraisal rails-8.1-json-2 rake spec:requests
305
+ bundle exec appraisal rails-8.1-json-2 rake spec:i18n
217
306
  # rails-8.1-json-3
218
307
  bundle exec appraisal rails-8.1-json-3 rake spec:generators
219
308
  bundle exec appraisal rails-8.1-json-3 rake dummy:prepare
220
309
  bundle exec appraisal rails-8.1-json-3 rake spec:requests
310
+ bundle exec appraisal rails-8.1-json-3 rake spec:i18n
221
311
  ```
222
312
 
223
313
  ## json 3.0 gem compatibility
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "rails/generators"
4
4
  require "rails/generators/active_record"
5
+ require "active_support/core_ext/string/indent"
5
6
  require_relative "features/confirmable"
6
7
  require_relative "features/recoverable"
7
8
  require_relative "features/registerable"
@@ -52,34 +53,55 @@ module RailsAuthentication
52
53
  source_root File.expand_path("templates", __dir__)
53
54
 
54
55
  FEATURES.each do |feature|
55
- class_option :"skip_#{feature}", type: :boolean, default: false,
56
- desc: "Skip #{feature}"
56
+ class_option :"skip_#{feature}", type: :boolean, default: false, desc: "Skip #{feature}"
57
57
  end
58
58
 
59
+ # Rails' base generator calls the column email_address; this renames it everywhere: in
60
+ # the base generator's files (by word-boundary substitution) and in this gem's templates.
61
+ class_option :email_attribute, type: :string, default: "email_address",
62
+ desc: "Name of the users table's email column"
63
+
59
64
  class_option :reconfirmable, type: :boolean, default: false,
60
- desc: "Confirmable: postpone email address changes until reconfirmed (adds unconfirmed_email column)"
65
+ desc: "Confirmable: postpone email address changes until reconfirmed (opt-in)"
61
66
 
62
67
  # Unlike the FEATURES above (default-on, opt-out via --skip-<feature>),
63
68
  # magic link is opt-in: it changes the sign-in UX, so it must be requested.
64
- class_option :magic_link, type: :boolean, default: false,
65
- desc: "Add passwordless magic link sign-in (opt-in)"
69
+ class_option :magic_link, type: :boolean, default: false, desc: "Add passwordless magic link sign-in (opt-in)"
66
70
 
67
71
  # Also opt-in: replaces the sign-in form with an email-only form that
68
72
  # emails a 6-digit one-time code, entered on a second screen. Password
69
73
  # machinery stays generated and functional.
70
74
  class_option :ott, type: :boolean, default: false,
71
- desc: "Add one-time token (emailed 6-digit code) sign-in (opt-in)"
75
+ desc: "Add one-time token (emailed 6-digit code) sign-in (opt-in)"
72
76
 
73
77
  # Also opt-in: WebAuthn passkey sign-in alongside password sign-in.
74
78
  # Requires the host app to add the `webauthn` gem itself.
75
79
  class_option :passkey, type: :boolean, default: false,
76
- desc: "Add WebAuthn passkey sign-in (opt-in; requires the webauthn gem)"
80
+ desc: "Add WebAuthn passkey sign-in (opt-in; requires the webauthn gem)"
81
+
82
+ # Checked before anything is written: the value becomes a column and method names.
83
+ def validate_email_attribute
84
+ return if email_attribute.match?(/\A[a-z_][a-z0-9_]*\z/)
85
+
86
+ raise Thor::Error, "--email-attribute must be a lowercase Ruby identifier, got #{email_attribute.inspect}"
87
+ end
77
88
 
78
89
  def install_base_authentication
79
90
  say "Running Rails' built-in authentication generator", :green
80
91
  Rails::Generators.invoke("rails:authentication", [], behavior: behavior, destination_root: destination_root)
81
92
  end
82
93
 
94
+ # Renames the base generator's email_address in the files it wrote (model, create_users
95
+ # migration, fixtures, tests, and the controllers/views/mailer that later steps may or may
96
+ # not replace). Runs before any feature step, so injections see the renamed attribute.
97
+ def rename_email_attribute
98
+ return if email_attribute == "email_address"
99
+
100
+ base_files_with_email_attribute.each do |path|
101
+ gsub_file path, /\bemail_address\b/, email_attribute
102
+ end
103
+ end
104
+
83
105
  def install_validatable
84
106
  generate_validatable if validatable?
85
107
  end
@@ -128,6 +150,20 @@ module RailsAuthentication
128
150
  generate_passkey if passkey?
129
151
  end
130
152
 
153
+ # User.authentication_email_column_name is the one place generated code reads the email column's
154
+ # name from. Injected after the feature steps so it lands above their concern includes:
155
+ # Validatable's `validates` runs at include time and needs it. normalizes uses it too.
156
+ def add_authentication_email_column_name
157
+ inject_into_class "app/models/user.rb", "User", <<~RUBY.indent(2)
158
+ # The users table's email column, read by every authentication flow. Defined before
159
+ # the concerns, which use it when they're included.
160
+ def self.authentication_email_column_name = :#{email_attribute}
161
+
162
+ RUBY
163
+ gsub_file "app/models/user.rb", /^ normalizes :#{email_attribute},/,
164
+ " normalizes authentication_email_column_name,"
165
+ end
166
+
131
167
  # Runs after every feature install so the blank line separates the concern
132
168
  # includes (if any) from the rest of the class body, no matter which features
133
169
  # are enabled.
@@ -135,21 +171,86 @@ module RailsAuthentication
135
171
  inject_into_file "app/models/user.rb", "\n", after: /(?: include \w+Concern\n)+/, force: true
136
172
  end
137
173
 
174
+ # User.available / User.unavailable: whether a user can sign in, composed from the scopes of
175
+ # whichever of Confirmable, Lockable, and Invitable are enabled. Placed, as a block of its
176
+ # own, after the base generator's `has_many :sessions` line.
177
+ def add_user_scopes
178
+ return if available_user_scope_chain.empty?
179
+
180
+ scopes = [
181
+ "scope :available, -> { #{available_user_scope_chain.join('.')} }",
182
+ "scope :unavailable, -> { where.not(id: available) }"
183
+ ]
184
+ inject_into_file "app/models/user.rb", "\n#{scopes.map { |line| " #{line}\n" }.join}",
185
+ after: /^ has_many :sessions, dependent: :destroy\n/, force: true
186
+ end
187
+
188
+ # The instance-level counterparts of User.available / User.unavailable, from the same
189
+ # enabled features, placed after the base generator's `normalizes` line.
190
+ # active_for_authentication? is Devise's name for the same check.
191
+ def add_user_availability_predicates
192
+ return if availability_checks.empty?
193
+
194
+ inject_into_file "app/models/user.rb", "\n#{user_availability_predicates}",
195
+ after: /^ normalizes authentication_email_column_name, .*\n/, force: true
196
+ end
197
+
138
198
  # Confirmable, Rememberable, Trackable, Timeoutable, and Lockable all hook into the
139
199
  # sign-in flow, so the base generator's session files are replaced with versions
140
200
  # rendered from the enabled feature set. Overwriting is safe: the base copies were
141
- # written moments ago by this same run.
201
+ # written moments ago by this same run. The Session model carries the expiry rules
202
+ # (Timeoutable's inactivity timeout, Rememberable's REMEMBERED_TIMEOUT_IN cap).
142
203
  def customize_session_layer
204
+ template "app/models/session.rb", force: true
143
205
  template "app/controllers/sessions_controller.rb", force: true
144
206
  template "app/controllers/concerns/authentication.rb", force: true
145
207
  template "app/views/sessions/new.html.erb", force: true
146
208
  end
147
209
 
210
+ def create_locale_file
211
+ template "config/locales/authentication.en.yml"
212
+ end
213
+
148
214
  no_commands do
149
215
  FEATURES.each do |feature|
150
216
  define_method(:"#{feature}?") { !options[:"skip_#{feature}"] }
151
217
  end
152
218
 
219
+ # The maxlength for new-password fields: Validatable's policy when it's generated,
220
+ # otherwise has_secure_password's hard limit (bcrypt's 72 bytes).
221
+ def password_maxlength
222
+ return "ValidatableConcern::PASSWORD_LENGTH.max" if validatable?
223
+
224
+ "ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED"
225
+ end
226
+
227
+ def email_attribute
228
+ options[:email_attribute]
229
+ end
230
+
231
+ # Reconfirmable's pending-address column. A trailing _address is dropped, so the default
232
+ # email_address (like Devise's email) pairs with unconfirmed_email.
233
+ def unconfirmed_email_attribute
234
+ "unconfirmed_#{email_attribute.delete_suffix('_address')}"
235
+ end
236
+
237
+ # The base generator's files that name email_address, relative to destination_root.
238
+ def base_files_with_email_attribute
239
+ paths = %w[
240
+ app/models/user.rb
241
+ app/controllers/sessions_controller.rb
242
+ app/controllers/passwords_controller.rb
243
+ app/mailers/passwords_mailer.rb
244
+ app/views/sessions/new.html.erb
245
+ app/views/passwords/new.html.erb
246
+ test/fixtures/users.yml
247
+ test/models/user_test.rb
248
+ test/controllers/sessions_controller_test.rb
249
+ test/controllers/passwords_controller_test.rb
250
+ ] + Dir.glob("db/migrate/*_create_users.rb", base: destination_root)
251
+ paths.select { |path| File.exist?(File.join(destination_root, path)) }
252
+ end
253
+
153
254
  def reconfirmable?
154
255
  confirmable? && options[:reconfirmable]
155
256
  end
@@ -166,6 +267,32 @@ module RailsAuthentication
166
267
  options[:passkey]
167
268
  end
168
269
 
270
+ # [available-when check, unavailable-when check] per enabled feature, matching the scopes.
271
+ def availability_checks
272
+ [
273
+ (["!locked?", "locked?"] if lockable?),
274
+ (["confirmed?", "!confirmed?"] if confirmable?),
275
+ (["!invitation_pending?", "invitation_pending?"] if invitable?)
276
+ ].compact
277
+ end
278
+
279
+ def user_availability_predicates
280
+ available = availability_checks.map(&:first).join(" &&\n ")
281
+ unavailable = availability_checks.map(&:last).join(" ||\n ")
282
+
283
+ " def available?\n #{available}\n end\n alias active_for_authentication? available?\n\n" \
284
+ " def unavailable?\n #{unavailable}\n end\n"
285
+ end
286
+
287
+ # Mirrors the sign-in checks: confirmed, not currently locked, no invitation outstanding.
288
+ def available_user_scope_chain
289
+ [
290
+ ("confirmed" if confirmable?),
291
+ ("not_locked" if lockable?),
292
+ ("not_pending" if invitable?)
293
+ ].compact
294
+ end
295
+
169
296
  def include_concern_in_user(concern)
170
297
  inject_into_class "app/models/user.rb", "User", " include #{concern}\n"
171
298
  end
@@ -14,11 +14,11 @@ module RailsAuthentication
14
14
  template "app/views/confirmations/new.html.erb"
15
15
  route "resources :confirmations, only: %i[ new create show ], param: :token"
16
16
 
17
- if defined?(ActionMailer::Railtie)
18
- template "app/mailers/confirmations_mailer.rb"
19
- template "app/views/confirmations_mailer/confirmation_instructions.html.erb"
20
- template "app/views/confirmations_mailer/confirmation_instructions.text.erb"
21
- end
17
+ return unless defined?(ActionMailer::Railtie)
18
+
19
+ template "app/mailers/confirmations_mailer.rb"
20
+ template "app/views/confirmations_mailer/confirmation_instructions.html.erb"
21
+ template "app/views/confirmations_mailer/confirmation_instructions.text.erb"
22
22
  end
23
23
  end
24
24
  end
@@ -15,11 +15,11 @@ module RailsAuthentication
15
15
  template "app/views/invitations/edit.html.erb"
16
16
  route "resources :invitations, only: %i[ new create edit update ], param: :token"
17
17
 
18
- if defined?(ActionMailer::Railtie)
19
- template "app/mailers/invitations_mailer.rb"
20
- template "app/views/invitations_mailer/invitation_instructions.html.erb"
21
- template "app/views/invitations_mailer/invitation_instructions.text.erb"
22
- end
18
+ return unless defined?(ActionMailer::Railtie)
19
+
20
+ template "app/mailers/invitations_mailer.rb"
21
+ template "app/views/invitations_mailer/invitation_instructions.html.erb"
22
+ template "app/views/invitations_mailer/invitation_instructions.text.erb"
23
23
  end
24
24
  end
25
25
  end
@@ -14,11 +14,11 @@ module RailsAuthentication
14
14
  template "app/views/unlocks/new.html.erb"
15
15
  route "resources :unlocks, only: %i[ new create show ], param: :token"
16
16
 
17
- if defined?(ActionMailer::Railtie)
18
- template "app/mailers/unlocks_mailer.rb"
19
- template "app/views/unlocks_mailer/unlock_instructions.html.erb"
20
- template "app/views/unlocks_mailer/unlock_instructions.text.erb"
21
- end
17
+ return unless defined?(ActionMailer::Railtie)
18
+
19
+ template "app/mailers/unlocks_mailer.rb"
20
+ template "app/views/unlocks_mailer/unlock_instructions.html.erb"
21
+ template "app/views/unlocks_mailer/unlock_instructions.text.erb"
22
22
  end
23
23
  end
24
24
  end
@@ -17,11 +17,11 @@ module RailsAuthentication
17
17
  template "app/views/magic_links/new.html.erb"
18
18
  route "resources :magic_links, only: %i[ new create show ], param: :token"
19
19
 
20
- if defined?(ActionMailer::Railtie)
21
- template "app/mailers/magic_links_mailer.rb"
22
- template "app/views/magic_links_mailer/magic_link.html.erb"
23
- template "app/views/magic_links_mailer/magic_link.text.erb"
24
- end
20
+ return unless defined?(ActionMailer::Railtie)
21
+
22
+ template "app/mailers/magic_links_mailer.rb"
23
+ template "app/views/magic_links_mailer/magic_link.html.erb"
24
+ template "app/views/magic_links_mailer/magic_link.text.erb"
25
25
  end
26
26
  end
27
27
  end
@@ -19,11 +19,11 @@ module RailsAuthentication
19
19
  template "app/views/otts/edit.html.erb"
20
20
  route "resource :ott, only: %i[ create edit update ]"
21
21
 
22
- if defined?(ActionMailer::Railtie)
23
- template "app/mailers/otts_mailer.rb"
24
- template "app/views/otts_mailer/ott.html.erb"
25
- template "app/views/otts_mailer/ott.text.erb"
26
- end
22
+ return unless defined?(ActionMailer::Railtie)
23
+
24
+ template "app/mailers/otts_mailer.rb"
25
+ template "app/views/otts_mailer/ott.html.erb"
26
+ template "app/views/otts_mailer/ott.text.erb"
27
27
  end
28
28
  end
29
29
  end
@@ -7,18 +7,20 @@ module RailsAuthentication
7
7
  private
8
8
 
9
9
  # Replaces the base generator's stateless generates_token_for password reset
10
- # with DB-backed, revocable tokens.
10
+ # with DB-backed, revocable tokens, and its password pages with translated ones.
11
11
  def generate_recoverable
12
12
  template "app/models/concerns/recoverable_concern.rb"
13
13
  include_concern_in_user "RecoverableConcern"
14
14
  migration_template "db/migrate/add_recoverable_to_users.rb", "db/migrate/add_recoverable_to_users.rb"
15
15
  template "app/controllers/passwords_controller.rb", force: true
16
+ template "app/views/passwords/new.html.erb", force: true
17
+ template "app/views/passwords/edit.html.erb", force: true
16
18
 
17
- if defined?(ActionMailer::Railtie)
18
- template "app/mailers/passwords_mailer.rb", force: true
19
- template "app/views/passwords_mailer/reset.html.erb", force: true
20
- template "app/views/passwords_mailer/reset.text.erb", force: true
21
- end
19
+ return unless defined?(ActionMailer::Railtie)
20
+
21
+ template "app/mailers/passwords_mailer.rb", force: true
22
+ template "app/views/passwords_mailer/reset.html.erb", force: true
23
+ template "app/views/passwords_mailer/reset.text.erb", force: true
22
24
  end
23
25
  end
24
26
  end
@@ -6,10 +6,15 @@ module RailsAuthentication
6
6
  module Rememberable
7
7
  private
8
8
 
9
+ # "Remember me" is per browser: it's stored on the Session (one row per signed-in
10
+ # browser), not the User, so checking or unchecking it on one device never changes
11
+ # another device's session. No User concern; the behavior lives in the Session
12
+ # model template. Apps generated before the move have users.remember_created_at, so it's
13
+ # dropped first (guarded, so a no-op on new apps), then the sessions column is added.
9
14
  def generate_rememberable
10
- template "app/models/concerns/rememberable_concern.rb"
11
- include_concern_in_user "RememberableConcern"
12
- migration_template "db/migrate/add_rememberable_to_users.rb", "db/migrate/add_rememberable_to_users.rb"
15
+ migration_template "db/migrate/remove_remember_created_at_from_users.rb",
16
+ "db/migrate/remove_remember_created_at_from_users.rb"
17
+ migration_template "db/migrate/add_rememberable_to_sessions.rb", "db/migrate/add_rememberable_to_sessions.rb"
13
18
  end
14
19
  end
15
20
  end