rails_authentication 0.6.0 → 0.7.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 (73) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +73 -7
  3. data/lib/generators/authentication/authentication_generator.rb +70 -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 +61 -14
  12. data/lib/generators/authentication/templates/app/controllers/confirmations_controller.rb.tt +9 -5
  13. data/lib/generators/authentication/templates/app/controllers/invitations_controller.rb.tt +13 -4
  14. data/lib/generators/authentication/templates/app/controllers/magic_links_controller.rb.tt +9 -7
  15. data/lib/generators/authentication/templates/app/controllers/otts_controller.rb.tt +12 -9
  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 +21 -8
  18. data/lib/generators/authentication/templates/app/controllers/registrations_controller.rb.tt +7 -5
  19. data/lib/generators/authentication/templates/app/controllers/sessions_controller.rb.tt +9 -7
  20. data/lib/generators/authentication/templates/app/controllers/unlocks_controller.rb.tt +7 -5
  21. data/lib/generators/authentication/templates/app/controllers/webauthn_credentials_controller.rb.tt +7 -3
  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 +7 -2
  29. data/lib/generators/authentication/templates/app/models/concerns/invitable_concern.rb.tt +12 -1
  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 +5 -3
  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 +6 -6
  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_rememberable_to_sessions.rb.tt +5 -0
  69. data/lib/generators/authentication/templates/db/migrate/remove_remember_created_at_from_users.rb.tt +11 -0
  70. data/lib/rails_authentication/version.rb +1 -1
  71. metadata +8 -3
  72. data/lib/generators/authentication/templates/app/models/concerns/rememberable_concern.rb.tt +0 -15
  73. 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: 963bda221b35580094da510f2b99d167109a5d07c6b61da9ea43b76797f22f77
4
+ data.tar.gz: d101e76f7ba2a3f02a6008ebbf7d984f39be27b8f66518edacda226afe350db0
5
5
  SHA512:
6
- metadata.gz: 0c0849f4c52e57761a6d43a555b2c70712be764c96dc205ec10805ba983637777e53d1326e1b41b106c4ad7baeae258680e073aec19e47a42f08d9fce2b731f9
7
- data.tar.gz: 8f1021d0c9e8c7a7ef71f791a83b24948af32b628154671b1dce31ad8cfe2299d5234a278412a45cff9b11fdc81201281ebbdd89ea391a49d7a41664bba14e03
6
+ metadata.gz: 275f96568c53fc008c6d23625f6ca69e74c8f463a73862ffe884534fca585871c6ffe004e043956be8a8dd934639ec1dd5b1401fe5c38fc82b3a44bead0a0e31
7
+ data.tar.gz: d89a01240bcd8fb2aa877018602e3fe83e59c9bfa68ce8629f9981e3a73ba9d9c733944527083d6cd050a93876640ae06d56c44bae25c18045bb22de7f256daa
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 |
@@ -92,12 +92,68 @@ register any number of passkeys, each stored as its own row in `webauthn_credent
92
92
  All three flows honor the other enabled features: locked, unconfirmed, or invitation-pending
93
93
  accounts still can't sign in, and Trackable records the attempt.
94
94
 
95
+ Signed-out pages (sign-in, sign-up, password reset, confirmation and unlock requests, invitation
96
+ acceptance, magic link and one-time code sign-in) redirect an already-signed-in user to the root
97
+ path with "You are already signed in." The emailed confirmation link stays reachable so a
98
+ signed-in user can confirm an email change.
99
+
100
+ Every controller requires a signed-in user unless it says otherwise. Three class methods, all
101
+ taking `before_action`'s `only:`/`except:` options, declare access:
102
+
103
+ | Method | Who can access |
104
+ |---|---|
105
+ | `allow_unauthenticated_access` | Everyone, signed in or not |
106
+ | `require_unauthenticated_access` | Signed-out visitors only; signed-in users are redirected to the root path |
107
+ | `require_authenticated_access` | Signed-in users only (the default; use it to be explicit, or to re-protect actions a parent controller opened) |
108
+
109
+ After signing in by any method, a user returns to the page they were sent away from (page visits
110
+ only, not form submissions or JSON requests). With no such page they land on
111
+ `default_after_authentication_url`, which is `root_url` unless you override it in
112
+ `ApplicationController`; already-signed-in users redirected away from signed-out pages land there
113
+ too:
114
+
115
+ ```ruby
116
+ class ApplicationController < ActionController::Base
117
+ include Authentication
118
+
119
+ private
120
+
121
+ def default_after_authentication_url
122
+ dashboard_url
123
+ end
124
+ end
125
+ ```
126
+
95
127
  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`,
128
+ model behavior lives in `app/models/concerns/<feature>_concern.rb`. Rememberable is the exception:
129
+ "remember me" belongs to one browser, not the user, so it's a `remembered_at` column on `sessions`
130
+ and `Session#remembered?`, with no User concern. Checking or unchecking it, or signing out, on one
131
+ device never changes another device's session. Magic link and passkey sign-ins aren't remembered.
132
+ Apps generated before this change get a `remove_remember_created_at_from_users` migration that
133
+ drops the old `users.remember_created_at` column (a no-op where it doesn't exist); previously
134
+ remembered users simply need to check "Remember me" again.
135
+ Each feature's concern adds scopes that match its checks: `User.confirmed` / `unconfirmed`,
136
+ `User.locked` / `not_locked` (a lock expires after `LockableConcern::UNLOCK_IN`, as at sign-in), and
137
+ `User.pending` / `not_pending` / `accepted` for invitations (users who signed up without one are
138
+ never `pending`). `User.available` combines the enabled ones into "can sign in" (confirmed, not locked,
139
+ no outstanding invitation) and `User.unavailable` is everyone else. The instance versions are
140
+ `user.available?` (also `active_for_authentication?`, Devise's name) and `user.unavailable?`.
141
+
142
+ Session expiry lives in the generated `app/models/session.rb`: `Session#expired?` (checked on
143
+ every request) and a `Session.expired` scope you can use to purge stale rows, e.g. from a
144
+ recurring job (`Session.expired.delete_all`). Remembered sessions are exempt from Timeoutable's
145
+ inactivity timeout but still expire after `Session::REMEMBERED_TIMEOUT_IN` (90 days) of inactivity. Tunables are plain constants in
146
+ the generated concerns — e.g. `TimeoutableConcern::TIMEOUT_IN`, `Session::REMEMBERED_TIMEOUT_IN`, `LockableConcern::MAXIMUM_ATTEMPTS`,
98
147
  `LockableConcern::UNLOCK_IN`, `ConfirmableConcern::CONFIRMATION_TOKEN_EXPIRES_IN`,
99
148
  `ValidatableConcern::PASSWORD_LENGTH`, `ValidatableConcern::PASSWORD_MINIMUM_COMPLEXITY`,
100
149
  `OttConcern::OTT_CODE_LENGTH` — edit them there. Concerns keep the model clean.
150
+ `PASSWORD_LENGTH` also sets the `maxlength` of the new-password fields; its upper bound can't
151
+ exceed 72, bcrypt's limit (`ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED`).
152
+
153
+ All user-facing text in the generated code (views, flash messages, passkey error messages, email
154
+ subjects, and validation messages) lives in `config/locales/authentication.en.yml`, so you can
155
+ reword it or add other locales without touching the code. The file only contains translations for
156
+ the features you generated.
101
157
 
102
158
  ### Inviting users
103
159
 
@@ -164,8 +220,9 @@ resources :passwords, param: :token # from the base generator
164
220
  Confirmable to an app with existing users:
165
221
  `User.update_all(confirmed_at: Time.current)`.
166
222
  - **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.
223
+ stateless signed tokens) with DB-token versions, and its password pages with translated ones. If
224
+ you `--skip-recoverable`, the base flow is left untouched, including Rails' English-only password
225
+ pages and messages.
169
226
  - The generator overwrites the base generator's `SessionsController`, `Authentication` concern, and
170
227
  sessions view with versions tailored to the features you selected. Run the generator once, up
171
228
  front — re-running it after you've customized those files will prompt to overwrite them.
@@ -177,11 +234,16 @@ bundle install
177
234
  bundle exec rake spec:generators # generator specs (fast, no app boot)
178
235
  bundle exec rake dummy:prepare # build spec/dummy by running the real generator
179
236
  bundle exec rake spec:requests # request specs against spec/dummy
180
- bundle exec rspec spec/generators/lockable_spec.rb:12 # a single example
237
+ bundle exec rake spec:i18n # i18n-tasks checks on spec/dummy's generated locale file
238
+ bundle exec rspec spec/generators/rails_authentication/generators/features/lockable_spec.rb:12 # a single example
239
+ bundle exec rubocop # lint
181
240
  ```
182
241
 
183
242
  `spec/dummy` is generated (and gitignored), never hand-maintained, so the request specs always
184
- exercise exactly what the templates produce.
243
+ exercise exactly what the templates produce. The i18n checks (configured in `config/i18n-tasks.yml`)
244
+ run against the same generated app, so fix any failures in
245
+ `lib/generators/authentication/templates/config/locales/authentication.en.yml.tt`, not in
246
+ `spec/dummy`.
185
247
 
186
248
  To run the app using the dummy app generated in `spec/dummy`, run `bin/dev`
187
249
 
@@ -206,18 +268,22 @@ Run a specific Appraisal test
206
268
  bundle exec appraisal rails-8.0-json-2 rake spec:generators
207
269
  bundle exec appraisal rails-8.0-json-2 rake dummy:prepare
208
270
  bundle exec appraisal rails-8.0-json-2 rake spec:requests
271
+ bundle exec appraisal rails-8.0-json-2 rake spec:i18n
209
272
  # rails-8.0-json-3
210
273
  bundle exec appraisal rails-8.0-json-3 rake spec:generators
211
274
  bundle exec appraisal rails-8.0-json-3 rake dummy:prepare
212
275
  bundle exec appraisal rails-8.0-json-3 rake spec:requests
276
+ bundle exec appraisal rails-8.0-json-3 rake spec:i18n
213
277
  # rails-8.1-json-2
214
278
  bundle exec appraisal rails-8.1-json-2 rake spec:generators
215
279
  bundle exec appraisal rails-8.1-json-2 rake dummy:prepare
216
280
  bundle exec appraisal rails-8.1-json-2 rake spec:requests
281
+ bundle exec appraisal rails-8.1-json-2 rake spec:i18n
217
282
  # rails-8.1-json-3
218
283
  bundle exec appraisal rails-8.1-json-3 rake spec:generators
219
284
  bundle exec appraisal rails-8.1-json-3 rake dummy:prepare
220
285
  bundle exec appraisal rails-8.1-json-3 rake spec:requests
286
+ bundle exec appraisal rails-8.1-json-3 rake spec:i18n
221
287
  ```
222
288
 
223
289
  ## json 3.0 gem compatibility
@@ -52,28 +52,26 @@ module RailsAuthentication
52
52
  source_root File.expand_path("templates", __dir__)
53
53
 
54
54
  FEATURES.each do |feature|
55
- class_option :"skip_#{feature}", type: :boolean, default: false,
56
- desc: "Skip #{feature}"
55
+ class_option :"skip_#{feature}", type: :boolean, default: false, desc: "Skip #{feature}"
57
56
  end
58
57
 
59
58
  class_option :reconfirmable, type: :boolean, default: false,
60
- desc: "Confirmable: postpone email address changes until reconfirmed (adds unconfirmed_email column)"
59
+ desc: "Confirmable: postpone email address changes until reconfirmed (opt-in)"
61
60
 
62
61
  # Unlike the FEATURES above (default-on, opt-out via --skip-<feature>),
63
62
  # 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)"
63
+ class_option :magic_link, type: :boolean, default: false, desc: "Add passwordless magic link sign-in (opt-in)"
66
64
 
67
65
  # Also opt-in: replaces the sign-in form with an email-only form that
68
66
  # emails a 6-digit one-time code, entered on a second screen. Password
69
67
  # machinery stays generated and functional.
70
68
  class_option :ott, type: :boolean, default: false,
71
- desc: "Add one-time token (emailed 6-digit code) sign-in (opt-in)"
69
+ desc: "Add one-time token (emailed 6-digit code) sign-in (opt-in)"
72
70
 
73
71
  # Also opt-in: WebAuthn passkey sign-in alongside password sign-in.
74
72
  # Requires the host app to add the `webauthn` gem itself.
75
73
  class_option :passkey, type: :boolean, default: false,
76
- desc: "Add WebAuthn passkey sign-in (opt-in; requires the webauthn gem)"
74
+ desc: "Add WebAuthn passkey sign-in (opt-in; requires the webauthn gem)"
77
75
 
78
76
  def install_base_authentication
79
77
  say "Running Rails' built-in authentication generator", :green
@@ -135,21 +133,59 @@ module RailsAuthentication
135
133
  inject_into_file "app/models/user.rb", "\n", after: /(?: include \w+Concern\n)+/, force: true
136
134
  end
137
135
 
136
+ # User.available / User.unavailable: whether a user can sign in, composed from the scopes of
137
+ # whichever of Confirmable, Lockable, and Invitable are enabled. Placed, as a block of its
138
+ # own, after the base generator's `has_many :sessions` line.
139
+ def add_user_scopes
140
+ return if available_user_scope_chain.empty?
141
+
142
+ scopes = [
143
+ "scope :available, -> { #{available_user_scope_chain.join('.')} }",
144
+ "scope :unavailable, -> { where.not(id: available) }"
145
+ ]
146
+ inject_into_file "app/models/user.rb", "\n#{scopes.map { |line| " #{line}\n" }.join}",
147
+ after: /^ has_many :sessions, dependent: :destroy\n/, force: true
148
+ end
149
+
150
+ # The instance-level counterparts of User.available / User.unavailable, from the same
151
+ # enabled features, placed after the base generator's `normalizes :email_address` line.
152
+ # active_for_authentication? is Devise's name for the same check.
153
+ def add_user_availability_predicates
154
+ return if availability_checks.empty?
155
+
156
+ inject_into_file "app/models/user.rb", "\n#{user_availability_predicates}",
157
+ after: /^ normalizes :email_address, .*\n/, force: true
158
+ end
159
+
138
160
  # Confirmable, Rememberable, Trackable, Timeoutable, and Lockable all hook into the
139
161
  # sign-in flow, so the base generator's session files are replaced with versions
140
162
  # rendered from the enabled feature set. Overwriting is safe: the base copies were
141
- # written moments ago by this same run.
163
+ # written moments ago by this same run. The Session model carries the expiry rules
164
+ # (Timeoutable's inactivity timeout, Rememberable's REMEMBERED_TIMEOUT_IN cap).
142
165
  def customize_session_layer
166
+ template "app/models/session.rb", force: true
143
167
  template "app/controllers/sessions_controller.rb", force: true
144
168
  template "app/controllers/concerns/authentication.rb", force: true
145
169
  template "app/views/sessions/new.html.erb", force: true
146
170
  end
147
171
 
172
+ def create_locale_file
173
+ template "config/locales/authentication.en.yml"
174
+ end
175
+
148
176
  no_commands do
149
177
  FEATURES.each do |feature|
150
178
  define_method(:"#{feature}?") { !options[:"skip_#{feature}"] }
151
179
  end
152
180
 
181
+ # The maxlength for new-password fields: Validatable's policy when it's generated,
182
+ # otherwise has_secure_password's hard limit (bcrypt's 72 bytes).
183
+ def password_maxlength
184
+ return "ValidatableConcern::PASSWORD_LENGTH.max" if validatable?
185
+
186
+ "ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED"
187
+ end
188
+
153
189
  def reconfirmable?
154
190
  confirmable? && options[:reconfirmable]
155
191
  end
@@ -166,6 +202,32 @@ module RailsAuthentication
166
202
  options[:passkey]
167
203
  end
168
204
 
205
+ # [available-when check, unavailable-when check] per enabled feature, matching the scopes.
206
+ def availability_checks
207
+ [
208
+ (["!locked?", "locked?"] if lockable?),
209
+ (["confirmed?", "!confirmed?"] if confirmable?),
210
+ (["!invitation_pending?", "invitation_pending?"] if invitable?)
211
+ ].compact
212
+ end
213
+
214
+ def user_availability_predicates
215
+ available = availability_checks.map(&:first).join(" &&\n ")
216
+ unavailable = availability_checks.map(&:last).join(" ||\n ")
217
+
218
+ " def available?\n #{available}\n end\n alias active_for_authentication? available?\n\n" \
219
+ " def unavailable?\n #{unavailable}\n end\n"
220
+ end
221
+
222
+ # Mirrors the sign-in checks: confirmed, not currently locked, no invitation outstanding.
223
+ def available_user_scope_chain
224
+ [
225
+ ("confirmed" if confirmable?),
226
+ ("not_locked" if lockable?),
227
+ ("not_pending" if invitable?)
228
+ ].compact
229
+ end
230
+
169
231
  def include_concern_in_user(concern)
170
232
  inject_into_class "app/models/user.rb", "User", " include #{concern}\n"
171
233
  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
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Authentication
2
4
  extend ActiveSupport::Concern
3
5
 
@@ -6,10 +8,27 @@ module Authentication
6
8
  helper_method :authenticated?, :current_user
7
9
  end
8
10
 
11
+ # Every controller requires a signed-in user by default (the before_action above).
9
12
  class_methods do
13
+ # Open to everyone, signed in or not.
10
14
  def allow_unauthenticated_access(**options)
11
15
  skip_before_action :require_authentication, **options
12
16
  end
17
+
18
+ # Signed-out only, for sign-in, sign-up, and the other signed-out flows: open to visitors,
19
+ # while a user who is already signed in is sent to the root path instead.
20
+ def require_unauthenticated_access(**options)
21
+ allow_unauthenticated_access(**options)
22
+ before_action :redirect_signed_in_user, **options
23
+ end
24
+
25
+ # Signed-in only. Already the default, so this is for being explicit, or for re-protecting
26
+ # actions a parent controller opened with allow_unauthenticated_access. It registers its
27
+ # own callback rather than :require_authentication: re-registering that one with only:/except:
28
+ # would replace the default and leave the other actions unprotected.
29
+ def require_authenticated_access(**options)
30
+ before_action :enforce_authentication, **options
31
+ end
13
32
  end
14
33
 
15
34
  private
@@ -26,20 +45,31 @@ module Authentication
26
45
  resume_session || request_authentication
27
46
  end
28
47
 
48
+ def enforce_authentication
49
+ require_authentication
50
+ end
51
+
52
+ # allow_unauthenticated_access skips resume_session, so authenticated? loads it here.
53
+ def redirect_signed_in_user
54
+ return unless authenticated?
55
+
56
+ if request.format.json?
57
+ render json: { error: t("flash.authentication.alert.already_signed_in") }, status: :forbidden
58
+ else
59
+ redirect_to default_after_authentication_url, alert: t("flash.authentication.alert.already_signed_in")
60
+ end
61
+ end
62
+
29
63
  def resume_session
30
64
  Current.session ||= find_session_by_cookie
31
65
  end
32
66
 
33
- <% if timeoutable? -%>
67
+ <% if timeoutable? || rememberable? -%>
34
68
  def find_session_by_cookie
35
69
  return unless cookies.signed[:session_id]
36
70
  return unless session = Session.find_by(id: cookies.signed[:session_id])
37
71
 
38
- <% if rememberable? -%>
39
- if !session.user.remembered? && session.user.timedout?(session.updated_at)
40
- <% else -%>
41
- if session.user.timedout?(session.updated_at)
42
- <% end -%>
72
+ if session.expired?
43
73
  session.destroy
44
74
  cookies.delete(:session_id)
45
75
  nil
@@ -54,25 +84,36 @@ module Authentication
54
84
  end
55
85
  <% end -%>
56
86
 
87
+ # Only page visits are remembered: returning to a form submission or a JSON/XHR endpoint
88
+ # after sign-in would hit the wrong action (a GET to a POST-only URL) or render raw data.
57
89
  def request_authentication
58
- session[:return_to_after_authenticating] = request.url
90
+ session[:return_to_after_authenticating] = request.url if request.get? && request.format.html? && !request.xhr?
59
91
  redirect_to new_session_path
60
92
  end
61
93
 
94
+ # Where every sign-in flow lands: the page the user was sent away from, otherwise the default.
62
95
  def after_authentication_url
63
- session.delete(:return_to_after_authenticating) || root_url
96
+ session.delete(:return_to_after_authenticating) || default_after_authentication_url
97
+ end
98
+
99
+ # Where signed-in users land when there's no page to return to. Override it in
100
+ # ApplicationController (e.g. `dashboard_url`) to change the default for every flow.
101
+ def default_after_authentication_url
102
+ root_url
64
103
  end
65
104
 
66
105
  <% if rememberable? -%>
106
+ # Remembering is per browser: it's stamped on this session only, never on the user,
107
+ # so other devices' sessions are unaffected.
67
108
  def start_new_session_for(user, remember: false)
68
- user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session|
109
+ user.sessions.create!(
110
+ user_agent: request.user_agent, ip_address: request.remote_ip, remembered_at: (Time.current if remember)
111
+ ).tap do |session|
69
112
  Current.session = session
70
113
 
71
114
  if remember
72
- user.remember_me!
73
115
  cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax }
74
116
  else
75
- user.forget_me!
76
117
  cookies.signed[:session_id] = { value: session.id, httponly: true, same_site: :lax }
77
118
  end
78
119
  end
@@ -87,10 +128,16 @@ module Authentication
87
128
  <% end -%>
88
129
 
89
130
  def terminate_session
90
- <% if rememberable? -%>
91
- Current.session.user.forget_me!
92
- <% end -%>
93
131
  Current.session.destroy
94
132
  cookies.delete(:session_id)
95
133
  end
134
+
135
+ def terminate_all_sessions_for(user)
136
+ user.sessions.destroy_all
137
+
138
+ if Current.user == user
139
+ Current.session = nil
140
+ cookies.delete(:session_id)
141
+ end
142
+ end
96
143
  end
@@ -1,6 +1,10 @@
1
+ # frozen_string_literal: true
2
+
1
3
  class ConfirmationsController < ApplicationController
2
- allow_unauthenticated_access
3
- rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_confirmation_path, alert: "Try again later." }
4
+ # show stays open to everyone: with --reconfirmable, a signed-in user confirms an email change there.
5
+ allow_unauthenticated_access only: :show
6
+ require_unauthenticated_access except: :show
7
+ rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_confirmation_path, alert: t("flash.confirmations.create.alert.rate_limited") }
4
8
 
5
9
  def new
6
10
  end
@@ -13,15 +17,15 @@ class ConfirmationsController < ApplicationController
13
17
  user.send_confirmation_instructions if user && !user.confirmed?
14
18
  <% end -%>
15
19
 
16
- redirect_to new_session_path, notice: "Confirmation instructions sent (if user with that email address exists and is unconfirmed)."
20
+ redirect_to new_session_path, notice: t("flash.confirmations.create.notice")
17
21
  end
18
22
 
19
23
  def show
20
24
  if user = User.find_by_valid_confirmation_token(params[:token])
21
25
  user.confirm!
22
- redirect_to new_session_path, notice: "Your email address has been confirmed. Please sign in."
26
+ redirect_to new_session_path, notice: t("flash.confirmations.show.notice")
23
27
  else
24
- redirect_to new_confirmation_path, alert: "Confirmation link is invalid or has expired."
28
+ redirect_to new_confirmation_path, alert: t("flash.confirmations.show.alert.invalid_token")
25
29
  end
26
30
  end
27
31
  end
@@ -1,5 +1,7 @@
1
+ # frozen_string_literal: true
2
+
1
3
  class InvitationsController < ApplicationController
2
- allow_unauthenticated_access only: %i[ edit update ]
4
+ require_unauthenticated_access only: %i[ edit update ]
3
5
  before_action :set_user_by_token, only: %i[ edit update ]
4
6
 
5
7
  def new
@@ -9,7 +11,7 @@ class InvitationsController < ApplicationController
9
11
  user = User.invite!(invitation_params, invited_by: Current.user)
10
12
 
11
13
  if user.persisted?
12
- redirect_to new_invitation_path, notice: "Invitation sent to #{user.email_address}."
14
+ redirect_to new_invitation_path, notice: t("flash.invitations.create.notice", email_address: user.email_address)
13
15
  else
14
16
  redirect_to new_invitation_path, alert: user.errors.full_messages.to_sentence
15
17
  end
@@ -21,7 +23,7 @@ class InvitationsController < ApplicationController
21
23
  def update
22
24
  if @user.accept_invitation!(password: params[:password], password_confirmation: params[:password_confirmation])
23
25
  start_new_session_for @user
24
- redirect_to after_authentication_url, notice: "Welcome! Your account is ready."
26
+ redirect_to after_authentication_url, notice: t("flash.invitations.update.notice")
25
27
  else
26
28
  redirect_to edit_invitation_path(params[:token]), alert: @user.errors.full_messages.to_sentence
27
29
  end
@@ -36,6 +38,13 @@ class InvitationsController < ApplicationController
36
38
 
37
39
  def set_user_by_token
38
40
  @user = User.find_by_valid_invitation_token(params[:token])
39
- redirect_to new_session_path, alert: "Invitation link is invalid or has expired." unless @user
41
+ return if @user
42
+
43
+ alert = if action_name == "edit"
44
+ t("flash.invitations.edit.alert.invalid_token")
45
+ else
46
+ t("flash.invitations.update.alert.invalid_token")
47
+ end
48
+ redirect_to new_session_path, alert: alert
40
49
  end
41
50
  end