cybertrain 0.3.1 → 0.4.1

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.
@@ -4,74 +4,340 @@
4
4
  #
5
5
  # db/migrate/*_create_users.rb, *_create_sessions.rb
6
6
  # app/models/user.rb, app/models/session.rb
7
+ # app/controllers/concerns/authentication.rb the Authentication concern
7
8
  # app/controllers/sessions_controller.rb, registrations_controller.rb
9
+ # app/controllers/passwords_controller.rb password reset by mail
10
+ # app/controllers/accounts_controller.rb the account page: a new
11
+ # address or password, or
12
+ # the account deleted
13
+ # app/mailers/passwords_mailer.rb its mail
14
+ # app/commands/user_command.rb `./<app> user ...`
8
15
  # app/views/sessions/new.html.erb, _nav.html.erb, registrations/new.html.erb
9
- # test/authentication.rb, test/support/app_test.rb
16
+ # app/views/passwords/new.html.erb, edit.html.erb, mail/_password_reset.html.erb
17
+ # app/views/accounts/edit.html.erb
18
+ # test/fixtures/users.yml, test/support/session_test_helper.rb
19
+ # (sign_in_as, included into ActionDispatch::IntegrationTest by
20
+ # test/test_helper.rb) and the class-form tests cybertrain test runs:
21
+ # test/models/user_test.rb, test/controllers/sessions_controller_test.rb,
22
+ # registrations_controller_test.rb, passwords_controller_test.rb,
23
+ # accounts_controller_test.rb, test/integration/remember_me_test.rb,
24
+ # lockout_test.rb, admin_test.rb (cli/authentication_tests.rb)
10
25
  #
11
- # and three edits: `before_action`s and the sign-in helpers into
26
+ # and these edits: `include Authentication` into
12
27
  # app/controllers/application_controller.rb, the routes into
13
- # config/routes.rb and the nav partial into the layout (plus a sign-in in
14
- # any test/attachment_*.rb written before it, which now needs one). Every
15
- # file is written once (Templates.write never overwrites) and every edit is
16
- # made once, so running the generator again is harmless.
28
+ # config/routes.rb (and the jobs page's line, a comment until now, drawn
29
+ # behind require_admin), the nav partial into the layout, the user command
30
+ # into bin/<app>.rb, the base_url setting (<APP>_BASE_URL, where links in
31
+ # mails start) into config/app.rb (plus a sign-in in any
32
+ # test/integration/*_attachment_test.rb, and in a scaffold's
33
+ # test/controllers/*_controller_test.rb, written before it, which now
34
+ # need one). Every file is written once
35
+ # and every edit is made once, so running the generator again is
36
+ # harmless.
37
+ #
38
+ # Run over an application an older generator wrote (0.4's, or one
39
+ # without --confirmable; D19 of docs/superpowers/plans/2026-11-11-phase4b-i18n-auth-plan.md),
40
+ # it writes the files that are missing, a db/migrate/<v>_add_authentication_columns.rb
41
+ # with the columns the existing migrations lack, and the edits above; a
42
+ # file it writes whole that exists with other content is left alone and
43
+ # its diff printed (CLI::LineDiff; `patch -p1` applies the whole output),
44
+ # or overwritten with --force. 0.4's authentication block in
45
+ # ApplicationController (LEGACY_APPLICATION_CONTROLLER_BLOCKS) becomes
46
+ # `include Authentication` the same way, --force replacing it only as 0.4
47
+ # wrote it, and the jobs page's route follows it.
48
+ #
49
+ # Every word the screens show goes through t(): lazy keys
50
+ # (`t(".title")`, sessions.new.title) in the views and the actions,
51
+ # absolute ones in private methods, all of them in the bundled en and ja
52
+ # dictionaries (cybertrain/locales/*.yml); an application's
53
+ # config/locales overrides any of them.
17
54
  #
18
55
  # Sign-in attempts are rate limited as in Rails' generator (`rate_limit to:
19
- # 10, within: 3 * 60, only: [:create]`, per client address, per process;
20
- # docs/design.md D26), and AppTest.sign_in resets the counts so a test
21
- # suite never reaches the limit.
56
+ # 10, within: 3 * 60, only: [:create]`, per client address, counted in
57
+ # Cybertrain::Cache; docs/design.md D26), and AppTest.sign_in resets the
58
+ # counts so a test suite never reaches the limit.
59
+ #
60
+ # Users have an admin flag (`users.admin`, User#admin?), which the
61
+ # concern's require_admin asks for and `./<app> user admin EMAIL` sets.
62
+ #
63
+ # Lockout (users.failed_attempts, users.locked_until): auth_lockout_attempts
64
+ # wrong passwords lock an account for auth_lockout_period, answered with the
65
+ # wrong-password message. Remember me (sessions.remember): the sign-in
66
+ # form's "Keep me signed in" box makes a sign-in last auth_remember_for in
67
+ # place of session_absolute_max_age, with a cookie that has a Max-Age;
68
+ # unchecked, the cookie ends with the browser. Either way a sign-in unused
69
+ # for auth_idle_timeout ends (sessions.last_active_at).
22
70
  #
23
- # What it leaves out, and why: password reset (needs a mailer, which
24
- # cybertrain does not have) and a `Current` object (templates read `@current_user` instead, an ivar
71
+ # Password reset (/passwords): a link by mail (deliver_later, so the app
72
+ # needs the CYBERTRAIN_SMTP_* settings and a job thread), valid for 15
73
+ # minutes and until the password or the address changes; the answer is
74
+ # the same for an unknown address. The link starts with the base_url setting, else with
75
+ # the request's address only where a forged Host cannot reach it (the
76
+ # concern's mail_link_base). A reset clears a lockout and ends every
77
+ # session of the user.
78
+ #
79
+ # The account page (/account/edit, the nav's "Account"): a new address
80
+ # (at once; with --confirmable once confirmed) or a new password, either
81
+ # only with the current password, and the account deleted (with its
82
+ # sessions, in one transaction), only with the password. A new password
83
+ # ends the user's other sessions and signs this browser in again,
84
+ # remembered as it was. Wrong passwords there are rate limited per client
85
+ # address as sign-ins are, and per user.
86
+ #
87
+ # What it leaves out, and why: a `Current` object (templates read `@current_user` instead, an ivar
25
88
  # `resume_session` sets on every controller). What it adds that Rails'
26
89
  # does not: a sign-up page, because there is no console to create the first
27
- # user in (Spinel has no `eval`).
90
+ # user in (Spinel has no `eval`), and the user command.
28
91
  #
29
92
  # `--invite-only` (docs/design.md D29) writes no sign-up page. Instead:
30
93
  #
31
- # app/commands/user_command.rb `./<app> user EMAIL [PASSWORD]`, a
32
- # Main.command that creates a user or sets
33
- # its password (from stdin when not given),
34
- # and the boot warning while no user exists
35
94
  # app/controllers/setup_controller.rb, app/views/setup/new.html.erb
36
95
  # /setup, the first user's form: only while
37
96
  # no user exists, only with the one-time
38
97
  # token the boot warning prints, only from
39
98
  # loopback unless <APP>_SETUP_OPEN=1
40
99
  #
41
- # plus two more edits: the require and the warning into bin/<app>.rb
42
- # (before `exit(Cybertrain::Main.run(`), and the `setup_open` setting into
100
+ # plus the boot warning while no user exists (in the user command's file,
101
+ # called from bin/<app>.rb), and the `setup_open` setting into
43
102
  # config/app.rb's configure block.
103
+ #
104
+ # `--confirmable` (either mode) asks each new account to confirm its
105
+ # address by mail before it can sign in, and a new address on the account
106
+ # page to confirm itself before it takes the old one's place:
107
+ #
108
+ # users.confirmed_at, users.unconfirmed_email (in the users migration)
109
+ # app/controllers/confirmations_controller.rb the link, and the form
110
+ # that sends it again
111
+ # app/mailers/confirmations_mailer.rb, app/views/confirmations/new.html.erb,
112
+ # app/views/mail/_confirmation.html.erb,
113
+ # test/controllers/confirmations_controller_test.rb
114
+ #
115
+ # plus the confirmations route. Sign-up mails the link and signs nobody
116
+ # in; a sign-in with the right password and an address not confirmed yet
117
+ # is refused with its own message (the wrong-password one otherwise); the
118
+ # link confirms, and the user then signs in. Users made by /setup and by
119
+ # the user command are confirmed as they are created: nothing mails them.
44
120
  require "cybertrain/cli/templates"
45
121
  require "cybertrain/cli/scaffold"
46
122
  require "cybertrain/cli/build"
123
+ require "cybertrain/cli/line_diff"
124
+ require "cybertrain/cli/authentication_tests"
47
125
 
48
126
  module Cybertrain
49
127
  module CLI
50
128
  module Authentication
51
129
  CLASS_LINE = "class ApplicationController < Cybertrain::Controller"
52
130
  ROUTE_MARK = "resource :session"
131
+ # The password reset's routes, added after ROUTE_MARK's line to an app
132
+ # whose routes have the sign-in but not these yet.
133
+ PASSWORDS_ROUTE_MARK = "resources :passwords"
134
+ PASSWORDS_ROUTE = "resources :passwords, param: :token, only: [:new, :create, :edit, :update]"
135
+ # The account page's route, added after PASSWORDS_ROUTE_MARK's line the
136
+ # same way.
137
+ ACCOUNT_ROUTE_MARK = "resource :account"
138
+ ACCOUNT_ROUTE = "resource :account, only: [:edit, :update, :destroy]"
139
+ # --confirmable's routes, added after PASSWORDS_ROUTE_MARK's line (so
140
+ # before the account's) the same way.
141
+ CONFIRMATIONS_ROUTE_MARK = "resources :confirmations"
142
+ CONFIRMATIONS_ROUTE = "resources :confirmations, param: :token, only: [:new, :create, :show]"
143
+ # --confirmable's button that withdraws a new address waiting, added
144
+ # after ACCOUNT_ROUTE_MARK's line.
145
+ PENDING_EMAIL_ROUTE_MARK = "/account/pending_email"
146
+ PENDING_EMAIL_ROUTE = "delete \"/account/pending_email\", to: \"accounts#cancel_email_change\", as: \"account_pending_email\""
53
147
  NAV_LINE = "<%= render \"sessions/nav\" %>"
54
- # What an app test's new_client needs once the app has authentication:
55
- # empty the two tables, then a user signed in through the form.
56
- # `generate attachment` writes them into its test when app/models/user.rb
57
- # exists; add_sign_in_to_attachment_tests adds them to a test written
58
- # before this generator ran.
59
- TEST_RESET_LINES = " Session.all.delete_all\n User.all.delete_all\n"
60
- TEST_SIGN_IN_LINES = " AppTest.user\n AppTest.sign_in(client)\n"
61
- NEW_CLIENT_LINE = "def new_client"
62
- TEST_CLIENT_LINE = " client = Cybertrain::Test::Client.new(APP)"
63
- # --invite-only's two edits: bin/<app>.rb gets the command file and the
64
- # boot warning before this line, config/app.rb the setting after this one.
148
+ # The setup line of an ActionDispatch::IntegrationTest (the
149
+ # attachment's, the scaffold's controller test): `generate attachment`
150
+ # writes test_sign_in_lines after it when app/models/user.rb exists;
151
+ # add_sign_in_to_attachment_tests and add_sign_in_to_controller_tests
152
+ # add a sign-in to a test written before this generator ran.
153
+ TEST_SETUP_LINE = " setup do"
154
+ # The sign-in line (SessionTestHelper#sign_in_as of the fixture user
155
+ # `one`); a test that has it signs in already.
156
+ TEST_SIGN_IN_POST = "sign_in_as users(:one)"
157
+ # The edits bin/<app>.rb and config/app.rb get: the user command's file
158
+ # (and, with --invite-only, the boot warning) before this line, the
159
+ # setting (--invite-only) after this one.
65
160
  MAIN_RUN_LINE = "exit(Cybertrain::Main.run("
66
161
  CONFIGURE_LINE = "Cybertrain.configure do |c|"
67
162
  COMMAND_REQUIRE = "require_relative \"../app/commands/user_command\""
163
+ # What ApplicationController gets right after its class line.
164
+ INCLUDE_LINE = "include Authentication"
165
+ # `cybertrain new`'s routes carry the jobs page as a comment of this
166
+ # line (Templates.routes), there being no require_admin yet.
167
+ NEW_APP_JOBS_PAGE_LINE = "jobs_page \"/admin/jobs\", before_action: :require_admin"
168
+ # What enable_jobs_page draws in its place: require_admin alone
169
+ # decides, so a visitor gets its 404 rather than a redirect to sign in
170
+ # that shows the page exists (the skip is jobs_page's explicit option).
171
+ JOBS_PAGE_LINE = "jobs_page \"/admin/jobs\", before_action: :require_admin, skip_before_action: :require_authentication"
172
+ # jobs_page_plan's reason for a routes file that draws a jobs_page line
173
+ # of its own (`admin.jobs_page "/jobs", ...`, say) without the skip.
174
+ JOBS_PAGE_OWN_LINE = "it draws a jobs_page line of its own"
175
+ # The authentication block 0.4's generator inserted after CLASS_LINE
176
+ # (v0.4.0's and v0.4.1's application_controller_block, the same text
177
+ # in both), each line indented two spaces as it was inserted
178
+ # (indent). A re-run over a 0.4 application replaces it with
179
+ # `include Authentication`: as a diff to apply by hand, or with
180
+ # --force when the file holds it exactly.
181
+ LEGACY_APPLICATION_CONTROLLER_BLOCKS = [
182
+ <<~RUBY
183
+ # ---- Authentication (cybertrain generate authentication) -------------
184
+ # Every action needs a signed-in user unless its controller opens it:
185
+ # `allow_unauthenticated_access only: [:new, :create]`. resume_session
186
+ # sets @current_user (and @current_session), which templates can read.
187
+ before_action :resume_session
188
+ before_action :require_authentication
189
+
190
+ def self.allow_unauthenticated_access(only: [], except: [])
191
+ skip_before_action(:require_authentication, only: only, except: except)
192
+ end
193
+
194
+ # @return [Boolean] whether this request has a signed-in user
195
+ def authenticated?
196
+ !@current_user.nil?
197
+ end
198
+
199
+ # Loads the Session row the cookie names (and its user); a stale or
200
+ # expired id is dropped. Cookie Max-Age alone cannot stop replay:
201
+ # authentication expires session_absolute_max_age seconds after
202
+ # sign-in (SessionStore enforces the same on the cookie). A cookie
203
+ # whose password key no longer matches (the password changed since
204
+ # it signed in) ends its Session row.
205
+ def resume_session
206
+ @current_session = nil
207
+ @current_user = nil
208
+ id = session[:session_id]
209
+ return nil if id.nil? || id.empty? || id.size > 18
210
+
211
+ found = Session.find_by(id: id.to_i)
212
+ if found.nil?
213
+ session.delete(:session_id)
214
+ return nil
215
+ end
216
+ created_at = found.created_at
217
+ lifetime = Cybertrain.config.session_absolute_max_age
218
+ if created_at.nil? || (lifetime > 0 && created_at.to_i + lifetime <= Time.now.to_i)
219
+ session.delete(:session_id)
220
+ return nil
221
+ end
222
+ user = found.user
223
+ if user.nil? || !Cybertrain::Password.session_key_matches?(session[:password_key], user.password_digest)
224
+ found.destroy
225
+ session.delete(:session_id)
226
+ return nil
227
+ end
228
+ @current_session = found
229
+ @current_user = user
230
+ nil
231
+ end
232
+
233
+ # Sends a visitor to the sign-in page, remembering a GET to come back to.
234
+ def require_authentication
235
+ return nil if authenticated?
236
+
237
+ session[:return_to_after_authenticating] = request.path if request.method == "GET"
238
+ redirect_to new_session_path, status: :see_other
239
+ nil
240
+ end
241
+
242
+ # Also stores the password key resume_session compares, and restarts
243
+ # the cookie's absolute lifetime. After a password change, call
244
+ # `session[:password_key] = Cybertrain::Password.session_key(user.password_digest)`
245
+ # to keep the browser that changed it signed in.
246
+ def start_new_session_for(user)
247
+ started = Session.create(user_id: user.id, ip_address: request.client_ip,
248
+ user_agent: request.header("user-agent").to_s)
249
+ session.restart_lifetime!
250
+ session[:session_id] = started.id
251
+ session[:password_key] = Cybertrain::Password.session_key(user.password_digest)
252
+ @current_session = started
253
+ @current_user = user
254
+ nil
255
+ end
256
+
257
+ # Deletes the Session row and empties the cookie session (the CSRF
258
+ # token with it, so forms rendered before no longer submit).
259
+ def terminate_session
260
+ current = @current_session
261
+ current.destroy unless current.nil?
262
+ session.clear
263
+ @current_session = nil
264
+ @current_user = nil
265
+ nil
266
+ end
267
+
268
+ # Where to go after signing in: the page that asked for it, if it is a
269
+ # local path (Cybertrain::Controller#safe_redirect_path), or /.
270
+ def after_authentication_url
271
+ safe_redirect_path(session.delete(:return_to_after_authenticating), "/")
272
+ end
273
+ # ---- end of authentication ------------------------------------------
274
+
275
+ RUBY
276
+ ]
277
+ # The block's first and last lines, as inserted: where a diff finds an
278
+ # edited block.
279
+ LEGACY_BLOCK_START = " # ---- Authentication (cybertrain generate authentication) -------------\n"
280
+ LEGACY_BLOCK_END = " # ---- end of authentication ------------------------------------------\n"
281
+ # The columns the users and sessions migrations above create that an
282
+ # application generated before them may lack: table, column, and the
283
+ # rest of the add_column line. --confirmable's two are CONFIRMABLE_COLUMNS.
284
+ AUTHENTICATION_COLUMNS = [
285
+ ["users", "admin", ":boolean, null: false, default: \"false\""],
286
+ ["users", "failed_attempts", ":integer, null: false, default: \"0\""],
287
+ ["users", "locked_until", ":datetime"],
288
+ ["sessions", "remember", ":boolean, null: false, default: \"false\""],
289
+ ["sessions", "last_active_at", ":datetime"]
290
+ ]
291
+ CONFIRMABLE_COLUMNS = [
292
+ ["users", "confirmed_at", ":datetime"],
293
+ ["users", "unconfirmed_email", ":string"]
294
+ ]
295
+ # What heads each diff in GenerateResult#manual.
296
+ MANUAL_NOTE = "apply this diff by hand, or re-run with --force to overwrite the file"
297
+
298
+ # What generate_with_result did: the paths it created, the paths it
299
+ # overwrote (--force), the paths it deleted (--force: an earlier
300
+ # generator's test files, TEST_FILES_REPLACED) and the changes to make
301
+ # by hand, each a heading line (`manual <path>: ...`) and a unified
302
+ # diff (LineDiff.unified) that `patch -p1` applies: one per file it
303
+ # writes whole that exists with other content, and one each for
304
+ # ApplicationController and the jobs page's route of an application
305
+ # 0.4 generated; or, for an earlier generator's test file, the one
306
+ # line `manual <path>: replaced by <new path>; delete it`.
307
+ class GenerateResult
308
+ # @return [Array<String>] each one's path from the app's root
309
+ # (`manual`: each one's heading and diff)
310
+ attr_reader :created, :forced, :manual, :removed
311
+
312
+ def initialize(created, forced, manual, removed)
313
+ @created = created
314
+ @forced = forced
315
+ @manual = manual
316
+ @removed = removed
317
+ end
318
+ end
319
+
320
+ # The paths it created (generate_with_result's `created`).
321
+ def self.generate(root, invite_only = false, confirmable = false)
322
+ generate_with_result(root, invite_only, confirmable).created
323
+ end
68
324
 
69
- # Returns the paths it created. Raises InvalidArgument, before anything
70
- # is written, when `root` is not an application (no config/routes.rb
71
- # with the draw line, no app/controllers/application_controller.rb
72
- # with the class line; with `invite_only`, no bin/<app>.rb with the
73
- # Main.run line or no config/app.rb with the configure line).
74
- def self.generate(root, invite_only = false)
325
+ # Writes the files and makes the edits (with `confirmable`, those of
326
+ # --confirmable too). Raises InvalidArgument, before
327
+ # anything is written, when `root` is not an application (no
328
+ # config/routes.rb with the draw line, no
329
+ # app/controllers/application_controller.rb with the class line, no
330
+ # bin/<app>.rb with the Main.run line, no config/app.rb with the
331
+ # configure line).
332
+ #
333
+ # Run again over an application generated before (by 0.4, say, or
334
+ # without --confirmable), it writes the files that are missing, a
335
+ # `<v>_add_authentication_columns.rb` migration with the columns the
336
+ # existing migrations lack, and makes the marker edits. A file it
337
+ # writes whole that exists with other content is left alone and its
338
+ # diff put in `manual`, or, with `force`, overwritten (`forced`). The
339
+ # create_* migrations are never rewritten: they may have run.
340
+ def self.generate_with_result(root, invite_only = false, confirmable = false, force = false)
75
341
  routes_path = File.join(root, "config/routes.rb")
76
342
  raise InvalidArgument, "#{routes_path} not found: run this inside a cybertrain app" unless File.exist?(routes_path)
77
343
  raise InvalidArgument, "#{routes_path} has no `#{Scaffold::DRAW_LINE}` line" if File.read(routes_path).index(Scaffold::DRAW_LINE).nil?
@@ -80,55 +346,428 @@ module Cybertrain
80
346
  raise InvalidArgument, "#{controller_path} not found: run this inside a cybertrain app" unless File.exist?(controller_path)
81
347
  raise InvalidArgument, "#{controller_path} has no `#{CLASS_LINE}` line" if File.read(controller_path).index(CLASS_LINE).nil?
82
348
 
83
- app = ""
349
+ # Both modes require the user command from bin/<app>.rb.
350
+ app = Build.app_name(root)
351
+ raise InvalidArgument, "#{root}/spin.toml has no [package] name: run this inside a cybertrain app" if app == ""
352
+
353
+ bin_path = File.join(root, "bin/#{app}.rb")
354
+ raise InvalidArgument, "#{bin_path} not found: run this inside a cybertrain app" unless File.exist?(bin_path)
355
+ raise InvalidArgument, "#{bin_path} has no line starting with `#{MAIN_RUN_LINE}`" if line_start(File.read(bin_path), MAIN_RUN_LINE) < 0
356
+
357
+ # Both modes declare the base_url setting in config/app.rb.
358
+ config_path = File.join(root, "config/app.rb")
359
+ raise InvalidArgument, "#{config_path} not found: run this inside a cybertrain app" unless File.exist?(config_path)
360
+ raise InvalidArgument, "#{config_path} has no `#{CONFIGURE_LINE}` line" if File.read(config_path).index(CONFIGURE_LINE).nil?
361
+
362
+ result = GenerateResult.new(Array.new(0) { "" }, Array.new(0) { "" }, Array.new(0) { "" }, Array.new(0) { "" })
363
+ record_migration(result, root, migration_path(root, "users"), users_migration(confirmable))
364
+ record_migration(result, root, migration_path(root, "sessions"), sessions_migration)
365
+ add_columns = add_columns_migration(root, confirmable)
366
+ record_migration(result, root, add_columns_path(root), add_columns) unless add_columns.empty?
367
+ # Until these two are changed, they do not ask for a confirmation: the
368
+ # concern's start_new_session_for still refuses an unconfirmed account
369
+ # (so neither signs one in), but the user is not told why, and a
370
+ # sign-up gets no link. Their diffs say so first.
371
+ unconfirmed_sign_in = confirmable ? "until this diff is applied, an unconfirmed account's right password is refused without its message (the concern refuses it)" : ""
372
+ unconfirmed_sign_up = confirmable ? "until this diff is applied, a sign-up is mailed no confirmation link (the concern signs it in no more)" : ""
373
+ # An application generated before without --confirmable already has
374
+ # the concern: its confirmation check, the backstop the two warnings
375
+ # above lean on, then arrives only as this diff.
376
+ unconfirmed_concern = confirmable ? "this diff holds the check that refuses an unconfirmed account a session; until it is applied, unconfirmed accounts sign in (whatever the other diffs say)" : ""
377
+ unconfirmed_setup = confirmable ? "until this diff is applied, the first user /setup creates is not confirmed and cannot sign in (a password reset confirms it)" : ""
378
+ record_file(result, root, "app/models/user.rb", user_model(app, confirmable), force)
379
+ record_file(result, root, "app/models/session.rb", session_model, force)
380
+ record_file(result, root, "app/controllers/concerns/authentication.rb", authentication_concern(app, confirmable), force, unconfirmed_concern)
381
+ record_file(result, root, "app/controllers/sessions_controller.rb", sessions_controller(confirmable), force, unconfirmed_sign_in)
84
382
  if invite_only
85
- app = Build.app_name(root)
86
- raise InvalidArgument, "#{root}/spin.toml has no [package] name: run this inside a cybertrain app" if app == ""
87
-
88
- bin_path = File.join(root, "bin/#{app}.rb")
89
- raise InvalidArgument, "#{bin_path} not found: run this inside a cybertrain app" unless File.exist?(bin_path)
90
- raise InvalidArgument, "#{bin_path} has no line starting with `#{MAIN_RUN_LINE}`" if line_start(File.read(bin_path), MAIN_RUN_LINE) < 0
91
-
92
- config_path = File.join(root, "config/app.rb")
93
- raise InvalidArgument, "#{config_path} not found: run this inside a cybertrain app" unless File.exist?(config_path)
94
- raise InvalidArgument, "#{config_path} has no `#{CONFIGURE_LINE}` line" if File.read(config_path).index(CONFIGURE_LINE).nil?
383
+ record_file(result, root, "app/controllers/setup_controller.rb", setup_controller(app, confirmable), force, unconfirmed_setup)
384
+ else
385
+ record_file(result, root, "app/controllers/registrations_controller.rb", registrations_controller(confirmable), force, unconfirmed_sign_up)
95
386
  end
96
-
97
- created = Array.new(0) { "" }
98
- users = migration_path(root, "users")
99
- record(created, root, users, users_migration)
100
- record(created, root, migration_path(root, "sessions"), sessions_migration)
101
- record(created, root, "app/models/user.rb", user_model)
102
- record(created, root, "app/models/session.rb", session_model)
103
- record(created, root, "app/controllers/sessions_controller.rb", sessions_controller)
387
+ record_file(result, root, "app/controllers/passwords_controller.rb", passwords_controller(confirmable), force)
388
+ record_file(result, root, "app/controllers/confirmations_controller.rb", confirmations_controller, force) if confirmable
389
+ record_file(result, root, "app/controllers/accounts_controller.rb", accounts_controller(confirmable), force)
390
+ record_file(result, root, "app/mailers/passwords_mailer.rb", passwords_mailer, force)
391
+ record_file(result, root, "app/mailers/confirmations_mailer.rb", confirmations_mailer, force) if confirmable
392
+ record_file(result, root, "app/commands/user_command.rb", user_command(app, invite_only, confirmable), force)
393
+ record_file(result, root, "app/views/sessions/new.html.erb", sessions_new_view(invite_only, confirmable), force)
394
+ record_file(result, root, "app/views/sessions/_nav.html.erb", nav_partial, force)
104
395
  if invite_only
105
- record(created, root, "app/controllers/setup_controller.rb", setup_controller(app))
106
- record(created, root, "app/commands/user_command.rb", user_command(app))
396
+ record_file(result, root, "app/views/setup/new.html.erb", setup_new_view, force)
107
397
  else
108
- record(created, root, "app/controllers/registrations_controller.rb", registrations_controller)
398
+ record_file(result, root, "app/views/registrations/new.html.erb", registrations_new_view, force)
399
+ end
400
+ record_file(result, root, "app/views/passwords/new.html.erb", passwords_new_view, force)
401
+ record_file(result, root, "app/views/passwords/edit.html.erb", passwords_edit_view, force)
402
+ record_file(result, root, "app/views/mail/_password_reset.html.erb", password_reset_mail_view, force)
403
+ if confirmable
404
+ record_file(result, root, "app/views/confirmations/new.html.erb", confirmations_new_view, force)
405
+ record_file(result, root, "app/views/mail/_confirmation.html.erb", confirmation_mail_view, force)
109
406
  end
110
- record(created, root, "app/views/sessions/new.html.erb", sessions_new_view(invite_only))
111
- record(created, root, "app/views/sessions/_nav.html.erb", nav_partial)
407
+ record_file(result, root, "app/views/accounts/edit.html.erb", accounts_edit_view(confirmable), force)
408
+ record_file(result, root, "test/fixtures/users.yml", users_fixture(confirmable), force)
409
+ record_file(result, root, Templates::SESSION_TEST_HELPER, session_test_helper, force)
410
+ record_file(result, root, "test/models/user_test.rb", user_model_test, force)
411
+ record_file(result, root, "test/controllers/sessions_controller_test.rb", sessions_controller_test(invite_only), force)
112
412
  if invite_only
113
- record(created, root, "app/views/setup/new.html.erb", setup_new_view)
413
+ record_file(result, root, "test/integration/first_run_test.rb", first_run_test(app), force)
114
414
  else
115
- record(created, root, "app/views/registrations/new.html.erb", registrations_new_view)
415
+ record_file(result, root, "test/controllers/registrations_controller_test.rb", registrations_controller_test(confirmable), force)
416
+ end
417
+ record_file(result, root, "test/controllers/passwords_controller_test.rb", passwords_controller_test(app), force)
418
+ record_file(result, root, "test/controllers/accounts_controller_test.rb", accounts_controller_test(confirmable), force)
419
+ record_file(result, root, "test/controllers/confirmations_controller_test.rb", confirmations_controller_test(app, invite_only), force) if confirmable
420
+ record_file(result, root, "test/integration/remember_me_test.rb", remember_me_integration_test, force)
421
+ record_file(result, root, "test/integration/lockout_test.rb", lockout_integration_test, force)
422
+ record_file(result, root, "test/integration/admin_test.rb", admin_integration_test(app), force)
423
+ record_replaced_tests(result, root, force)
424
+ legacy = legacy_application_controller?(File.read(controller_path))
425
+ if legacy
426
+ upgrade_application_controller(result, controller_path, force)
427
+ else
428
+ add_to_application_controller(controller_path)
429
+ end
430
+ add_routes(routes_path, invite_only, confirmable)
431
+ if legacy
432
+ upgrade_jobs_page(result, routes_path, controller_path)
433
+ else
434
+ enable_jobs_page(routes_path, controller_path)
116
435
  end
117
- record(created, root, "test/support/app_test.rb", app_test_support)
118
- record(created, root, "test/authentication.rb", invite_only ? invite_only_test(app) : authentication_test)
119
- add_to_application_controller(controller_path)
120
- add_routes(routes_path, invite_only)
121
436
  add_nav_to_layout(File.join(root, "app/views/layouts/application.html.erb"))
437
+ add_session_helper(result, root)
122
438
  add_sign_in_to_attachment_tests(root)
123
- if invite_only
124
- add_command_to_bin(File.join(root, "bin/#{app}.rb"), app)
125
- add_setting_to_config(File.join(root, "config/app.rb"), app)
439
+ add_sign_in_to_controller_tests(root)
440
+ add_command_to_bin(bin_path, app, invite_only)
441
+ add_setting_to_config(config_path, app, invite_only)
442
+ result
443
+ end
444
+
445
+ # Writes a file the generator writes whole (Templates.write: create,
446
+ # or identical). One that exists with other content is left alone
447
+ # and answered "manual", or, with `force`, overwritten and answered
448
+ # "force".
449
+ # @return [String] "create", "identical", "manual" or "force"
450
+ def self.write_or_diff(root, path, content, force)
451
+ full = File.join(root, path)
452
+ return Templates.write(root, path, content) unless File.exist?(full)
453
+
454
+ if LineDiff.as_utf8(File.read(full)) == content
455
+ puts "identical #{path}"
456
+ return "identical"
457
+ end
458
+
459
+ if force
460
+ File.write(full, content)
461
+ puts "force #{path}"
462
+ return "force"
463
+ end
464
+ puts "manual #{path} (diff below)"
465
+ "manual"
466
+ end
467
+
468
+ # write_or_diff, and what it did put into result; `warning`, when
469
+ # given, is a second heading line above the diff.
470
+ def self.record_file(result, root, path, content, force = false, warning = "")
471
+ status = write_or_diff(root, path, content, force)
472
+ if status == "create"
473
+ result.created << path
474
+ elsif status == "force"
475
+ result.forced << path
476
+ elsif status == "manual"
477
+ result.manual << manual_change(path, File.read(File.join(root, path)), content, MANUAL_NOTE, warning)
478
+ end
479
+ nil
480
+ end
481
+
482
+ # A migration is written once and never rewritten (it may have run):
483
+ # one that exists with other content is left as it is (Templates.write
484
+ # says "exist"), and the columns it lacks go into the add-columns
485
+ # migration.
486
+ def self.record_migration(result, root, path, content)
487
+ result.created << path if Templates.write(root, path, content) == "create"
488
+ nil
489
+ end
490
+
491
+ # GenerateResult#manual's entry: the heading, the warning line if
492
+ # any, and the diff from old_text to new_text.
493
+ def self.manual_change(path, old_text, new_text, note, warning = "")
494
+ out = +""
495
+ out << "manual #{path}: #{note}\n"
496
+ out << "IMPORTANT: #{warning}\n" unless warning.empty?
497
+ out << LineDiff.unified(path, old_text, new_text)
498
+ out
499
+ end
500
+
501
+ # The add_column lines (each indented for the migration's change, and
502
+ # with its newline) of the columns this generator's migrations create
503
+ # that db/schema.rb and db/migrate/*.rb do not have; with
504
+ # `confirmable`, --confirmable's two too.
505
+ def self.missing_column_lines(root, confirmable)
506
+ out = Array.new(0) { "" }
507
+ AUTHENTICATION_COLUMNS.each do |col|
508
+ out << " add_column \"#{col[0]}\", \"#{col[1]}\", #{col[2]}\n" unless column_present?(root, col[0], col[1])
509
+ end
510
+ if confirmable
511
+ CONFIRMABLE_COLUMNS.each do |col|
512
+ out << " add_column \"#{col[0]}\", \"#{col[1]}\", #{col[2]}\n" unless column_present?(root, col[0], col[1])
513
+ end
514
+ end
515
+ out
516
+ end
517
+
518
+ # The migration that adds the missing columns (missing_column_lines),
519
+ # or "" when none is missing. When it adds users.confirmed_at, the
520
+ # users already there count as confirmed (since they were created):
521
+ # they signed up when nobody was asked to confirm, and would
522
+ # otherwise never sign in again.
523
+ def self.add_columns_migration(root, confirmable)
524
+ lines = missing_column_lines(root, confirmable)
525
+ return "" if lines.empty?
526
+
527
+ name = File.basename(add_columns_path(root), ".rb")
528
+ name = name[Scaffold.leading_digits(name).size + 1, name.size].to_s
529
+ out = +""
530
+ out << "# The columns `cybertrain generate authentication` reads that the\n"
531
+ out << "# migrations before this one did not create.\n"
532
+ out << "class #{Inflector.camelize(name)} < Cybertrain::Migration::Base\n"
533
+ out << " def change\n"
534
+ lines.each { |line| out << line }
535
+ if confirmable && !column_present?(root, "users", "confirmed_at")
536
+ out << " # The users already here signed up when nobody was asked to\n"
537
+ out << " # confirm an address: they count as confirmed since they were\n"
538
+ out << " # created, or none of them could sign in again.\n"
539
+ out << " reversible do |dir|\n"
540
+ out << " dir.up { execute \"UPDATE users SET confirmed_at = COALESCE(created_at, strftime('%Y-%m-%d %H:%M:%S.000000', 'now')) WHERE confirmed_at IS NULL\" }\n"
541
+ out << " end\n"
542
+ end
543
+ out << " end\n"
544
+ out << "end\n"
545
+ out
546
+ end
547
+
548
+ # db/migrate/<version>_add_authentication_columns.rb; when one is
549
+ # there already (an earlier upgrade), the next free name of
550
+ # ..._add_authentication_columns_2.rb, _3 and so on.
551
+ def self.add_columns_path(root)
552
+ base = "add_authentication_columns"
553
+ name = base
554
+ n = 1
555
+ until Dir.glob(File.join(root, "db/migrate/*_#{name}.rb")).empty?
556
+ n += 1
557
+ name = "#{base}_#{n}"
558
+ end
559
+ "db/migrate/#{Scaffold.next_version(root, Scaffold.timestamp)}_#{name}.rb"
560
+ end
561
+
562
+ # Whether db/schema.rb or a migration in db/migrate has `column` in
563
+ # `table` (declares_column?).
564
+ def self.column_present?(root, table, column)
565
+ sources = Dir.glob(File.join(root, "db/migrate/*.rb")).sort
566
+ schema = File.join(root, "db/schema.rb")
567
+ sources << schema if File.exist?(schema)
568
+ sources.each do |path|
569
+ return true if declares_column?(File.read(path), table, column)
570
+ end
571
+ false
572
+ end
573
+
574
+ # Whether source declares `column` of `table`: a `t.<type> "<column>"`
575
+ # line (its first argument; a symbol too) inside a `create_table
576
+ # "<table>"` block (the schema dump's `s.create_table` too), or an
577
+ # `add_column "<table>", "<column>"` line (symbols too). Each name
578
+ # must end where the line says it does (`:admin_notes` is not
579
+ # `admin`, `:users_archive` not `users`), and comment lines are
580
+ # skipped. Not read: remove_column and change_table (a column they
581
+ # remove still counts, and one they add does not, so db migrate
582
+ # then refuses the duplicate add_column, loudly).
583
+ def self.declares_column?(source, table, column)
584
+ heads = ["create_table \"#{table}\"", "create_table :#{table}", "s.create_table \"#{table}\""]
585
+ names = ["\"#{column}\"", ":#{column}"]
586
+ adds = Array.new(0) { "" }
587
+ ["\"#{table}\"", ":#{table}"].each { |t| names.each { |n| adds << "add_column #{t}, #{n}" } }
588
+ inside = false
589
+ source.each_line do |raw|
590
+ code = raw.strip
591
+ next if code.start_with?("#")
592
+
593
+ if heads.any? { |head| word_prefix?(code, head) }
594
+ inside = true
595
+ elsif inside && code == "end"
596
+ inside = false
597
+ elsif inside && code.start_with?("t.")
598
+ space = code.index(" ")
599
+ first = space.nil? ? "" : code[space + 1, code.size - space - 1].to_s.strip
600
+ return true if names.any? { |name| word_prefix?(first, name) }
601
+ elsif adds.any? { |add| word_prefix?(code, add) }
602
+ return true
603
+ end
604
+ end
605
+ false
606
+ end
607
+
608
+ # Whether text starts with prefix and the name there ends with it: the
609
+ # next character, if any, is not a letter, a digit or `_`.
610
+ def self.word_prefix?(text, prefix)
611
+ return false unless text.start_with?(prefix)
612
+ return true if text.size == prefix.size
613
+
614
+ b = text.getbyte(prefix.bytesize).to_i
615
+ !((b >= 97 && b <= 122) || (b >= 65 && b <= 90) || (b >= 48 && b <= 57) || b == 95)
616
+ end
617
+
618
+ # Whether source holds 0.4's authentication block (its first line)
619
+ # and no include: what generate_with_result upgrades rather than
620
+ # inserts into.
621
+ def self.legacy_application_controller?(source)
622
+ !source.index(LEGACY_BLOCK_START).nil? && !Authentication.included?(source)
623
+ end
624
+
625
+ # 0.4's ApplicationController with its authentication block (from
626
+ # LEGACY_BLOCK_START to LEGACY_BLOCK_END and the blank line after it)
627
+ # replaced by `include Authentication`. With `force` and the block as
628
+ # 0.4 wrote it (LEGACY_APPLICATION_CONTROLLER_BLOCKS), the file is
629
+ # changed; otherwise the change goes into result.manual. A block
630
+ # whose end line is gone is left alone with a note.
631
+ def self.upgrade_application_controller(result, path, force)
632
+ name = "app/controllers/application_controller.rb"
633
+ source = File.read(path)
634
+ start = source.index(LEGACY_BLOCK_START).to_i
635
+ unless source.index(LEGACY_BLOCK_START, start + LEGACY_BLOCK_START.size).nil?
636
+ puts "skip #{name} (0.4's authentication block is there more than once): " \
637
+ "replace each with one `#{INCLUDE_LINE}` (app/controllers/concerns/authentication.rb)"
638
+ return nil
639
+ end
640
+ last = source.index(LEGACY_BLOCK_END, start)
641
+ if last.nil?
642
+ puts "skip #{name} (0.4's authentication block has no end line): " \
643
+ "replace that code with `#{INCLUDE_LINE}` (app/controllers/concerns/authentication.rb)"
644
+ return nil
645
+ end
646
+
647
+ stop = last + LEGACY_BLOCK_END.size
648
+ stop += 1 if source[stop, 1] == "\n"
649
+ block = source[start, stop - start].to_s
650
+ updated = +""
651
+ updated << source[0, start].to_s << " #{INCLUDE_LINE}\n\n" << source[stop, source.size - stop].to_s
652
+ exact = LEGACY_APPLICATION_CONTROLLER_BLOCKS.any? { |legacy| indent(legacy) == block }
653
+ warn_own_require_admin(updated)
654
+ if force && exact
655
+ File.write(path, updated)
656
+ puts "force #{name} (0.4's authentication block replaced by #{INCLUDE_LINE})"
657
+ result.forced << name
658
+ return nil
659
+ end
660
+
661
+ note = exact ? MANUAL_NOTE : "apply this diff by hand (0.4's authentication block was edited, so --force leaves it alone)"
662
+ puts "manual #{name} (diff below)"
663
+ result.manual << manual_change(name, source, updated, note)
664
+ nil
665
+ end
666
+
667
+ # The jobs page of an application 0.4 generated (jobs_page_plan,
668
+ # which adds the line where 0.4's `cybertrain new` wrote no comment
669
+ # of it): drawn once ApplicationController includes the concern,
670
+ # else its diff into result.manual, to apply with
671
+ # application_controller.rb's.
672
+ def self.upgrade_jobs_page(result, routes_path, controller_path)
673
+ source = File.read(routes_path)
674
+ plan = jobs_page_plan(source, true, jobs_page_line(File.read(controller_path)))
675
+ updated = plan[0]
676
+ if updated.empty?
677
+ report_jobs_page_skip(plan[1])
678
+ return nil
679
+ end
680
+
681
+ if Authentication.included?(File.read(controller_path))
682
+ File.write(routes_path, updated)
683
+ puts "route #{jobs_page_line(File.read(controller_path))}"
684
+ return nil
685
+ end
686
+
687
+ puts "manual config/routes.rb (diff below)"
688
+ result.manual << manual_change("config/routes.rb", source, updated,
689
+ "apply this diff by hand with application_controller.rb's (require_admin comes with #{INCLUDE_LINE})")
690
+ nil
691
+ end
692
+
693
+ # The jobs page's line for this ApplicationController source:
694
+ # JOBS_PAGE_LINE, which skips require_authentication so that a visitor
695
+ # gets the concern's require_admin's 404; NEW_APP_JOBS_PAGE_LINE (no
696
+ # skip) when the controller defines its own require_admin, which may
697
+ # count on require_authentication having run.
698
+ def self.jobs_page_line(controller_source)
699
+ Authentication.own_require_admin?(controller_source) ? NEW_APP_JOBS_PAGE_LINE : JOBS_PAGE_LINE
700
+ end
701
+
702
+ # What to do with the jobs page's route, as [routes, reason]: routes
703
+ # is source with the jobs page drawn as `line` (JOBS_PAGE_LINE unless
704
+ # given) in place of the comment `cybertrain new` writes (or
705
+ # JOBS_PAGE_LINE commented out), or, with `add_missing` and no
706
+ # `jobs_page` anywhere in source, as the last line of the
707
+ # Cybertrain::Routes.draw block (before the `end` at the draw line's
708
+ # own indentation). When there is nothing to do, routes is "" and
709
+ # reason says why: "drawn" (JOBS_PAGE_LINE is there), "drawn " and the
710
+ # line (`line`, or a jobs_page line of the application's own that
711
+ # already skips require_authentication), JOBS_PAGE_OWN_LINE (one of
712
+ # its own without the skip), or the words report_jobs_page_skip prints.
713
+ def self.jobs_page_plan(source, add_missing, line = JOBS_PAGE_LINE)
714
+ comments = ["# #{NEW_APP_JOBS_PAGE_LINE}", "# #{JOBS_PAGE_LINE}"]
715
+ updated = +""
716
+ found = false
717
+ drawn = false
718
+ drawn_line = ""
719
+ own = false
720
+ source.each_line do |text|
721
+ code = text.strip
722
+ drawn = true if code == JOBS_PAGE_LINE
723
+ if !code.start_with?("#") && !code.index("jobs_page ").nil?
724
+ own = true
725
+ # The line to draw (without the skip), or one of the application's
726
+ # own that already skips require_authentication: nothing to do.
727
+ drawn_line = code if code == line || !code.index("skip_before_action: :require_authentication").nil?
728
+ end
729
+ if !found && comments.include?(code)
730
+ found = true
731
+ updated << text[0, text.index(code).to_i].to_s << line << "\n"
732
+ else
733
+ updated << text
734
+ end
126
735
  end
127
- created
736
+ return [updated.to_s, ""] if found
737
+ return ["", "drawn"] if drawn
738
+ return ["", "drawn #{drawn_line}"] unless drawn_line.empty?
739
+ return ["", JOBS_PAGE_OWN_LINE] if own
740
+ return ["", "it has a jobs_page line of its own"] unless source.index("jobs_page").nil?
741
+ return ["", "no `# #{NEW_APP_JOBS_PAGE_LINE}` comment to draw"] unless add_missing
742
+
743
+ draw = source.index(Scaffold::DRAW_LINE).to_i
744
+ start = line_start_before(source, draw)
745
+ pad = source[start, draw - start].to_s
746
+ return ["", "its draw line is not at the start of a line"] unless pad.strip.empty?
747
+
748
+ at = source.index("\n#{pad}end\n", draw)
749
+ at = source.index("\n#{pad}end", draw) if at.nil? && source.end_with?("\n#{pad}end")
750
+ return ["", "no `end` of the Cybertrain::Routes.draw block at its indentation"] if at.nil?
751
+
752
+ out = +""
753
+ out << source[0, at + 1].to_s << "#{pad} #{line}\n" << source[at + 1, source.size - at - 1].to_s
754
+ [out.to_s, ""]
128
755
  end
129
756
 
130
- def self.record(created, root, path, content)
131
- created << path if Templates.write(root, path, content) == "create"
757
+ # Says why config/routes.rb gets no jobs page line (jobs_page_plan's
758
+ # reason).
759
+ def self.report_jobs_page_skip(reason)
760
+ if reason == "drawn"
761
+ puts "identical config/routes.rb (#{JOBS_PAGE_LINE})"
762
+ elsif reason.start_with?("drawn ")
763
+ puts "identical config/routes.rb (#{reason[6, reason.size - 6]})"
764
+ elsif reason == JOBS_PAGE_OWN_LINE
765
+ puts "skip config/routes.rb (#{reason}): add `skip_before_action: :require_authentication` to that line " \
766
+ "so that a visitor gets require_admin's 404"
767
+ else
768
+ puts "skip config/routes.rb (#{reason}): to show the jobs page to admins, add " \
769
+ "`#{JOBS_PAGE_LINE}` inside Cybertrain::Routes.draw"
770
+ end
132
771
  nil
133
772
  end
134
773
 
@@ -142,39 +781,152 @@ module Cybertrain
142
781
  "db/migrate/#{Scaffold.next_version(root, Scaffold.timestamp)}#{suffix}"
143
782
  end
144
783
 
145
- # Inserts the authentication block right after the class line, once
146
- # (the block's own `def require_authentication` marks a file that has
147
- # it). Returns true when the file was changed.
784
+ # Whether source has an `include Authentication` line (a trailing
785
+ # comment allowed): not a commented-out one, and not
786
+ # `include AuthenticationHelpers` or `include Authentication::X`.
787
+ def self.included?(source)
788
+ source.each_line do |line|
789
+ return true if Authentication.include_line?(line)
790
+ end
791
+ false
792
+ end
793
+
794
+ # Whether this one line is such an include (Attachment reads the
795
+ # concern's callbacks in its place).
796
+ def self.include_line?(line)
797
+ code = line.strip
798
+ code == INCLUDE_LINE || code.start_with?("#{INCLUDE_LINE} #")
799
+ end
800
+
801
+ # Inserts `include Authentication` right after the class line, once. A
802
+ # controller that defines require_authentication itself (0.4's
803
+ # generator put the whole block there) is left alone: including the
804
+ # concern on top of it would run every callback twice. Returns true
805
+ # when the file was changed.
148
806
  def self.add_to_application_controller(path)
149
807
  source = File.read(path)
808
+ if Authentication.included?(source)
809
+ puts "identical app/controllers/application_controller.rb (#{INCLUDE_LINE})"
810
+ return false
811
+ end
150
812
  unless source.index("def require_authentication").nil?
151
- puts "identical app/controllers/application_controller.rb (authentication already added)"
813
+ puts "skip app/controllers/application_controller.rb (it defines require_authentication itself): " \
814
+ "replace that code with `#{INCLUDE_LINE}` (app/controllers/concerns/authentication.rb)"
815
+ return false
816
+ end
817
+
818
+ File.write(path, insert_after_line(source, CLASS_LINE, " #{INCLUDE_LINE}\n\n"))
819
+ puts "insert app/controllers/application_controller.rb (#{INCLUDE_LINE})"
820
+ warn_own_require_admin(source)
821
+ true
822
+ end
823
+
824
+ # Whether source (an ApplicationController) defines require_admin
825
+ # itself, which then takes the place of the concern's in every
826
+ # controller.
827
+ def self.own_require_admin?(source)
828
+ source.each_line do |line|
829
+ code = line.strip
830
+ return true if code == "def require_admin" || code.start_with?("def require_admin ") || code.start_with?("def require_admin(")
831
+ end
832
+ false
833
+ end
834
+
835
+ # Says so when ApplicationController defines its own require_admin.
836
+ def self.warn_own_require_admin(source)
837
+ return nil unless Authentication.own_require_admin?(source)
838
+
839
+ puts "warn app/controllers/application_controller.rb defines require_admin itself: it takes the place of " \
840
+ "the Authentication concern's in every controller (delete it to use the concern's)"
841
+ nil
842
+ end
843
+
844
+ # Draws the jobs page `cybertrain new` left as a comment (a line that
845
+ # is `# jobs_page "/admin/jobs", before_action: :require_admin`, or
846
+ # already JOBS_PAGE_LINE commented out) as JOBS_PAGE_LINE, once
847
+ # ApplicationController includes the concern that defines
848
+ # require_admin. Any other routes file is left as it is. Returns true
849
+ # when the file was changed.
850
+ def self.enable_jobs_page(routes_path, controller_path)
851
+ line = jobs_page_line(File.read(controller_path))
852
+ plan = jobs_page_plan(File.read(routes_path), false, line)
853
+ updated = plan[0]
854
+ if updated.empty?
855
+ report_jobs_page_skip(plan[1])
856
+ return false
857
+ end
858
+
859
+ unless Authentication.included?(File.read(controller_path))
860
+ puts "skip config/routes.rb (the jobs page): ApplicationController has no require_admin until it includes Authentication"
152
861
  return false
153
862
  end
154
863
 
155
- File.write(path, insert_after_line(source, CLASS_LINE, indent(application_controller_block)))
156
- puts "insert app/controllers/application_controller.rb (authentication)"
864
+ File.write(routes_path, updated)
865
+ puts "route #{line}"
157
866
  true
158
867
  end
159
868
 
160
- # Inserts the sign-in and sign-up (or setup) routes after the draw
161
- # line, once.
162
- def self.add_routes(path, invite_only = false)
869
+ # Inserts the sign-in, password reset, (--confirmable) confirmation,
870
+ # account and sign-up (or setup) routes after the draw line, once.
871
+ # Routes that have the sign-in but not the reset, the confirmations or
872
+ # the account page (an app generated before them) get the reset's
873
+ # line right after the sign-in's, and the account's and then the
874
+ # confirmations' right after the reset's, each indented as the line
875
+ # before it is.
876
+ def self.add_routes(path, invite_only = false, confirmable = false)
163
877
  source = File.read(path)
164
- unless source.index(ROUTE_MARK).nil?
165
- puts "identical route #{ROUTE_MARK}"
878
+ confirmations = confirmable ? "#{CONFIRMATIONS_ROUTE_MARK}, " : ""
879
+ if source.index(ROUTE_MARK).nil?
880
+ File.write(path, insert_after_line(source, Scaffold::DRAW_LINE, indent(routes_block(invite_only, confirmable))))
881
+ puts "route #{ROUTE_MARK}, #{PASSWORDS_ROUTE_MARK}, #{confirmations}#{ACCOUNT_ROUTE_MARK}, get/post #{invite_only ? "/setup" : "/sign_up"}"
882
+ return true
883
+ end
884
+ added = Array.new(0) { "" }
885
+ if source.index(PASSWORDS_ROUTE_MARK).nil?
886
+ source = insert_route_after(source, ROUTE_MARK, PASSWORDS_ROUTE)
887
+ added << PASSWORDS_ROUTE_MARK
888
+ end
889
+ if source.index(ACCOUNT_ROUTE_MARK).nil?
890
+ source = insert_route_after(source, PASSWORDS_ROUTE_MARK, ACCOUNT_ROUTE)
891
+ added << ACCOUNT_ROUTE_MARK
892
+ end
893
+ if confirmable && source.index(CONFIRMATIONS_ROUTE_MARK).nil?
894
+ source = insert_route_after(source, PASSWORDS_ROUTE_MARK, CONFIRMATIONS_ROUTE)
895
+ added << CONFIRMATIONS_ROUTE_MARK
896
+ end
897
+ if confirmable && source.index(PENDING_EMAIL_ROUTE_MARK).nil?
898
+ source = insert_route_after(source, ACCOUNT_ROUTE_MARK, PENDING_EMAIL_ROUTE)
899
+ added << "delete #{PENDING_EMAIL_ROUTE_MARK}"
900
+ end
901
+ if added.empty?
902
+ puts "identical route #{ROUTE_MARK}, #{PASSWORDS_ROUTE_MARK}, #{confirmations}#{ACCOUNT_ROUTE_MARK}"
166
903
  return false
167
904
  end
168
905
 
169
- File.write(path, insert_after_line(source, Scaffold::DRAW_LINE, indent(routes_block(invite_only))))
170
- puts "route #{ROUTE_MARK}, get/post #{invite_only ? "/setup" : "/sign_up"}"
906
+ File.write(path, source)
907
+ puts "route #{added.join(", ")}"
171
908
  true
172
909
  end
173
910
 
174
- # --invite-only: requires app/commands/user_command.rb (which registers
175
- # the `user` command) and runs its boot warning, just before the
176
- # Main.run line of bin/<app>.rb, once.
177
- def self.add_command_to_bin(path, app)
911
+ # source with route on a line of its own right after the first line
912
+ # that holds mark, indented as that line is.
913
+ def self.insert_route_after(source, mark, route)
914
+ at = source.index(mark).to_i
915
+ start = line_start_before(source, at)
916
+ margin = source[start, at - start].to_s
917
+ insert_after_line(source, mark, "#{margin}#{route}\n")
918
+ end
919
+
920
+ # Where the line holding offset `at` of source starts.
921
+ def self.line_start_before(source, at)
922
+ found = at > 0 ? source.rindex("\n", at - 1) : nil
923
+ found.nil? ? 0 : found + 1
924
+ end
925
+
926
+ # Requires app/commands/user_command.rb (which registers the `user`
927
+ # command) and, with --invite-only, runs its boot warning, just before
928
+ # the Main.run line of bin/<app>.rb, once.
929
+ def self.add_command_to_bin(path, app, invite_only = false)
178
930
  name = "bin/#{app}.rb"
179
931
  source = File.read(path)
180
932
  unless source.index(COMMAND_REQUIRE).nil?
@@ -182,24 +934,35 @@ module Cybertrain
182
934
  return false
183
935
  end
184
936
 
185
- File.write(path, insert_before_line(source, MAIN_RUN_LINE, bin_block(app)))
186
- puts "insert #{name} (./#{app} user, the first-run warning)"
937
+ File.write(path, insert_before_line(source, MAIN_RUN_LINE, bin_block(app, invite_only)))
938
+ puts invite_only ? "insert #{name} (./#{app} user, the first-run warning)" : "insert #{name} (./#{app} user)"
187
939
  true
188
940
  end
189
941
 
190
- # --invite-only: declares the setup_open setting at the top of
191
- # config/app.rb's configure block, once.
192
- def self.add_setting_to_config(path, app)
942
+ # Declares the base_url setting (both modes) and, with --invite-only,
943
+ # the setup_open setting above it, at the top of config/app.rb's
944
+ # configure block, each once. Returns true when the file was changed.
945
+ def self.add_setting_to_config(path, app, invite_only = false)
193
946
  source = File.read(path)
194
- unless source.index("setting_bool :setup_open").nil?
195
- puts "identical config/app.rb (setup_open already declared)"
196
- return false
947
+ changed = false
948
+ if source.index("setting_string :base_url").nil?
949
+ source = insert_after_line(source, CONFIGURE_LINE, indent(base_url_block(app)))
950
+ puts "insert config/app.rb (#{base_url_env(app)})"
951
+ changed = true
952
+ else
953
+ puts "identical config/app.rb (base_url already declared)"
197
954
  end
198
-
199
- File.write(path, insert_after_line(source, CONFIGURE_LINE, indent(config_block(app))))
200
- env = setup_env(app)
201
- puts "insert config/app.rb (#{env})"
202
- true
955
+ if invite_only
956
+ if source.index("setting_bool :setup_open").nil?
957
+ source = insert_after_line(source, CONFIGURE_LINE, indent(config_block(app)))
958
+ puts "insert config/app.rb (#{setup_env(app)})"
959
+ changed = true
960
+ else
961
+ puts "identical config/app.rb (setup_open already declared)"
962
+ end
963
+ end
964
+ File.write(path, source) if changed
965
+ changed
203
966
  end
204
967
 
205
968
  # The environment variable that opens /setup to any address:
@@ -208,6 +971,12 @@ module Cybertrain
208
971
  "#{app.upcase}_SETUP_OPEN"
209
972
  end
210
973
 
974
+ # The environment variable of the base_url setting, which links in
975
+ # mails start with: SHOP_BASE_URL for the app shop.
976
+ def self.base_url_env(app)
977
+ "#{app.upcase}_BASE_URL"
978
+ end
979
+
211
980
  # Renders the nav partial at the top of <main> in the layout, once;
212
981
  # a layout without a `<main>` line is left alone with a note.
213
982
  def self.add_nav_to_layout(path)
@@ -232,28 +1001,45 @@ module Cybertrain
232
1001
  true
233
1002
  end
234
1003
 
235
- # A test/attachment_*.rb written by `generate attachment` before this
236
- # generator ran drives the forms anonymously, which every action now
237
- # redirects to the sign-in page. Its new_client gets the reset and
238
- # sign-in lines, once (AppTest.sign_in marks a test that has them); a
239
- # new_client rewritten past recognition is left alone with a note.
1004
+ # The setup line of the attachment test in an app with
1005
+ # authentication: the fixture user `one` signed in through the form
1006
+ # (SessionTestHelper#sign_in_as), as a browser would, before each test.
1007
+ def self.test_sign_in_lines
1008
+ out = +""
1009
+ out << " # A user signed in through the form: the controller's actions need one.\n"
1010
+ out << " #{TEST_SIGN_IN_POST}\n"
1011
+ out
1012
+ end
1013
+
1014
+ # A test/integration/*_attachment_test.rb written by `generate
1015
+ # attachment` before this generator ran drives the forms anonymously,
1016
+ # which every action now redirects to the sign-in page. Its setup gets
1017
+ # the sign-in line, once (TEST_SIGN_IN_POST marks a test that has
1018
+ # it); a setup rewritten past recognition is left alone with a note.
240
1019
  def self.add_sign_in_to_attachment_tests(root)
241
- Dir.glob(File.join(root, "test/attachment_*.rb")).sort.each do |path|
242
- name = "test/#{File.basename(path)}"
1020
+ Dir.glob(File.join(root, "test/integration/*_attachment_test.rb")).sort.each do |path|
1021
+ name = "test/integration/#{File.basename(path)}"
243
1022
  source = File.read(path)
244
- unless source.index("AppTest.sign_in(").nil?
1023
+ unless source.index(TEST_SIGN_IN_POST).nil?
245
1024
  puts "identical #{name} (signs in already)"
246
1025
  next
247
1026
  end
248
- if source.index(NEW_CLIENT_LINE).nil? || source.index(TEST_CLIENT_LINE).nil?
249
- puts "skip #{name} (no new_client): sign in there with AppTest.user and AppTest.sign_in(client)"
1027
+ if source.index("\n#{TEST_SETUP_LINE}\n").nil?
1028
+ puts "skip #{name} (no setup do): sign in there before each test"
250
1029
  next
251
1030
  end
252
1031
 
253
- source = insert_after_line(source, NEW_CLIENT_LINE, TEST_RESET_LINES)
254
- File.write(path, insert_after_line(source, TEST_CLIENT_LINE, TEST_SIGN_IN_LINES))
1032
+ File.write(path, insert_after_line(source, "#{TEST_SETUP_LINE}\n", test_sign_in_lines))
255
1033
  puts "insert #{name} (sign in first)"
256
1034
  end
1035
+ # An earlier generator's top-level-form attachment test
1036
+ # (test/attachment_<model>_<field>.rb) is not rewritten: it is named,
1037
+ # with what it needs, since its forms now redirect to the sign-in page.
1038
+ unsigned_attachment_tests(root).each do |name|
1039
+ puts "note #{name}: its requests now need a signed-in user; sign one in before them " \
1040
+ "(post \"/session\" with a user's email_address and password), or move it to the class form " \
1041
+ "(an ActionDispatch::IntegrationTest with `#{TEST_SIGN_IN_POST}` in its setup)"
1042
+ end
257
1043
  nil
258
1044
  end
259
1045
 
@@ -266,6 +1052,16 @@ module Cybertrain
266
1052
  out
267
1053
  end
268
1054
 
1055
+ # `text` with `spaces` spaces before every non-blank line: a chunk
1056
+ # written flush, moved to where splice puts it (inside a method's
1057
+ # `if`, say).
1058
+ def self.margin(text, spaces)
1059
+ pad = " " * spaces
1060
+ out = +""
1061
+ text.each_line { |line| out << (line == "\n" ? line : "#{pad}#{line}") }
1062
+ out
1063
+ end
1064
+
269
1065
  # `source` with `block` (its own lines, each ending in a newline)
270
1066
  # inserted right after the first line containing `marker`.
271
1067
  def self.insert_after_line(source, marker, block)
@@ -283,6 +1079,23 @@ module Cybertrain
283
1079
  updated
284
1080
  end
285
1081
 
1082
+ # `text` with the whole line that holds `mark` (a placeholder line in
1083
+ # one of the templates below, wherever it is indented) replaced by
1084
+ # `chunk`: lines of their own, each ending in a newline and indented
1085
+ # as the file needs, or "" to drop the line. What --confirmable adds
1086
+ # to a file the other modes write too goes in this way.
1087
+ def self.splice(text, mark, chunk)
1088
+ at = text.index(mark)
1089
+ raise InvalidArgument, "no `#{mark}` in the template" if at.nil?
1090
+
1091
+ start = line_start_before(text, at)
1092
+ stop = text.index("\n", at)
1093
+ stop = stop.nil? ? text.size : stop + 1
1094
+ out = +""
1095
+ out << text[0, start].to_s << chunk << text[stop, text.size - stop].to_s
1096
+ out
1097
+ end
1098
+
286
1099
  # Where the first line that starts with `marker` starts, or -1.
287
1100
  def self.line_start(source, marker)
288
1101
  return 0 if source.start_with?(marker)
@@ -306,19 +1119,28 @@ module Cybertrain
306
1119
 
307
1120
  # ---- the files ----------------------------------------------------
308
1121
 
309
- def self.users_migration
310
- <<~RUBY
1122
+ # With `confirmable`, the two columns --confirmable reads: when the
1123
+ # address was confirmed (nil: not yet), and a new address waiting for
1124
+ # its own confirmation (nil: none).
1125
+ def self.users_migration(confirmable = false)
1126
+ text = <<~RUBY
311
1127
  class CreateUsers < Cybertrain::Migration::Base
312
1128
  def change
313
1129
  create_table "users" do |t|
314
1130
  t.string "email_address", null: false
315
1131
  t.string "password_digest", null: false
1132
+ t.boolean "admin", null: false, default: "false"
1133
+ t.integer "failed_attempts", null: false, default: "0"
1134
+ t.datetime "locked_until"
1135
+ @CONFIRMABLE_COLUMNS@
316
1136
  t.timestamps
317
1137
  end
318
1138
  add_index "users", ["email_address"], unique: true
319
1139
  end
320
1140
  end
321
1141
  RUBY
1142
+ columns = confirmable ? " t.datetime \"confirmed_at\"\n t.string \"unconfirmed_email\"\n" : ""
1143
+ splice(text, "@CONFIRMABLE_COLUMNS@", columns)
322
1144
  end
323
1145
 
324
1146
  def self.sessions_migration
@@ -329,6 +1151,8 @@ module Cybertrain
329
1151
  t.references :user
330
1152
  t.string "ip_address"
331
1153
  t.string "user_agent"
1154
+ t.boolean "remember", null: false, default: "false"
1155
+ t.datetime "last_active_at"
332
1156
  t.timestamps
333
1157
  end
334
1158
  end
@@ -336,11 +1160,15 @@ module Cybertrain
336
1160
  RUBY
337
1161
  end
338
1162
 
339
- def self.user_model
340
- <<~RUBY
341
- # Columns (email_address, password_digest), the Cybertrain::Model
342
- # superclass and `sessions` (from the sessions table's foreign key) come
343
- # from gen/models/user.rb, generated from db/schema.rb by `spin run gen`.
1163
+ # With `confirmable`, what --confirmable adds: confirmed?, the
1164
+ # confirmation token and confirm, and the check of a new address
1165
+ # waiting for its confirmation.
1166
+ def self.user_model(app, confirmable = false)
1167
+ text = <<~RUBY
1168
+ # Columns (email_address, password_digest, admin, failed_attempts,
1169
+ # locked_until@CONFIRMABLE_COLUMN_NAMES@), the Cybertrain::Model superclass and `sessions` (from
1170
+ # the sessions table's foreign key) come from gen/models/user.rb,
1171
+ # generated from db/schema.rb by `spin run gen`.
344
1172
  #
345
1173
  # Written by `cybertrain generate authentication`; it is yours to change.
346
1174
  # The password is hashed by Cybertrain::Password (PBKDF2-HMAC-SHA256) into
@@ -350,16 +1178,20 @@ module Cybertrain
350
1178
  # run time, so they are written out).
351
1179
  class User
352
1180
  MIN_PASSWORD_LENGTH = 8
1181
+ @CONFIRMATION_TOKEN_TTL@
353
1182
 
354
1183
  validates :email_address, presence: true
355
1184
 
356
- # Normalizes the address, refuses a taken one, and checks the password
357
- # on a new record or whenever one was given. Errors added here make
358
- # the record invalid (Cybertrain::Model.before_validation).
1185
+ # Normalizes the address, refuses one that is not a single address
1186
+ # or is taken, and checks the password on a new record or whenever
1187
+ # one was given. Errors added here make the record invalid
1188
+ # (Cybertrain::Model.before_validation).
359
1189
  before_validation do |user|
360
1190
  user.email_address = User.normalize_email_address(user.email_address)
1191
+ user.validate_email_address_format
361
1192
  user.validate_email_address_taken
362
1193
  user.validate_password
1194
+ @VALIDATE_UNCONFIRMED_EMAIL@
363
1195
  end
364
1196
 
365
1197
  # The address lowercased and trimmed: " Ann@Example.COM " is
@@ -368,17 +1200,71 @@ module Cybertrain
368
1200
  value.to_s.strip.downcase
369
1201
  end
370
1202
 
1203
+ # Whether value is one address: exactly one @, with text before and
1204
+ # after it, and no comma, whitespace, angle bracket or control
1205
+ # character. Cybertrain::Mailer reads "a@x.example,b@y.example" as two
1206
+ # recipients, so without this an account could hold two mailboxes and
1207
+ # have its mails (a confirmation link among them) sent to both. It
1208
+ # must also be an address the mailer sends to
1209
+ # (Cybertrain::Mailer.address_problem: plain ASCII, none of
1210
+ # ( ) [ ] ; : \\ or ", within its length limits), so no account is
1211
+ # saved that could never be mailed. Some addresses the mail
1212
+ # standards allow (a quoted local part with a space or a comma in
1213
+ # it) are refused too.
1214
+ def self.email_address_format?(value)
1215
+ s = value.to_s
1216
+ n = s.bytesize
1217
+ at = -1
1218
+ i = 0
1219
+ while i < n
1220
+ b = s.getbyte(i)
1221
+ return false if b <= 32 || b == 127 || b == 44 || b == 60 || b == 62
1222
+ if b == 64
1223
+ return false if at >= 0
1224
+
1225
+ at = i
1226
+ end
1227
+ i += 1
1228
+ end
1229
+ at > 0 && at < n - 1 && Cybertrain::Mailer.address_problem(s).empty?
1230
+ end
1231
+
371
1232
  # The user with this address and password, or nil. A missing address
372
- # costs a verification too (against Cybertrain::Password.dummy_digest),
373
- # so the response time does not say which of the two was wrong.
1233
+ # and a locked account (locked?, while lockout is on) cost a password
1234
+ # verification too, against Cybertrain::Password.dummy_digest, and
1235
+ # answer nil whatever the password, as a wrong one does: the sign-in
1236
+ # form shows them all the wrong-password message. A wrong password
1237
+ # on an existing, unlocked account also writes its row once
1238
+ # (count_failed_attempt!), as Devise's lockable does; that one write
1239
+ # is the timing difference left between it and the other two, and it
1240
+ # is accepted. The right password clears the count.
374
1241
  def self.authenticate_by(email_address:, password:)
375
1242
  user = User.find_by(email_address: User.normalize_email_address(email_address))
376
- if user.nil?
1243
+ if user.nil? || (Cybertrain.config.auth_lockout_attempts > 0 && user.locked?)
377
1244
  Cybertrain::Password.verify_serialized(password.to_s, Cybertrain::Password.dummy_digest)
378
1245
  return nil
379
1246
  end
380
- user.authenticate(password) ? user : nil
1247
+ unless user.authenticate(password)
1248
+ user.count_failed_attempt!
1249
+ return nil
1250
+ end
1251
+ user.clear_failed_attempts!
1252
+ user
1253
+ end
1254
+
1255
+ # The user a password_reset_token was made for, while it is valid against
1256
+ # that user's password and address now (password_reset_binding); nil for
1257
+ # any other token (a wrong, expired or spent one, or one made for another
1258
+ # user).
1259
+ def self.find_by_password_reset_token(token)
1260
+ text = token.to_s
1261
+ user = User.find_by(id: Cybertrain::Token.id_from(text))
1262
+ return nil if user.nil?
1263
+ return nil unless Cybertrain::Token.valid?(text, "password_reset", user.password_reset_binding)
1264
+
1265
+ user
381
1266
  end
1267
+ @FIND_BY_CONFIRMATION_TOKEN@
382
1268
 
383
1269
  # The plain-text password given to `password=` in this request ("" when
384
1270
  # none was), for the validations; never stored.
@@ -421,29 +1307,230 @@ module Cybertrain
421
1307
  true
422
1308
  end
423
1309
 
424
- # Public so the before_validation block above (which receives the
425
- # record, not an implicit self) can call them.
1310
+ # Whether this user may see the admin pages (the Authentication
1311
+ # concern's require_admin): `./@APP@ user admin EMAIL` sets it.
1312
+ def admin? = admin
1313
+
1314
+ # Whether wrong passwords have locked the account for now
1315
+ # (count_failed_attempt!): authenticate_by refuses it until then,
1316
+ # unless lockout is off (auth_lockout_attempts 0), which also stops
1317
+ # enforcing a lock made before.
1318
+ def locked? = !locked_until.nil? && locked_until > Time.current
1319
+
1320
+ # A wrong password: one more failed attempt, counted by the database
1321
+ # in one UPDATE that reads the row as it is (so sign-ins at the same
1322
+ # time all count). The attempt that reaches
1323
+ # Cybertrain.config.auth_lockout_attempts (10; 0 never locks) locks
1324
+ # the account for auth_lockout_period seconds (an hour) and starts
1325
+ # the count again, in the same statement.
1326
+ def count_failed_attempt!
1327
+ limit = Cybertrain.config.auth_lockout_attempts
1328
+ return nil if limit <= 0
1329
+
1330
+ count = "failed_attempts = CASE WHEN failed_attempts + 1 >= ? THEN 0 ELSE failed_attempts + 1 END"
1331
+ lock = "locked_until = CASE WHEN failed_attempts + 1 >= ? THEN ? ELSE locked_until END"
1332
+ ends = Time.current + Cybertrain.config.auth_lockout_period
1333
+ User.where(id: id).update_all_sql(count + ", " + lock, [limit, limit, ends])
1334
+ nil
1335
+ end
1336
+
1337
+ # No failed attempts and no lock: a successful sign-in calls it, and
1338
+ # so do `./@APP@ user EMAIL PASSWORD` and a password reset
1339
+ # (PasswordsController#update). Writes only when there is something
1340
+ # to clear.
1341
+ def clear_failed_attempts!
1342
+ return nil if failed_attempts == 0 && locked_until.nil?
1343
+
1344
+ update_columns(failed_attempts: 0, locked_until: nil)
1345
+ nil
1346
+ end
1347
+
1348
+ # The token of a password reset link (PasswordsController): signed,
1349
+ # valid for 15 minutes from now, and bound to password_reset_binding,
1350
+ # so it stops working once the password or the address changes
1351
+ # (Cybertrain::Token).
1352
+ def password_reset_token(now = Time.current.to_i)
1353
+ Cybertrain::Token.issue("password_reset", id, 15 * 60, password_reset_binding, now)
1354
+ end
1355
+
1356
+ # What a password reset token is bound to: the password and the address,
1357
+ # so a new password or a new address ends every link sent before (the
1358
+ # old address's mailbox keeps no way into the account).
1359
+ def password_reset_binding
1360
+ digest = password_digest.to_s
1361
+ address = email_address.to_s
1362
+ "\#{digest}:\#{address}"
1363
+ end
1364
+ @CONFIRMATION_METHODS@
1365
+
1366
+ # Public so the before_validation block above (which receives the
1367
+ # record, not an implicit self) can call them. Their messages come
1368
+ # from the dictionary of the current locale, as a validator's do.
1369
+
1370
+ # An address saved before this check existed is left as it is, so
1371
+ # that account can still be reset and signed in to; a new or changed
1372
+ # one must be a single address (User.email_address_format?).
1373
+ def validate_email_address_format
1374
+ address = email_address.to_s
1375
+ return nil if address.empty? || User.email_address_format?(address)
1376
+ return nil if persisted? && User.where(id: id, email_address: address).exists?
1377
+
1378
+ errors.add(:email_address, I18n.error_message("user", :email_address, :invalid))
1379
+ nil
1380
+ end
426
1381
 
427
1382
  def validate_email_address_taken
428
1383
  address = email_address
429
1384
  return nil if address.nil? || address.empty?
430
1385
 
431
1386
  taken = User.where(email_address: address).where_sql("id != ?", [id]).exists?
432
- errors.add(:email_address, "has already been taken") if taken
1387
+ errors.add(:email_address, I18n.error_message("user", :email_address, :taken)) if taken
433
1388
  nil
434
1389
  end
435
1390
 
436
1391
  def validate_password
437
1392
  given = password
438
1393
  if password_digest.to_s.empty?
439
- errors.add(:password, "can't be blank")
1394
+ errors.add(:password, I18n.error_message("user", :password, :blank))
440
1395
  elsif !given.empty? && given.size < MIN_PASSWORD_LENGTH
441
- errors.add(:password, "is too short (minimum is \#{MIN_PASSWORD_LENGTH} characters)")
1396
+ errors.add(:password, I18n.error_message("user", :password, :too_short, { count: MIN_PASSWORD_LENGTH }))
442
1397
  end
443
1398
  confirmation = @password_confirmation
444
- errors.add(:password_confirmation, "doesn't match Password") if !confirmation.nil? && confirmation != given
1399
+ if !confirmation.nil? && confirmation != given
1400
+ attribute = I18n.human_attribute_name("user", :password)
1401
+ errors.add(:password_confirmation, I18n.error_message("user", :password_confirmation, :confirmation, { attribute: attribute }))
1402
+ end
445
1403
  nil
446
1404
  end
1405
+ @VALIDATE_UNCONFIRMED_EMAIL_METHOD@
1406
+ end
1407
+ RUBY
1408
+ text = text.gsub("@APP@", app)
1409
+ text = text.sub("@CONFIRMABLE_COLUMN_NAMES@", confirmable ? ", confirmed_at,\n# unconfirmed_email" : "")
1410
+ text = splice(text, "@CONFIRMATION_TOKEN_TTL@", confirmable ? confirmation_token_ttl_lines : "")
1411
+ text = splice(text, "@VALIDATE_UNCONFIRMED_EMAIL@", confirmable ? " user.validate_unconfirmed_email\n" : "")
1412
+ text = splice(text, "@FIND_BY_CONFIRMATION_TOKEN@", confirmable ? find_by_confirmation_token_method : "")
1413
+ text = splice(text, "@CONFIRMATION_METHODS@", confirmable ? confirmation_methods : "")
1414
+ splice(text, "@VALIDATE_UNCONFIRMED_EMAIL_METHOD@", confirmable ? validate_unconfirmed_email_method : "")
1415
+ end
1416
+
1417
+ # --confirmable's pieces of app/models/user.rb (user_model).
1418
+ def self.confirmation_token_ttl_lines
1419
+ indent(<<~'RUBY')
1420
+ # How long a confirmation link works: three days (--confirmable).
1421
+ CONFIRMATION_TOKEN_TTL = 3 * 24 * 3600
1422
+ RUBY
1423
+ end
1424
+
1425
+ def self.find_by_confirmation_token_method
1426
+ indent(<<~'RUBY')
1427
+
1428
+ # The user a confirmation_token was made for, while it still confirms
1429
+ # what it was made to (confirmation_binding); nil for any other token (a
1430
+ # wrong, expired or used one, or one made for another user).
1431
+ def self.find_by_confirmation_token(token)
1432
+ text = token.to_s
1433
+ user = User.find_by(id: Cybertrain::Token.id_from(text))
1434
+ return nil if user.nil?
1435
+ return nil unless Cybertrain::Token.valid?(text, "confirmation", user.confirmation_binding)
1436
+
1437
+ user
1438
+ end
1439
+ RUBY
1440
+ end
1441
+
1442
+ def self.confirmation_methods
1443
+ indent(<<~'RUBY')
1444
+
1445
+ # Whether the address has been confirmed (--confirmable): until it is,
1446
+ # SessionsController#create answers the right password with the
1447
+ # message that asks for the confirmation, and signs nobody in.
1448
+ def confirmed? = !confirmed_at.nil?
1449
+
1450
+ # The token of a confirmation link (ConfirmationsController#show):
1451
+ # signed, valid for CONFIRMATION_TOKEN_TTL from now, and bound to
1452
+ # confirmation_binding, so it confirms the address it was mailed to and
1453
+ # works once.
1454
+ def confirmation_token(now = Time.current.to_i)
1455
+ Cybertrain::Token.issue("confirmation", id, CONFIRMATION_TOKEN_TTL, confirmation_binding, now)
1456
+ end
1457
+
1458
+ # What a confirmation token is bound to: the address being confirmed
1459
+ # (unconfirmed_email when a new one waits, else email_address), the
1460
+ # address in use, and when an address was last confirmed (0: never).
1461
+ # Confirming changes it (confirmed_at, and a new address moves into
1462
+ # email_address), so a used link confirms nothing more; asking for
1463
+ # another new address ends the link to the one before.
1464
+ def confirmation_binding
1465
+ pending = unconfirmed_email.to_s
1466
+ address = email_address.to_s
1467
+ at = confirmed_at
1468
+ stamp = at.nil? ? 0 : at.to_i
1469
+ "#{pending}:#{address}:#{stamp}"
1470
+ end
1471
+
1472
+ # Confirms what confirmation_binding names: a new account's address, or
1473
+ # the new address waiting, which takes the place of the old one. False,
1474
+ # with the reason in errors, when another account has taken that address
1475
+ # since it was asked for (validate_email_address_taken asks again here,
1476
+ # and the unique index behind it): then only the address waiting is
1477
+ # forgotten, as it can never be confirmed now.
1478
+ def confirm
1479
+ pending = unconfirmed_email.to_s
1480
+ self.email_address = pending unless pending.empty?
1481
+ self.unconfirmed_email = nil
1482
+ self.confirmed_at = Time.current
1483
+ return true if save_confirmed
1484
+
1485
+ update_columns(unconfirmed_email: nil) unless pending.empty?
1486
+ false
1487
+ end
1488
+
1489
+ # confirm's save. Another account that takes the address between the
1490
+ # check and the write meets the unique index: the same answer as the
1491
+ # check's, not an error page.
1492
+ def save_confirmed
1493
+ save
1494
+ rescue Cybertrain::DB::Error => e
1495
+ raise e unless e.message.include?("UNIQUE")
1496
+
1497
+ errors.add(:email_address, I18n.error_message("user", :email_address, :taken))
1498
+ false
1499
+ end
1500
+
1501
+ # Asks for a new address (AccountsController#update): it waits in
1502
+ # unconfirmed_email for the link mailed to it, and is checked
1503
+ # (validate_unconfirmed_email) by this save only, so an address someone
1504
+ # takes later never stops a reset, the user command or a rehash from
1505
+ # saving the account.
1506
+ def request_email_change(address)
1507
+ requested = User.normalize_email_address(address)
1508
+ @requested_email = requested
1509
+ self.unconfirmed_email = requested
1510
+ nil
1511
+ end
1512
+ RUBY
1513
+ end
1514
+
1515
+ def self.validate_unconfirmed_email_method
1516
+ indent(<<~'RUBY')
1517
+
1518
+ # The new address request_email_change asked for (--confirmable),
1519
+ # refused when blank, not a single address (User.email_address_format?)
1520
+ # or another account's address, on email_address (the field the form
1521
+ # shows). Any other save skips it.
1522
+ def validate_unconfirmed_email
1523
+ requested = @requested_email
1524
+ return nil if requested.nil?
1525
+
1526
+ if requested.empty?
1527
+ errors.add(:email_address, I18n.error_message("user", :email_address, :blank))
1528
+ elsif !User.email_address_format?(requested)
1529
+ errors.add(:email_address, I18n.error_message("user", :email_address, :invalid))
1530
+ elsif User.where(email_address: requested).where_sql("id != ?", [id]).exists?
1531
+ errors.add(:email_address, I18n.error_message("user", :email_address, :taken))
1532
+ end
1533
+ nil
447
1534
  end
448
1535
  RUBY
449
1536
  end
@@ -456,231 +1543,1052 @@ module Cybertrain
456
1543
  # deleting their rows. Columns, the Cybertrain::Model superclass and
457
1544
  # `user` (from the user_id foreign key) come from gen/models/session.rb.
458
1545
  #
459
- # Not to be confused with Cybertrain::Session, the signed cookie that
1546
+ # Not to be confused with Cybertrain::Session, the encrypted cookie that
460
1547
  # holds this row's id as `session[:session_id]`.
461
1548
  class Session
462
1549
  end
463
1550
  RUBY
464
1551
  end
465
1552
 
466
- # Inserted (indented) after the class line of
467
- # app/controllers/application_controller.rb.
468
- def self.application_controller_block
469
- <<~RUBY
470
- # ---- Authentication (cybertrain generate authentication) -------------
471
- # Every action needs a signed-in user unless its controller opens it:
1553
+ # app/controllers/concerns/authentication.rb: what 0.4 inserted into
1554
+ # ApplicationController, as Rails 8's concern, plus require_admin and
1555
+ # mail_link_base (the one place that decides where a mail's links
1556
+ # point: the reset's, and --confirmable's), plus with `confirmable`
1557
+ # send_confirmation_mail, which the controllers that mail a
1558
+ # confirmation share.
1559
+ def self.authentication_concern(app, confirmable = false)
1560
+ env = base_url_env(app)
1561
+ text = <<~RUBY
1562
+ # Sign-in for the whole application (cybertrain generate authentication),
1563
+ # as Rails 8's generator writes it: ApplicationController includes it, so
1564
+ # every action needs a signed-in user unless its controller opens it with
472
1565
  # `allow_unauthenticated_access only: [:new, :create]`. resume_session
473
- # sets @current_user (and @current_session), which templates can read.
474
- before_action :resume_session
475
- before_action :require_authentication
1566
+ # sets @current_user (and @current_session), which templates can read;
1567
+ # require_admin guards the pages only admins may see.
1568
+ #
1569
+ # Written by the generator; it is yours to change.
1570
+ module Authentication
1571
+ extend ActiveSupport::Concern
476
1572
 
477
- def self.allow_unauthenticated_access(only: [], except: [])
478
- skip_before_action(:require_authentication, only: only, except: except)
479
- end
1573
+ included do
1574
+ before_action :resume_session
1575
+ before_action :require_authentication
1576
+ helper_method :authenticated?
1577
+ end
480
1578
 
481
- # @return [Boolean] whether this request has a signed-in user
482
- def authenticated?
483
- !@current_user.nil?
484
- end
1579
+ private
485
1580
 
486
- # Loads the Session row the cookie names (and its user); a stale or
487
- # expired id is dropped. Cookie Max-Age alone cannot stop replay:
488
- # authentication expires session_absolute_max_age seconds after
489
- # sign-in (SessionStore enforces the same on the cookie). A cookie
490
- # whose password key no longer matches (the password changed since
491
- # it signed in) ends its Session row.
492
- def resume_session
493
- @current_session = nil
494
- @current_user = nil
495
- id = session[:session_id]
496
- return nil if id.nil? || id.empty? || id.size > 18
1581
+ # Whether this request has a signed-in user.
1582
+ def authenticated?
1583
+ !@current_user.nil?
1584
+ end
497
1585
 
498
- found = Session.find_by(id: id.to_i)
499
- if found.nil?
500
- session.delete(:session_id)
501
- return nil
1586
+ # Loads the Session row the cookie names (and its user); an id with no
1587
+ # row is dropped, and an expired row is ended (destroyed, so no later
1588
+ # change of the limits revives it). Cookie Max-Age alone cannot stop
1589
+ # replay, so the row's own limits end a sign-in: session_limit(remember) seconds
1590
+ # after it started (SessionStore enforces the same on the cookie,
1591
+ # from the stamp start_new_session_for writes), and auth_idle_timeout
1592
+ # seconds (0: no limit) after its last request (last_active_at, or
1593
+ # created_at while it has none). A request touches last_active_at at
1594
+ # most once a minute. A cookie whose password key no longer matches
1595
+ # (the password changed since it signed in) ends its Session row.
1596
+ def resume_session
1597
+ @current_session = nil
1598
+ @current_user = nil
1599
+ id = session[:session_id]
1600
+ return nil if id.nil? || id.empty? || id.size > 18
1601
+
1602
+ found = Session.find_by(id: id.to_i)
1603
+ if found.nil?
1604
+ session.delete(:session_id)
1605
+ return nil
1606
+ end
1607
+ created_at = found.created_at
1608
+ now = Time.current.to_i
1609
+ if created_at.nil? || created_at.to_i + session_limit(found.remember) <= now
1610
+ found.destroy
1611
+ session.delete(:session_id)
1612
+ return nil
1613
+ end
1614
+ last_active_at = found.last_active_at
1615
+ active = last_active_at.nil? ? created_at.to_i : last_active_at.to_i
1616
+ idle = Cybertrain.config.auth_idle_timeout
1617
+ if idle > 0 && active + idle <= now
1618
+ found.destroy
1619
+ session.delete(:session_id)
1620
+ return nil
1621
+ end
1622
+ user = found.user
1623
+ if user.nil? || !Cybertrain::Password.session_key_matches?(session[:password_key], user.password_digest)
1624
+ found.destroy
1625
+ session.delete(:session_id)
1626
+ return nil
1627
+ end
1628
+ found.update_columns(last_active_at: Time.current) if now - active >= 60
1629
+ @current_session = found
1630
+ @current_user = user
1631
+ nil
502
1632
  end
503
- created_at = found.created_at
504
- lifetime = Cybertrain.config.session_absolute_max_age
505
- if created_at.nil? || (lifetime > 0 && created_at.to_i + lifetime <= Time.now.to_i)
506
- session.delete(:session_id)
507
- return nil
1633
+
1634
+ # Sends a visitor to the sign-in page, remembering a GET to come back to.
1635
+ def require_authentication
1636
+ return nil if authenticated?
1637
+
1638
+ session[:return_to_after_authenticating] = request.path if request.method == "GET"
1639
+ redirect_to new_session_path, status: :see_other
1640
+ nil
508
1641
  end
509
- user = found.user
510
- if user.nil? || !Cybertrain::Password.session_key_matches?(session[:password_key], user.password_digest)
511
- found.destroy
512
- session.delete(:session_id)
513
- return nil
1642
+
1643
+ # The before_action of the pages only admins may see: anyone but a
1644
+ # signed-in admin gets a 404, as if there were no such page. The user
1645
+ # command makes a user an admin (`user admin EMAIL`,
1646
+ # app/commands/user_command.rb). The jobs page (config/routes.rb)
1647
+ # names it with `skip_before_action: :require_authentication`, so it
1648
+ # runs alone there and a visitor gets the 404 too; in a controller
1649
+ # that declares `before_action :require_admin` itself,
1650
+ # require_authentication runs first and sends a visitor to sign in.
1651
+ def require_admin
1652
+ render plain: "Not Found", status: :not_found unless @current_user && @current_user.admin?
1653
+ nil
514
1654
  end
515
- @current_session = found
516
- @current_user = user
517
- nil
518
- end
519
1655
 
520
- # Sends a visitor to the sign-in page, remembering a GET to come back to.
521
- def require_authentication
522
- return nil if authenticated?
1656
+ # Signs user in: a Session row (remembered or not, active now), its
1657
+ # id and the password key resume_session compares in the cookie, and
1658
+ # the cookie's lifetime, restarted and then stamped in that order (a
1659
+ # restart clears the stamp): session_limit(remember) seconds, with a
1660
+ # Max-Age when remembered ("keep me signed in"), else a cookie the
1661
+ # browser drops when it closes. After a password change, call
1662
+ # `session[:password_key] = Cybertrain::Password.session_key(user.password_digest)`
1663
+ # to keep the browser that changed it signed in.
1664
+ def start_new_session_for(user, remember: false)
1665
+ @CONFIRMED_ONLY@
1666
+ started = Session.create(user_id: user.id, ip_address: request.client_ip,
1667
+ user_agent: request.header("user-agent").to_s,
1668
+ remember: remember, last_active_at: Time.current)
1669
+ session.restart_lifetime!
1670
+ session.stamp_lifetime!(session_limit(remember), remember)
1671
+ session[:session_id] = started.id
1672
+ session[:password_key] = Cybertrain::Password.session_key(user.password_digest)
1673
+ @current_session = started
1674
+ @current_user = user
1675
+ nil
1676
+ end
523
1677
 
524
- session[:return_to_after_authenticating] = request.path if request.method == "GET"
525
- redirect_to new_session_path, status: :see_other
526
- nil
527
- end
1678
+ # How long a sign-in lasts in seconds, however often it is used:
1679
+ # auth_remember_for when remembered, else (or when that is not
1680
+ # positive) session_absolute_max_age, or with that off (0)
1681
+ # session_max_age, or two weeks when that is not positive either.
1682
+ # Never 0: a stamp of 0 would leave the cookie with no limit at all.
1683
+ def session_limit(remember)
1684
+ c = Cybertrain.config
1685
+ return c.auth_remember_for if remember && c.auth_remember_for > 0
1686
+ return c.session_absolute_max_age if c.session_absolute_max_age > 0
1687
+ return c.session_max_age if c.session_max_age > 0
1688
+
1689
+ 1_209_600
1690
+ end
528
1691
 
529
- # Also stores the password key resume_session compares, and restarts
530
- # the cookie's absolute lifetime. After a password change, call
531
- # `session[:password_key] = Cybertrain::Password.session_key(user.password_digest)`
532
- # to keep the browser that changed it signed in.
533
- def start_new_session_for(user)
534
- started = Session.create(user_id: user.id, ip_address: request.client_ip,
535
- user_agent: request.header("user-agent").to_s)
536
- session.restart_lifetime!
537
- session[:session_id] = started.id
538
- session[:password_key] = Cybertrain::Password.session_key(user.password_digest)
539
- @current_session = started
540
- @current_user = user
541
- nil
542
- end
1692
+ # Deletes the Session row and empties the cookie session (the CSRF
1693
+ # token with it, so forms rendered before no longer submit).
1694
+ def terminate_session
1695
+ current = @current_session
1696
+ current.destroy unless current.nil?
1697
+ session.clear
1698
+ @current_session = nil
1699
+ @current_user = nil
1700
+ nil
1701
+ end
543
1702
 
544
- # Deletes the Session row and empties the cookie session (the CSRF
545
- # token with it, so forms rendered before no longer submit).
546
- def terminate_session
547
- current = @current_session
548
- current.destroy unless current.nil?
549
- session.clear
550
- @current_session = nil
551
- @current_user = nil
552
- nil
1703
+ # Where to go after signing in: the page that asked for it, if it is a
1704
+ # local path (Cybertrain::Controller#safe_redirect_path), or /.
1705
+ def after_authentication_url
1706
+ safe_redirect_path(session.delete(:return_to_after_authenticating), "/")
1707
+ end
1708
+
1709
+ # Where links in mails start ("https://shop.example.com"): the base_url
1710
+ # setting (#{env}, config/app.rb) when set; else the address this
1711
+ # request came to, but only where the Host header is known to be
1712
+ # safe: the Host is checked (development, or CYBERTRAIN_HOSTS lists
1713
+ # the hosts the app answers to, so any other Host is refused before
1714
+ # an action runs), or the app runs its tests. In any other
1715
+ # environment (production, staging, ...) "" and an [ERROR] line: the
1716
+ # mail named `mail` is not sent, as a link built from a Host header
1717
+ # anyone can forge would carry its token to their site.
1718
+ def mail_link_base(mail)
1719
+ c = Cybertrain.config
1720
+ configured = c.string_setting(:base_url)
1721
+ return configured.delete_suffix("/") unless configured.empty?
1722
+ return request.base_url if c.host_check? || c.test?
1723
+
1724
+ Cybertrain.logger.error("\#{mail} mail not sent: set #{env} (or CYBERTRAIN_HOSTS)")
1725
+ ""
1726
+ end
1727
+ @SEND_CONFIRMATION_MAIL@
553
1728
  end
1729
+ RUBY
1730
+ text = splice(text, "@CONFIRMED_ONLY@", confirmable ? confirmed_only_lines : "")
1731
+ splice(text, "@SEND_CONFIRMATION_MAIL@", confirmable ? send_confirmation_mail_method : "")
1732
+ end
554
1733
 
555
- # Where to go after signing in: the page that asked for it, if it is a
556
- # local path (Cybertrain::Controller#safe_redirect_path), or /.
557
- def after_authentication_url
558
- safe_redirect_path(session.delete(:return_to_after_authenticating), "/")
1734
+ # --confirmable's first lines of the concern's start_new_session_for:
1735
+ # no session for an account whose address is not confirmed, whichever
1736
+ # action asks. SessionsController#create refuses such an account
1737
+ # first, with its own message; this holds where that check is
1738
+ # missing too (a sessions controller an upgrade's diff never reached).
1739
+ def self.confirmed_only_lines
1740
+ margin(<<~'RUBY', 4)
1741
+ # --confirmable: an account whose address is not confirmed gets no
1742
+ # session, whichever action asks (SessionsController#create says
1743
+ # why first; this holds where that check is missing too).
1744
+ unless user.confirmed?
1745
+ Cybertrain.logger.warn("no session started: user #{user.id} has not confirmed its address")
1746
+ return nil
559
1747
  end
560
- # ---- end of authentication ------------------------------------------
561
1748
 
562
1749
  RUBY
563
1750
  end
564
1751
 
565
- def self.sessions_controller
566
- <<~RUBY
1752
+ # --confirmable's private method of the concern: sign-up, the account
1753
+ # page and the send-again form all mail a confirmation this way.
1754
+ def self.send_confirmation_mail_method
1755
+ indent(<<~'RUBY')
1756
+
1757
+ # The confirmation mail (ConfirmationsMailer, --confirmable) to the
1758
+ # address user is confirming, with the link to
1759
+ # ConfirmationsController#show for token, from mail_link_base. Queued
1760
+ # only when deliver is true: the send-again form builds the mail for an
1761
+ # address that gets none as well, so that its answer takes the same
1762
+ # work. An address the mailer refuses is logged (the message never
1763
+ # repeats the address), and the caller answers as it would have.
1764
+ def send_confirmation_mail(user, token, deliver)
1765
+ base = mail_link_base("confirmation")
1766
+ return nil if base.empty?
1767
+
1768
+ path = confirmation_path(token)
1769
+ mail = ConfirmationsMailer.confirmation_instructions(user, base + path)
1770
+ mail.deliver_later if deliver
1771
+ nil
1772
+ rescue ArgumentError => e
1773
+ Cybertrain.logger.error("confirmation mail not sent: #{e.message}")
1774
+ nil
1775
+ end
1776
+ RUBY
1777
+ end
1778
+
1779
+ # With `confirmable`, the right password and an address not confirmed
1780
+ # yet get their own message, and no session.
1781
+ def self.sessions_controller(confirmable = false)
1782
+ text = <<~RUBY
567
1783
  # Sign in and out (cybertrain generate authentication).
568
1784
  class SessionsController < ApplicationController
569
1785
  allow_unauthenticated_access only: [:new, :create]
570
1786
  # Ten sign-in attempts per client address every three minutes, then
571
- # back to the form until the window closes. Behind a reverse proxy on
572
- # this host, set CYBERTRAIN_TRUSTED_PROXY=1 so that each visitor is
573
- # counted rather than the proxy (README, "Rate limiting").
574
- rate_limit to: 10, within: 3 * 60, only: [:create],
575
- redirect_to: "/session/new", alert: "Try again later."
1787
+ # back to the form (rate_limited) until the window closes. Behind a
1788
+ # reverse proxy on this host, set CYBERTRAIN_TRUSTED_PROXY=1 so that
1789
+ # each visitor is counted rather than the proxy.
1790
+ rate_limit to: 10, within: 3 * 60, only: [:create], with: :rate_limited
576
1791
 
577
1792
  # GET /session/new
578
1793
  # (named new_action: a `new` method would shadow SessionsController.new)
579
1794
  def new_action
580
1795
  end
581
1796
 
582
- # POST /session
583
- def create
584
- user = User.authenticate_by(email_address: params[:email_address].to_s, password: params[:password].to_s)
585
- if user.nil?
586
- flash[:alert] = "Try another email address or password."
587
- redirect_to new_session_path, status: :see_other
1797
+ # POST /session
1798
+ def create
1799
+ user = User.authenticate_by(email_address: params[:email_address].to_s, password: params[:password].to_s)
1800
+ if user.nil?
1801
+ flash[:alert] = t(".invalid")
1802
+ redirect_to new_session_path, status: :see_other
1803
+ @UNCONFIRMED@
1804
+ else
1805
+ start_new_session_for(user, remember: params[:remember_me] == "1")
1806
+ redirect_to after_authentication_url, status: :see_other
1807
+ end
1808
+ end
1809
+
1810
+ # DELETE /session
1811
+ def destroy
1812
+ terminate_session
1813
+ flash[:notice] = t(".signed_out")
1814
+ redirect_to new_session_path, status: :see_other
1815
+ end
1816
+
1817
+ private
1818
+
1819
+ # What a client past the rate limit gets: the form again, with a
1820
+ # message. Not an action, so its key is written in full (the
1821
+ # action it answers for is create).
1822
+ def rate_limited
1823
+ flash[:alert] = t("sessions.create.rate_limited")
1824
+ redirect_to new_session_path, status: :see_other
1825
+ nil
1826
+ end
1827
+ end
1828
+ RUBY
1829
+ splice(text, "@UNCONFIRMED@", confirmable ? sessions_unconfirmed_branch : "")
1830
+ end
1831
+
1832
+ # --confirmable's branch of SessionsController#create.
1833
+ def self.sessions_unconfirmed_branch
1834
+ margin(<<~'RUBY', 4)
1835
+ elsif !user.confirmed?
1836
+ # Said only once the password is right, so that it tells nobody
1837
+ # without the password that the address is registered. The
1838
+ # sign-in page links to the form that mails the link again.
1839
+ flash[:alert] = t(".unconfirmed")
1840
+ redirect_to new_session_path, status: :see_other
1841
+ RUBY
1842
+ end
1843
+
1844
+ # With `confirmable`, a sign-up mails the confirmation link and signs
1845
+ # nobody in.
1846
+ def self.registrations_controller(confirmable = false)
1847
+ text = <<~RUBY
1848
+ # Sign up (cybertrain generate authentication). Rails' generator has no
1849
+ # sign-up page and expects the first user to be created in the console;
1850
+ # cybertrain has no console, so this is how the first user gets in.
1851
+ # Delete it (and its routes) for an invitation-only application.
1852
+ class RegistrationsController < ApplicationController
1853
+ allow_unauthenticated_access only: [:new, :create]
1854
+ # Ten sign-ups per client address every three minutes, as for signing
1855
+ # in: each one hashes a password and may mail a link, and each
1856
+ # "already been taken" says an address is registered.
1857
+ rate_limit to: 10, within: 3 * 60, only: [:create], with: :rate_limited
1858
+
1859
+ # GET /sign_up
1860
+ def new_action
1861
+ @user = User.new
1862
+ end
1863
+
1864
+ # POST /sign_up
1865
+ def create
1866
+ fields = params.require(:user)
1867
+ @user = User.new(fields.permit(:email_address))
1868
+ @user.password = fields[:password].to_s
1869
+ @user.password_confirmation = fields[:password_confirmation].to_s
1870
+ if @user.save
1871
+ @SIGNED_UP@
1872
+ else
1873
+ render :new, status: :unprocessable_entity
1874
+ end
1875
+ end
1876
+
1877
+ private
1878
+
1879
+ # What a client past the rate limit gets: the form again, with a
1880
+ # message (the key is create's).
1881
+ def rate_limited
1882
+ flash[:alert] = t("registrations.create.rate_limited")
1883
+ redirect_to sign_up_path, status: :see_other
1884
+ nil
1885
+ end
1886
+ end
1887
+ RUBY
1888
+ splice(text, "@SIGNED_UP@", confirmable ? registrations_confirm_lines : registrations_sign_in_lines)
1889
+ end
1890
+
1891
+ def self.registrations_sign_in_lines
1892
+ margin(<<~'RUBY', 6)
1893
+ start_new_session_for(@user)
1894
+ flash[:notice] = t(".welcome")
1895
+ redirect_to after_authentication_url, status: :see_other
1896
+ RUBY
1897
+ end
1898
+
1899
+ # --confirmable: the link by mail, and the sign-in page.
1900
+ def self.registrations_confirm_lines
1901
+ margin(<<~'RUBY', 6)
1902
+ # Signed in only once the address is confirmed (the mail's link),
1903
+ # and then with the password.
1904
+ token = @user.confirmation_token
1905
+ send_confirmation_mail(@user, token, true)
1906
+ flash[:notice] = t(".confirm")
1907
+ redirect_to new_session_path, status: :see_other
1908
+ RUBY
1909
+ end
1910
+
1911
+ # With --invite-only there is no sign-up page to link to; with
1912
+ # `confirmable`, a link to the form that mails the confirmation again.
1913
+ def self.sessions_new_view(invite_only = false, confirmable = false)
1914
+ view = <<~ERB
1915
+ <h1><%= t(".title") %></h1>
1916
+
1917
+ <%= form_with(url: session_path) do |f| %>
1918
+ <div class="field">
1919
+ <%= f.label :email_address, t(".email_address") %>
1920
+ <%= f.email_field :email_address, autocomplete: "username", autofocus: true %>
1921
+ </div>
1922
+
1923
+ <div class="field">
1924
+ <%= f.label :password, t(".password") %>
1925
+ <%= f.password_field :password, autocomplete: "current-password" %>
1926
+ </div>
1927
+
1928
+ <div class="field">
1929
+ <%= check_box_tag :remember_me %>
1930
+ <%= label_tag :remember_me, t(".remember_me") %>
1931
+ </div>
1932
+
1933
+ <div class="actions">
1934
+ <%= f.submit t(".submit") %>
1935
+ </div>
1936
+ <% end %>
1937
+
1938
+ <p><%= link_to t(".forgot_password"), new_password_path %></p>
1939
+ ERB
1940
+ view = "#{view}<p><%= link_to t(\".confirmation\"), new_confirmation_path %></p>\n" if confirmable
1941
+ return view if invite_only
1942
+
1943
+ "#{view}<p><%= link_to t(\".sign_up\"), sign_up_path %></p>\n"
1944
+ end
1945
+
1946
+ def self.nav_partial
1947
+ <<~ERB
1948
+ <%# locals: () %>
1949
+ <nav class="session">
1950
+ <% if @current_user %>
1951
+ <span><%= @current_user.email_address %></span>
1952
+ <%= link_to t(".account"), edit_account_path %>
1953
+ <%= button_to t(".sign_out"), session_path, method: :delete %>
1954
+ <% else %>
1955
+ <%= link_to t(".sign_in"), new_session_path %>
1956
+ <% end %>
1957
+ </nav>
1958
+ ERB
1959
+ end
1960
+
1961
+ def self.registrations_new_view
1962
+ <<~ERB
1963
+ <h1><%= t(".title") %></h1>
1964
+
1965
+ <%= form_with(model: @user, url: sign_up_path) do |f| %>
1966
+ <% if @user.errors.any? %>
1967
+ <div id="error_explanation">
1968
+ <h2><%= t("errors.template.header", count: @user.errors.count, model: t(".model")) %></h2>
1969
+ <ul>
1970
+ <% @user.errors.full_messages.each do |message| %>
1971
+ <li><%= message %></li>
1972
+ <% end %>
1973
+ </ul>
1974
+ </div>
1975
+ <% end %>
1976
+
1977
+ <div class="field">
1978
+ <%= f.label :email_address %>
1979
+ <%= f.email_field :email_address, autocomplete: "username" %>
1980
+ </div>
1981
+
1982
+ <div class="field">
1983
+ <%= f.label :password %>
1984
+ <%= f.password_field :password, autocomplete: "new-password" %>
1985
+ </div>
1986
+
1987
+ <div class="field">
1988
+ <%= f.label :password_confirmation %>
1989
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
1990
+ </div>
1991
+
1992
+ <div class="actions">
1993
+ <%= f.submit t(".submit") %>
1994
+ </div>
1995
+ <% end %>
1996
+
1997
+ <p><%= link_to t(".sign_in"), new_session_path %></p>
1998
+ ERB
1999
+ end
2000
+
2001
+ # ---- password reset -----------------------------------------------
2002
+
2003
+ # app/controllers/passwords_controller.rb: Rails 8's, with the same
2004
+ # answer and work for an unknown address, the link's base from the
2005
+ # concern's mail_link_base, and a reset that clears a lockout and ends
2006
+ # every session of the user.
2007
+ # With `confirmable` a reset also confirms the address it was mailed to.
2008
+ def self.passwords_controller(confirmable = false)
2009
+ text = <<~'RUBY'
2010
+ # Password reset (cybertrain generate authentication): the form that asks
2011
+ # for an address, the mail with a link (PasswordsMailer.reset), and the
2012
+ # form behind the link that sets a new password. The link's token
2013
+ # (User#password_reset_token) is signed, lasts 15 minutes and is bound to
2014
+ # the password and the address, so it stops working once either changes,
2015
+ # and every link sent before with it. The address form answers the same
2016
+ # whether or not the address is registered.
2017
+ class PasswordsController < ApplicationController
2018
+ allow_unauthenticated_access
2019
+ # Ten requests per client address every three minutes, as for signing in.
2020
+ rate_limit to: 10, within: 3 * 60, only: [:create], with: :rate_limited
2021
+ # The link's page carries the token in its address: no Referer for it.
2022
+ before_action :no_referrer, only: [:edit, :update]
2023
+
2024
+ # GET /passwords/new
2025
+ def new_action
2026
+ end
2027
+
2028
+ # POST /passwords
2029
+ # An address no user has gets the same answer after the same work (a
2030
+ # token, the mail rendered), short of queueing the mail.
2031
+ def create
2032
+ address = User.normalize_email_address(params[:email_address].to_s)
2033
+ user = User.find_by(email_address: address)
2034
+ token = user.nil? ? Cybertrain::Token.issue("password_reset", 1, 15 * 60, Cybertrain::Password.dummy_digest) : user.password_reset_token
2035
+ url = edit_password_url_for(token)
2036
+ unless url.empty?
2037
+ mail = PasswordsMailer.reset(user.nil? ? User.new(email_address: address) : user, url)
2038
+ queue_reset_mail(mail) unless user.nil?
2039
+ end
2040
+ flash[:notice] = t(".sent")
2041
+ redirect_to new_session_path, status: :see_other
2042
+ end
2043
+
2044
+ # GET /passwords/:token/edit
2045
+ def edit
2046
+ @token = params[:token].to_s
2047
+ invalid_link if User.find_by_password_reset_token(@token).nil?
2048
+ end
2049
+
2050
+ # PUT /passwords/:token
2051
+ # Sets the password, clears a lockout and ends every session of the
2052
+ # user (their Session rows): each browser signs in again, with the new
2053
+ # password.
2054
+ def update
2055
+ token = params[:token].to_s
2056
+ user = User.find_by_password_reset_token(token)
2057
+ if user.nil?
2058
+ invalid_link
2059
+ else
2060
+ user.password = params[:password].to_s
2061
+ user.password_confirmation = params[:password_confirmation].to_s
2062
+ @WITHDRAW_ON_RESET@
2063
+ if user.save
2064
+ user.clear_failed_attempts!
2065
+ @CONFIRM_ON_RESET@
2066
+ Session.where(user_id: user.id).delete_all
2067
+ flash[:notice] = t(".updated")
2068
+ redirect_to new_session_path, status: :see_other
2069
+ else
2070
+ flash[:alert] = user.errors.full_messages.join(" ")
2071
+ redirect_to edit_password_path(token), status: :see_other
2072
+ end
2073
+ end
2074
+ end
2075
+
2076
+ private
2077
+
2078
+ # The link in the mail: mail_link_base (the Authentication concern's)
2079
+ # and the form's path; "" when there is no safe base, and then no mail
2080
+ # is sent.
2081
+ def edit_password_url_for(token)
2082
+ base = mail_link_base("password reset")
2083
+ return "" if base.empty?
2084
+
2085
+ path = edit_password_path(token)
2086
+ base + path
2087
+ end
2088
+
2089
+ # Queues the mail. An address the mailer refuses (a space or a
2090
+ # non-ASCII byte: Cybertrain::Mailer.check_address) is logged, and
2091
+ # the answer stays the one every other address gets.
2092
+ def queue_reset_mail(mail)
2093
+ mail.deliver_later
2094
+ nil
2095
+ rescue ArgumentError => e
2096
+ Cybertrain.logger.error("password reset mail not sent: #{e.message}")
2097
+ nil
2098
+ end
2099
+
2100
+ # Browsers send no Referer from the link's page, whose address holds
2101
+ # the token.
2102
+ def no_referrer
2103
+ response.set_header("Referrer-Policy", "no-referrer")
2104
+ nil
2105
+ end
2106
+
2107
+ # A token that is wrong, expired or spent: back to the address form.
2108
+ # Not an action, so its key is written in full (edit's).
2109
+ def invalid_link
2110
+ flash[:alert] = t("passwords.edit.invalid")
2111
+ redirect_to new_password_path, status: :see_other
2112
+ nil
2113
+ end
2114
+
2115
+ # What a client past the rate limit gets (the key is create's).
2116
+ def rate_limited
2117
+ flash[:alert] = t("passwords.create.rate_limited")
2118
+ redirect_to new_password_path, status: :see_other
2119
+ nil
2120
+ end
2121
+ end
2122
+ RUBY
2123
+ chunk = margin("# The link went to email_address: a reset proves that mailbox, as a\n" \
2124
+ "# confirmation link does (--confirmable). A new address waiting\n" \
2125
+ "# (unconfirmed_email) is not confirmed: that takes its own link.\n" \
2126
+ "user.update_columns(confirmed_at: Time.current) unless user.confirmed?\n", 8)
2127
+ withdraw = margin("# A new address waiting (unconfirmed_email) is withdrawn, and with it\n" \
2128
+ "# its link (the token is bound to it): whoever asked for it may be\n" \
2129
+ "# the one the owner is taking the account back from.\n" \
2130
+ "user.unconfirmed_email = nil\n", 6)
2131
+ text = splice(text, "@WITHDRAW_ON_RESET@", confirmable ? withdraw : "")
2132
+ splice(text, "@CONFIRM_ON_RESET@", confirmable ? chunk : "")
2133
+ end
2134
+
2135
+ # app/mailers/passwords_mailer.rb. `reset` takes the link as well as
2136
+ # the user (Rails' takes the user alone): the base URL may be the
2137
+ # request's (mail_link_base), and a mailer has no request.
2138
+ def self.passwords_mailer
2139
+ <<~'RUBY'
2140
+ # The password reset mail (cybertrain generate authentication): its HTML is
2141
+ # app/views/mail/_password_reset.html.erb, its subject and text come from
2142
+ # the dictionary (passwords_mailer.reset.subject, mail.password_reset.*),
2143
+ # in the locale of the request that asked for it.
2144
+ #
2145
+ # Written by the generator; it is yours to change.
2146
+ module PasswordsMailer
2147
+ # The mail to user with url, the link PasswordsController#create built (a
2148
+ # mailer has no request to take the site's address from). Its sender is
2149
+ # Config#smtp_from (CYBERTRAIN_SMTP_FROM).
2150
+ def self.reset(user, url)
2151
+ address = user.email_address.to_s
2152
+ html = Cybertrain::Views.render_mail("mail/password_reset", user: user, url: url)
2153
+ greeting = I18n.t("mail.password_reset.greeting", { email_address: address })
2154
+ text = +""
2155
+ text << greeting << "\n\n"
2156
+ text << I18n.t("mail.password_reset.intro") << "\n" << url << "\n\n"
2157
+ text << I18n.t("mail.password_reset.ignore") << "\n"
2158
+ subject = I18n.t("passwords_mailer.reset.subject")
2159
+ Cybertrain::MailMessage.new(to: address, subject: subject, body: text, html: html)
2160
+ end
2161
+ end
2162
+ RUBY
2163
+ end
2164
+
2165
+ def self.passwords_new_view
2166
+ <<~ERB
2167
+ <h1><%= t(".title") %></h1>
2168
+
2169
+ <%= form_with(url: passwords_path) do |f| %>
2170
+ <div class="field">
2171
+ <%= f.label :email_address, t("activerecord.attributes.user.email_address") %>
2172
+ <%= f.email_field :email_address, autocomplete: "username", autofocus: true %>
2173
+ </div>
2174
+
2175
+ <div class="actions">
2176
+ <%= f.submit t(".submit") %>
2177
+ </div>
2178
+ <% end %>
2179
+
2180
+ <p><%= link_to t(".sign_in"), new_session_path %></p>
2181
+ ERB
2182
+ end
2183
+
2184
+ def self.passwords_edit_view
2185
+ <<~ERB
2186
+ <h1><%= t(".title") %></h1>
2187
+
2188
+ <%= form_with(url: password_path(@token), method: :put) do |f| %>
2189
+ <div class="field">
2190
+ <%= f.label :password, t("activerecord.attributes.user.password") %>
2191
+ <%= f.password_field :password, autocomplete: "new-password", autofocus: true %>
2192
+ </div>
2193
+
2194
+ <div class="field">
2195
+ <%= f.label :password_confirmation, t("activerecord.attributes.user.password_confirmation") %>
2196
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
2197
+ </div>
2198
+
2199
+ <div class="actions">
2200
+ <%= f.submit t(".submit") %>
2201
+ </div>
2202
+ <% end %>
2203
+ ERB
2204
+ end
2205
+
2206
+ # The mail's HTML (Views.render_mail); its lazy keys are
2207
+ # mail.password_reset.* (D8).
2208
+ def self.password_reset_mail_view
2209
+ <<~ERB
2210
+ <%# locals: (user:, url:) %>
2211
+ <p><%= t(".greeting", email_address: user.email_address) %></p>
2212
+ <p><%= t(".intro") %></p>
2213
+ <p><%= link_to t(".link"), url %></p>
2214
+ <p><%= t(".ignore") %></p>
2215
+ ERB
2216
+ end
2217
+
2218
+ # ---- --confirmable --------------------------------------------------
2219
+
2220
+ # app/controllers/confirmations_controller.rb: the mail's link, and the
2221
+ # form that sends it again (the same answer for any address, after
2222
+ # the same work, as the password reset's address form).
2223
+ def self.confirmations_controller
2224
+ <<~'RUBY'
2225
+ # Confirming an email address (cybertrain generate authentication
2226
+ # --confirmable): the link a confirmation mail carries
2227
+ # (ConfirmationsMailer), which confirms a new account's address or puts
2228
+ # a new address in the old one's place, and the form that mails the link
2229
+ # again. The link's token (User#confirmation_token) is signed, lasts
2230
+ # three days (User::CONFIRMATION_TOKEN_TTL) and works once. Opening the
2231
+ # link signs nobody in: the user then signs in with the password. The
2232
+ # form answers the same whether or not the address is registered, or
2233
+ # confirmed already.
2234
+ #
2235
+ # Written by the generator; it is yours to change.
2236
+ class ConfirmationsController < ApplicationController
2237
+ allow_unauthenticated_access
2238
+ # Ten requests per client address every three minutes, as for signing in.
2239
+ rate_limit to: 10, within: 3 * 60, only: [:create], with: :rate_limited
2240
+ # The link's page carries the token in its address: no Referer for it.
2241
+ before_action :no_referrer, only: [:show]
2242
+
2243
+ # GET /confirmations/new
2244
+ def new_action
2245
+ end
2246
+
2247
+ # POST /confirmations
2248
+ # A new link for an account whose address is not confirmed yet. Any
2249
+ # other address (no account's, or one confirmed already) gets the same
2250
+ # answer after the same work (a token, the mail rendered), short of
2251
+ # queueing the mail.
2252
+ def create
2253
+ address = User.normalize_email_address(params[:email_address].to_s)
2254
+ user = User.find_by(email_address: address)
2255
+ if user.nil? || user.confirmed?
2256
+ token = Cybertrain::Token.issue("confirmation", 1, User::CONFIRMATION_TOKEN_TTL, address)
2257
+ send_confirmation_mail(User.new(email_address: address), token, false)
2258
+ else
2259
+ token = user.confirmation_token
2260
+ send_confirmation_mail(user, token, true)
2261
+ end
2262
+ flash[:notice] = t(".sent")
2263
+ redirect_to new_session_path, status: :see_other
2264
+ end
2265
+
2266
+ # GET /confirmations/:token
2267
+ # Confirms the address (User#confirm), unless another account has
2268
+ # taken it since; signs nobody in.
2269
+ def show
2270
+ user = User.find_by_confirmation_token(params[:token].to_s)
2271
+ if user.nil?
2272
+ invalid_link
2273
+ elsif user.confirm
2274
+ flash[:notice] = t(".confirmed")
2275
+ redirect_to after_confirmation_path, status: :see_other
2276
+ else
2277
+ flash[:alert] = t(".taken")
2278
+ redirect_to after_confirmation_path, status: :see_other
2279
+ end
2280
+ end
2281
+
2282
+ private
2283
+
2284
+ # A browser signed in already (a new address, confirmed from the
2285
+ # account page's browser) goes back to the account page; any other to
2286
+ # the sign-in page.
2287
+ def after_confirmation_path
2288
+ authenticated? ? edit_account_path : new_session_path
2289
+ end
2290
+
2291
+ # Browsers send no Referer from the link's page, whose address holds
2292
+ # the token.
2293
+ def no_referrer
2294
+ response.set_header("Referrer-Policy", "no-referrer")
2295
+ nil
2296
+ end
2297
+
2298
+ # A token that is wrong, expired or used: to the form that mails a new
2299
+ # link. Not an action, so its key is written in full (show's).
2300
+ def invalid_link
2301
+ flash[:alert] = t("confirmations.show.invalid")
2302
+ redirect_to new_confirmation_path, status: :see_other
2303
+ nil
2304
+ end
2305
+
2306
+ # What a client past the rate limit gets (the key is create's).
2307
+ def rate_limited
2308
+ flash[:alert] = t("confirmations.create.rate_limited")
2309
+ redirect_to new_confirmation_path, status: :see_other
2310
+ nil
2311
+ end
2312
+ end
2313
+ RUBY
2314
+ end
2315
+
2316
+ # app/mailers/confirmations_mailer.rb: as PasswordsMailer, the link
2317
+ # given (the concern's send_confirmation_mail builds it).
2318
+ def self.confirmations_mailer
2319
+ <<~'RUBY'
2320
+ # The confirmation mail (cybertrain generate authentication --confirmable):
2321
+ # its HTML is app/views/mail/_confirmation.html.erb, its subject and text
2322
+ # come from the dictionary (confirmations_mailer.confirmation_instructions.subject,
2323
+ # mail.confirmation.*), in the locale of the request that asked for it.
2324
+ #
2325
+ # Written by the generator; it is yours to change.
2326
+ module ConfirmationsMailer
2327
+ # The mail with url, the link that confirms user's address: the new one
2328
+ # waiting (unconfirmed_email) when there is one, else the account's own.
2329
+ # It goes to that address. Its sender is Config#smtp_from
2330
+ # (CYBERTRAIN_SMTP_FROM).
2331
+ def self.confirmation_instructions(user, url)
2332
+ pending = user.unconfirmed_email.to_s
2333
+ address = pending.empty? ? user.email_address.to_s : pending
2334
+ html = Cybertrain::Views.render_mail("mail/confirmation", address: address, url: url)
2335
+ greeting = I18n.t("mail.confirmation.greeting", { email_address: address })
2336
+ text = +""
2337
+ text << greeting << "\n\n"
2338
+ text << I18n.t("mail.confirmation.intro") << "\n" << url << "\n\n"
2339
+ text << I18n.t("mail.confirmation.ignore") << "\n"
2340
+ subject = I18n.t("confirmations_mailer.confirmation_instructions.subject")
2341
+ Cybertrain::MailMessage.new(to: address, subject: subject, body: text, html: html)
2342
+ end
2343
+ end
2344
+ RUBY
2345
+ end
2346
+
2347
+ def self.confirmations_new_view
2348
+ <<~ERB
2349
+ <h1><%= t(".title") %></h1>
2350
+
2351
+ <p><%= t(".intro") %></p>
2352
+
2353
+ <%= form_with(url: confirmations_path) do |f| %>
2354
+ <div class="field">
2355
+ <%= f.label :email_address, t("activerecord.attributes.user.email_address") %>
2356
+ <%= f.email_field :email_address, autocomplete: "username", autofocus: true %>
2357
+ </div>
2358
+
2359
+ <div class="actions">
2360
+ <%= f.submit t(".submit") %>
2361
+ </div>
2362
+ <% end %>
2363
+
2364
+ <p><%= link_to t(".sign_in"), new_session_path %></p>
2365
+ ERB
2366
+ end
2367
+
2368
+ # The mail's HTML (Views.render_mail); its lazy keys are
2369
+ # mail.confirmation.* (D8).
2370
+ def self.confirmation_mail_view
2371
+ <<~ERB
2372
+ <%# locals: (address:, url:) %>
2373
+ <p><%= t(".greeting", email_address: address) %></p>
2374
+ <p><%= t(".intro") %></p>
2375
+ <p><%= link_to t(".link"), url %></p>
2376
+ <p><%= t(".ignore") %></p>
2377
+ ERB
2378
+ end
2379
+
2380
+ # ---- the account page ---------------------------------------------
2381
+
2382
+ # app/controllers/accounts_controller.rb: the signed-in user's own
2383
+ # page. Every change asks for the current password; a wrong one is
2384
+ # rate limited per client address as a sign-in is, and per user (it
2385
+ # does not count toward the lockout, which guards signing in). A new
2386
+ # password restarts this browser's session through
2387
+ # start_new_session_for with the row's own remember flag, so "keep me
2388
+ # signed in" survives it (pre-flight finding 9). With `confirmable` a
2389
+ # new address waits in unconfirmed_email for the link mailed to it.
2390
+ def self.accounts_controller(confirmable = false)
2391
+ text = <<~'RUBY'
2392
+ # The signed-in user's account (cybertrain generate authentication): a new
2393
+ # email address, a new password, or both, each only with the current
2394
+ # password; and the account deleted, also only with the password.
2395
+ #
2396
+ # Written by the generator; it is yours to change.
2397
+ class AccountsController < ApplicationController
2398
+ # Ten changes or deletions per client address every three minutes, as for
2399
+ # signing in, and ten per user whatever the address (account_key): a
2400
+ # current password is guessed here no faster than there, from one
2401
+ # address or from many.
2402
+ rate_limit to: 10, within: 3 * 60, only: [:update, :destroy], with: :rate_limited
2403
+ rate_limit to: 10, within: 3 * 60, only: [:update, :destroy], by: :account_key, name: "user", with: :rate_limited
2404
+ before_action :set_user
2405
+
2406
+ # GET /account/edit
2407
+ def edit
2408
+ end
2409
+
2410
+ # PATCH/PUT /account
2411
+ # The current password first, for any change.
2412
+ @ADDRESS_COMMENT@
2413
+ # A new password ends every other session of the user and starts this
2414
+ # browser's again (restart_sessions). A new password or address ends
2415
+ # every password reset link sent before (they are bound to both).
2416
+ def update
2417
+ fields = params.expect(user: [:current_password, :email_address, :password, :password_confirmation])
2418
+ digest = @user.password_digest
2419
+ if @user.authenticate(fields["current_password"].to_s)
2420
+ # What authenticate left saved: digest, or a new hash of the same
2421
+ # password when the cost was raised (User#authenticate).
2422
+ verified = @user.password_digest
2423
+ @ADDRESS@
2424
+ password = fields["password"].to_s
2425
+ unless password.empty?
2426
+ @user.password = password
2427
+ @user.password_confirmation = fields["password_confirmation"].to_s
2428
+ end
2429
+ if @user.save
2430
+ restart_sessions if @user.password_digest != digest
2431
+ @SAVED@
2432
+ redirect_to edit_account_path, status: :see_other
2433
+ else
2434
+ # A new hash saved by authenticate stays: this browser's key
2435
+ # follows it, or the browser would be signed out next time.
2436
+ session[:password_key] = Cybertrain::Password.session_key(verified) if verified != digest
2437
+ render :edit, status: :unprocessable_entity
2438
+ end
588
2439
  else
589
- start_new_session_for(user)
590
- redirect_to after_authentication_url, status: :see_other
2440
+ flash.now[:alert] = t(".wrong_password")
2441
+ render :edit, status: :unprocessable_entity
591
2442
  end
592
2443
  end
593
2444
 
594
- # DELETE /session
2445
+ # DELETE /account
2446
+ # With the password: the user's sessions (every browser's) and the user
2447
+ # are deleted together, and this browser's cookie session is emptied.
2448
+ # When the database refuses (a row of another table still refers to
2449
+ # the user), nothing is deleted and the page says so.
595
2450
  def destroy
596
- terminate_session
597
- flash[:notice] = "You have been signed out."
598
- redirect_to new_session_path, status: :see_other
2451
+ if @user.authenticate(params[:password].to_s)
2452
+ if delete_user_and_sessions
2453
+ terminate_session
2454
+ flash[:notice] = t(".deleted")
2455
+ redirect_to "/", status: :see_other
2456
+ else
2457
+ flash.now[:alert] = t(".not_deleted")
2458
+ render :edit, status: :unprocessable_entity
2459
+ end
2460
+ else
2461
+ flash.now[:alert] = t(".wrong_password")
2462
+ render :edit, status: :unprocessable_entity
2463
+ end
599
2464
  end
600
- end
601
- RUBY
602
- end
2465
+ @CANCEL_EMAIL_CHANGE@
603
2466
 
604
- def self.registrations_controller
605
- <<~RUBY
606
- # Sign up (cybertrain generate authentication). Rails' generator has no
607
- # sign-up page and expects the first user to be created in the console;
608
- # cybertrain has no console, so this is how the first user gets in.
609
- # Delete it (and its routes) for an invitation-only application.
610
- class RegistrationsController < ApplicationController
611
- allow_unauthenticated_access only: [:new, :create]
2467
+ private
612
2468
 
613
- # GET /sign_up
614
- def new_action
615
- @user = User.new
2469
+ # A copy of the signed-in user for the forms, so that a change that does
2470
+ # not pass leaves @current_user, which the nav shows, as it is.
2471
+ def set_user
2472
+ @user = User.find(@current_user.id)
2473
+ @PENDING@
616
2474
  end
617
2475
 
618
- # POST /sign_up
619
- def create
620
- fields = params.require(:user)
621
- @user = User.new(fields.permit(:email_address))
622
- @user.password = fields[:password].to_s
623
- @user.password_confirmation = fields[:password_confirmation].to_s
624
- if @user.save
625
- start_new_session_for(@user)
626
- flash[:notice] = "Welcome! You have signed up."
627
- redirect_to after_authentication_url, status: :see_other
628
- else
629
- render :new, status: :unprocessable_entity
2476
+ # The second rate limit's key: the signed-in user's id
2477
+ # (require_authentication has run first).
2478
+ def account_key
2479
+ @current_user.id.to_s
2480
+ end
2481
+
2482
+ # After a new password: every Session row of the user ends, the other
2483
+ # browsers' and this one's, and this browser signs in again at once with
2484
+ # the new password key, remembered ("keep me signed in") as it was.
2485
+ def restart_sessions
2486
+ current = @current_session
2487
+ remember = current.nil? ? false : current.remember
2488
+ Session.where(user_id: @user.id).delete_all
2489
+ start_new_session_for(@user, remember: remember)
2490
+ nil
2491
+ end
2492
+
2493
+ # The user's Session rows and the user, in one transaction: true once
2494
+ # both are gone. When the database refuses the delete (a foreign key
2495
+ # from another table: give that association a `dependent:`), both
2496
+ # stay, so this browser stays signed in, and the log says why.
2497
+ def delete_user_and_sessions
2498
+ user = @user
2499
+ User.transaction do |c|
2500
+ Session.where(user_id: user.id).delete_all
2501
+ user.destroy
630
2502
  end
2503
+ true
2504
+ rescue Cybertrain::DB::Error => e
2505
+ Cybertrain.logger.error("account not deleted: #{e.message}")
2506
+ false
2507
+ end
2508
+
2509
+ # What a client past the rate limit gets (the key is update's).
2510
+ def rate_limited
2511
+ flash[:alert] = t("accounts.update.rate_limited")
2512
+ redirect_to edit_account_path, status: :see_other
2513
+ nil
631
2514
  end
632
2515
  end
633
2516
  RUBY
2517
+ if confirmable
2518
+ text = splice(text, "@ADDRESS_COMMENT@", " # A new address waits for the link mailed to it, and takes the old\n" \
2519
+ " # one's place once that is opened (ConfirmationsController#show).\n")
2520
+ text = splice(text, "@ADDRESS@", accounts_pending_address_lines)
2521
+ text = splice(text, "@SAVED@", accounts_pending_address_saved_lines)
2522
+ text = splice(text, "@CANCEL_EMAIL_CHANGE@", accounts_cancel_email_change)
2523
+ return splice(text, "@PENDING@", " # The new address waiting, as saved: the page shows it.\n" \
2524
+ " @pending_email = @user.unconfirmed_email.to_s\n")
2525
+ end
2526
+ text = splice(text, "@ADDRESS_COMMENT@", " # A new address takes effect at once.\n")
2527
+ text = splice(text, "@ADDRESS@", margin("@user.email_address = fields[\"email_address\"].to_s if fields.key?(\"email_address\")\n", 6))
2528
+ text = splice(text, "@SAVED@", margin("flash[:notice] = t(\".updated\")\n", 8))
2529
+ text = splice(text, "@CANCEL_EMAIL_CHANGE@", "")
2530
+ splice(text, "@PENDING@", "")
634
2531
  end
635
2532
 
636
- # With --invite-only there is no sign-up page to link to.
637
- def self.sessions_new_view(invite_only = false)
638
- view = <<~ERB
639
- <h1>Sign in</h1>
640
-
641
- <%= form_with(url: session_path) do |f| %>
642
- <div class="field">
643
- <%= f.label :email_address %>
644
- <%= f.email_field :email_address, autocomplete: "username", autofocus: true %>
645
- </div>
646
-
647
- <div class="field">
648
- <%= f.label :password %>
649
- <%= f.password_field :password, autocomplete: "current-password" %>
650
- </div>
651
-
652
- <div class="actions">
653
- <%= f.submit "Sign in" %>
654
- </div>
655
- <% end %>
656
- ERB
657
- return view if invite_only
2533
+ # --confirmable's action that withdraws the new address waiting.
2534
+ def self.accounts_cancel_email_change
2535
+ indent(<<~'RUBY')
2536
+
2537
+ # DELETE /account/pending_email
2538
+ # Withdraws the new address waiting (a mistyped one, say): its link stops
2539
+ # working, as the token is bound to unconfirmed_email. No password is
2540
+ # asked: withdrawing only keeps the account where it is. A new password
2541
+ # on this page leaves the address waiting as it was; this and a
2542
+ # password reset (PasswordsController#update) end it.
2543
+ def cancel_email_change
2544
+ @user.update_columns(unconfirmed_email: nil)
2545
+ flash[:notice] = t(".cancelled")
2546
+ redirect_to edit_account_path, status: :see_other
2547
+ end
2548
+ RUBY
2549
+ end
658
2550
 
659
- "#{view}\n<p><%= link_to \"Sign up\", sign_up_path %></p>\n"
2551
+ # --confirmable's AccountsController#update: a new address goes into
2552
+ # unconfirmed_email (the address in use is no change).
2553
+ def self.accounts_pending_address_lines
2554
+ margin(<<~'RUBY', 6)
2555
+ address_changed = false
2556
+ if fields.key?("email_address")
2557
+ address = User.normalize_email_address(fields["email_address"].to_s)
2558
+ # The address in use, sent back as the form fills it in, is no change:
2559
+ # a new address waiting stays.
2560
+ unless address == @user.email_address
2561
+ @user.request_email_change(address)
2562
+ address_changed = true
2563
+ end
2564
+ end
2565
+ RUBY
660
2566
  end
661
2567
 
662
- def self.nav_partial
663
- <<~ERB
664
- <%# locals: () %>
665
- <nav class="session">
666
- <% if @current_user %>
667
- <span><%= @current_user.email_address %></span>
668
- <%= button_to "Sign out", session_path, method: :delete %>
669
- <% else %>
670
- <%= link_to "Sign in", new_session_path %>
671
- <% end %>
672
- </nav>
673
- ERB
2568
+ # ...and, once saved, the link to it by mail.
2569
+ def self.accounts_pending_address_saved_lines
2570
+ margin(<<~'RUBY', 8)
2571
+ if address_changed
2572
+ token = @user.confirmation_token
2573
+ send_confirmation_mail(@user, token, true)
2574
+ flash[:notice] = t(".confirm")
2575
+ else
2576
+ flash[:notice] = t(".updated")
2577
+ end
2578
+ RUBY
674
2579
  end
675
2580
 
676
- def self.registrations_new_view
677
- <<~ERB
678
- <h1>Sign up</h1>
2581
+ # Two forms: the details (address, new password, current password)
2582
+ # and the deletion (the password); with `confirmable`, the new address
2583
+ # waiting for its confirmation under the address field.
2584
+ def self.accounts_edit_view(confirmable = false)
2585
+ text = <<~ERB
2586
+ <h1><%= t(".title") %></h1>
679
2587
 
680
- <%= form_with(model: @user, url: sign_up_path) do |f| %>
2588
+ <%= form_with(model: @user, url: account_path) do |f| %>
681
2589
  <% if @user.errors.any? %>
682
2590
  <div id="error_explanation">
683
- <h2><%= pluralize(@user.errors.count, "error") %> prohibited this account from being created:</h2>
2591
+ <h2><%= t("errors.template.header", count: @user.errors.count, model: t(".model")) %></h2>
684
2592
  <ul>
685
2593
  <% @user.errors.full_messages.each do |message| %>
686
2594
  <li><%= message %></li>
@@ -692,11 +2600,13 @@ module Cybertrain
692
2600
  <div class="field">
693
2601
  <%= f.label :email_address %>
694
2602
  <%= f.email_field :email_address, autocomplete: "username" %>
2603
+ @PENDING_HINT@
695
2604
  </div>
696
2605
 
697
2606
  <div class="field">
698
- <%= f.label :password %>
2607
+ <%= f.label :password, t(".new_password") %>
699
2608
  <%= f.password_field :password, autocomplete: "new-password" %>
2609
+ <p class="hint"><%= t(".password_hint") %></p>
700
2610
  </div>
701
2611
 
702
2612
  <div class="field">
@@ -704,21 +2614,52 @@ module Cybertrain
704
2614
  <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
705
2615
  </div>
706
2616
 
2617
+ <div class="field">
2618
+ <%= f.label :current_password %>
2619
+ <%= f.password_field :current_password, autocomplete: "current-password", required: true %>
2620
+ </div>
2621
+
2622
+ <div class="actions">
2623
+ <%= f.submit t(".submit") %>
2624
+ </div>
2625
+ <% end %>
2626
+ @CANCEL_PENDING_BUTTON@
2627
+
2628
+ <h2><%= t(".delete_title") %></h2>
2629
+ <p><%= t(".delete_intro") %></p>
2630
+
2631
+ <%= form_with(url: account_path, method: :delete) do |f| %>
2632
+ <div class="field">
2633
+ <%= f.label :password, t("activerecord.attributes.user.current_password") %>
2634
+ <%= f.password_field :password, autocomplete: "current-password", required: true %>
2635
+ </div>
2636
+
707
2637
  <div class="actions">
708
- <%= f.submit "Sign up" %>
2638
+ <%= f.submit t(".delete") %>
709
2639
  </div>
710
2640
  <% end %>
2641
+ ERB
2642
+ text = splice(text, "@PENDING_HINT@", confirmable ? accounts_pending_hint : "")
2643
+ button = "\n<% unless @pending_email.empty? %>\n" \
2644
+ " <p><%= button_to t(\".cancel_pending\"), account_pending_email_path, method: :delete %></p>\n<% end %>\n"
2645
+ splice(text, "@CANCEL_PENDING_BUTTON@", confirmable ? button : "")
2646
+ end
711
2647
 
712
- <p><%= link_to "Sign in", new_session_path %></p>
2648
+ def self.accounts_pending_hint
2649
+ margin(<<~'ERB', 4)
2650
+ <% unless @pending_email.empty? %>
2651
+ <p class="hint"><%= t(".pending", email_address: @pending_email) %></p>
2652
+ <% end %>
713
2653
  ERB
714
2654
  end
715
2655
 
716
2656
  # ---- --invite-only ------------------------------------------------
717
2657
 
718
- # The first user's page (--invite-only).
719
- def self.setup_controller(app)
2658
+ # The first user's page (--invite-only); with `confirmable` the user
2659
+ # it creates is confirmed, as nothing mails them.
2660
+ def self.setup_controller(app, confirmable = false)
720
2661
  env = setup_env(app)
721
- <<~RUBY
2662
+ text = <<~RUBY
722
2663
  # First-run setup (cybertrain generate authentication --invite-only):
723
2664
  # the form that creates the first user and signs them in. It answers
724
2665
  # only while no user exists, only with the one-time token the server
@@ -761,6 +2702,7 @@ module Cybertrain
761
2702
  @user = User.new(fields.permit(:email_address))
762
2703
  @user.password = fields[:password].to_s
763
2704
  @user.password_confirmation = fields[:password_confirmation].to_s
2705
+ @CONFIRMED_AT_CREATION@
764
2706
  # The no-user check and the insert are one write transaction
765
2707
  # (BEGIN IMMEDIATE takes the lock first), so two requests that
766
2708
  # both passed require_first_run cannot both create "the first"
@@ -771,7 +2713,7 @@ module Cybertrain
771
2713
  end
772
2714
  if saved
773
2715
  start_new_session_for(@user)
774
- flash[:notice] = "Welcome! Your account has been created."
2716
+ flash[:notice] = t(".welcome")
775
2717
  redirect_to "/", status: :see_other
776
2718
  else
777
2719
  render :new, status: :unprocessable_entity
@@ -799,22 +2741,23 @@ module Cybertrain
799
2741
  end
800
2742
  end
801
2743
  RUBY
2744
+ chunk = margin("# Nothing mails the first user a link: the address counts as\n" \
2745
+ "# confirmed (--confirmable).\n@user.confirmed_at = Time.current\n", 4)
2746
+ splice(text, "@CONFIRMED_AT_CREATION@", confirmable ? chunk : "")
802
2747
  end
803
2748
 
804
2749
  def self.setup_new_view
805
2750
  <<~ERB
806
- <h1>Set up</h1>
2751
+ <h1><%= t(".title") %></h1>
807
2752
 
808
- <p>Create the first account. This page is only shown on this machine,
809
- with the link the server printed when it started, and only until an
810
- account exists.</p>
2753
+ <p><%= t(".intro") %></p>
811
2754
 
812
2755
  <%= form_with(model: @user, url: setup_path) do |f| %>
813
2756
  <input type="hidden" name="token" value="<%= @setup_token %>">
814
2757
 
815
2758
  <% if @user.errors.any? %>
816
2759
  <div id="error_explanation">
817
- <h2><%= pluralize(@user.errors.count, "error") %> prohibited this account from being created:</h2>
2760
+ <h2><%= t("errors.template.header", count: @user.errors.count, model: t(".model")) %></h2>
818
2761
  <ul>
819
2762
  <% @user.errors.full_messages.each do |message| %>
820
2763
  <li><%= message %></li>
@@ -839,37 +2782,68 @@ module Cybertrain
839
2782
  </div>
840
2783
 
841
2784
  <div class="actions">
842
- <%= f.submit "Create account" %>
2785
+ <%= f.submit t(".submit") %>
843
2786
  </div>
844
2787
  <% end %>
845
2788
  ERB
846
2789
  end
847
2790
 
848
- # app/commands/user_command.rb (--invite-only): the `user` command and
849
- # the boot warning, required from bin/<app>.rb (and from the app's
850
- # test, which runs the command through Main.run).
851
- def self.user_command(app)
852
- <<~RUBY
853
- # `./#{app} user EMAIL [PASSWORD]` (cybertrain generate authentication
854
- # --invite-only): creates the user with this address, or sets the
855
- # password of the one that has it (which signs that user's browsers
856
- # out: their sessions' password key no longer matches). Without
857
- # PASSWORD it is read from standard input, one line, so that it stays
858
- # out of `ps` and the shell history:
2791
+ # app/commands/user_command.rb: the `user` command, required from
2792
+ # bin/<app>.rb (and from the app's tests, which run it). With
2793
+ # --invite-only it also holds the boot warning, which names /setup's
2794
+ # token; a sign-up app has no SetupController to name.
2795
+ def self.user_command(app, invite_only = false, confirmable = false)
2796
+ head = user_command_head(app, invite_only, confirmable)
2797
+ warning = invite_only ? user_command_warning(app) : ""
2798
+ tail = <<~RUBY
2799
+ end
2800
+
2801
+ Cybertrain::Main.command("user", "EMAIL [PASSWORD] | admin EMAIL | unadmin EMAIL: create a user or set its password, or grant or revoke admin") do |argv|
2802
+ UserCommand.run(argv)
2803
+ end
2804
+ RUBY
2805
+ join_three(head, warning, tail)
2806
+ end
2807
+
2808
+ # The command's file up to the end of its last method, in both modes;
2809
+ # with `confirmable` a user it creates is confirmed, as nothing mails
2810
+ # them (pre-flight finding 6).
2811
+ def self.user_command_head(app, invite_only, confirmable = false)
2812
+ mode = invite_only ? " --invite-only" : ""
2813
+ warned = invite_only ? ", which also calls UserCommand.warn_if_no_user before serving" : ""
2814
+ text = <<~RUBY
2815
+ # `./#{app} user EMAIL [PASSWORD]` (cybertrain generate authentication#{mode}):
2816
+ # creates the user with this address, or sets the password of the one
2817
+ # that has it (which signs that user's browsers out: their sessions'
2818
+ # password key no longer matches; and clears a lockout, User#locked?).
2819
+ # Without PASSWORD it is read from
2820
+ # standard input, one line, so that it stays out of `ps` and the shell
2821
+ # history:
859
2822
  #
860
2823
  # ./#{app} user ann@example.com # type it, then Enter (it is echoed)
861
2824
  # printf '%s' "$PASSWORD" | ./#{app} user ann@example.com
862
2825
  #
2826
+ # `./#{app} user admin EMAIL` makes that user an admin (User#admin?, which
2827
+ # the Authentication concern's require_admin asks for: the jobs page),
2828
+ # `./#{app} user unadmin EMAIL` makes them an ordinary user again.
2829
+ #
863
2830
  # Registered with Cybertrain::Main.command, which connects the database
864
- # first (README, "Application commands"). Required by bin/#{app}.rb,
865
- # which also calls UserCommand.warn_if_no_user before serving.
2831
+ # first. Required by bin/#{app}.rb#{warned}.
866
2832
  # Written by the generator; it is yours to change.
867
2833
  module UserCommand
868
- USAGE = "usage: ./#{app} user EMAIL [PASSWORD] (without PASSWORD, it is read from standard input)"
2834
+ USAGE = "usage: ./#{app} user EMAIL [PASSWORD] (without PASSWORD, it is read from standard input) | ./#{app} user admin EMAIL | ./#{app} user unadmin EMAIL"
869
2835
 
870
- # The exit status: 0 when the user was created or updated, 1 for bad
871
- # arguments, an empty password or a record that does not validate.
2836
+ # The exit status: 0 when the user was created, updated or made an
2837
+ # admin or not, 1 for bad arguments, an empty password, an unknown
2838
+ # address (admin, unadmin) or a record that does not validate.
872
2839
  def self.run(argv)
2840
+ if !argv.empty? && (argv[0] == "admin" || argv[0] == "unadmin")
2841
+ if argv.size != 2
2842
+ puts USAGE
2843
+ return 1
2844
+ end
2845
+ return UserCommand.grant_admin(argv[1], argv[0] == "admin")
2846
+ end
873
2847
  if argv.empty? || argv.size > 2 || argv[0].start_with?("-")
874
2848
  puts USAGE
875
2849
  return 1
@@ -885,14 +2859,38 @@ module Cybertrain
885
2859
  created = found.nil?
886
2860
  user = found.nil? ? User.new(email_address: address) : found
887
2861
  user.password = password
2862
+ @CONFIRMED_AT_CREATION@
888
2863
  unless user.save
889
2864
  user.errors.full_messages.each { |message| puts "error: \#{message}" }
890
2865
  return 1
891
2866
  end
2867
+ user.clear_failed_attempts!
892
2868
  puts created ? "created \#{address}" : "updated \#{address}"
893
2869
  0
894
2870
  end
895
2871
 
2872
+ # `user admin EMAIL` (granted) or `user unadmin EMAIL`: prints what
2873
+ # admin_change did and answers the exit status.
2874
+ def self.grant_admin(email, granted)
2875
+ line = UserCommand.admin_change(email, granted)
2876
+ puts line
2877
+ line.start_with?("error: ") ? 1 : 0
2878
+ end
2879
+
2880
+ # Sets the admin flag of the user with this address, who must exist,
2881
+ # and answers the line to print: "admin ann@example.com",
2882
+ # "unadmin ann@example.com" or "error: ...".
2883
+ def self.admin_change(email, granted)
2884
+ address = User.normalize_email_address(email)
2885
+ found = User.find_by(email_address: address)
2886
+ return "error: no user \#{address}" if found.nil?
2887
+
2888
+ found.admin = granted
2889
+ return "error: \#{found.errors.full_messages.join(", ")}" unless found.save
2890
+
2891
+ granted ? "admin \#{address}" : "unadmin \#{address}"
2892
+ end
2893
+
896
2894
  # One line of standard input, with a prompt when it is a terminal.
897
2895
  def self.read_password
898
2896
  if STDIN.tty?
@@ -911,44 +2909,77 @@ module Cybertrain
911
2909
  s = s[0, s.size - 1].to_s if s.end_with?("\\r")
912
2910
  s
913
2911
  end
2912
+ RUBY
2913
+ chunk = margin("# A user made here gets no mail with a link: the address counts as\n" \
2914
+ "# confirmed from the start (--confirmable).\nuser.confirmed_at = Time.current if created\n", 4)
2915
+ splice(text, "@CONFIRMED_AT_CREATION@", confirmable ? chunk : "")
2916
+ end
914
2917
 
915
- # Called by bin/#{app}.rb before the server boots: a [WARN] while no
916
- # user exists, which is while /setup is open, with the page's
917
- # one-time token (SetupController.setup_token, this process's own).
918
- # Says nothing when the users table is not there yet (`./#{app}
919
- # migrate` comes first).
920
- def self.warn_if_no_user
921
- Cybertrain.logger.warn("no user exists yet: run ./#{app} user EMAIL, or open /setup?token=\#{SetupController.setup_token} from this machine") if UserCommand.no_user?
922
- nil
923
- end
924
-
925
- # Connects for the question only: Application#boot connects the
926
- # server's own pool afterwards.
927
- def self.no_user?
928
- begin
929
- Cybertrain::DB.connect(Cybertrain.config.database_path, size: 1)
930
- !User.all.exists?
931
- rescue Cybertrain::DB::Error
932
- false
933
- ensure
934
- Cybertrain::DB.disconnect
935
- end
936
- end
2918
+ # --invite-only: the boot warning and the question it asks, indented
2919
+ # into the module.
2920
+ def self.user_command_warning(app)
2921
+ text = <<~RUBY
2922
+
2923
+ # Called by bin/#{app}.rb before the server boots: a [WARN] while no
2924
+ # user exists, which is while /setup is open, with the page's
2925
+ # one-time token (SetupController.setup_token, this process's own).
2926
+ # Says nothing when the users table is not there yet (`./#{app}
2927
+ # migrate` comes first).
2928
+ def self.warn_if_no_user
2929
+ Cybertrain.logger.warn("no user exists yet: run ./#{app} user EMAIL, or open /setup?token=\#{SetupController.setup_token} from this machine") if UserCommand.no_user?
2930
+ nil
937
2931
  end
938
2932
 
939
- Cybertrain::Main.command("user", "EMAIL [PASSWORD]: create a user or set its password") do |argv|
940
- UserCommand.run(argv)
2933
+ # Connects for the question only: Application#boot connects the
2934
+ # server's own pool afterwards.
2935
+ def self.no_user?
2936
+ begin
2937
+ Cybertrain::DB.connect(Cybertrain.config.database_path, size: 1)
2938
+ !User.all.exists?
2939
+ rescue Cybertrain::DB::Error
2940
+ false
2941
+ ensure
2942
+ Cybertrain::DB.disconnect
2943
+ end
941
2944
  end
942
2945
  RUBY
2946
+ indent(text)
943
2947
  end
944
2948
 
945
- # Inserted before the Main.run line of bin/<app>.rb (--invite-only).
946
- def self.bin_block(app)
2949
+ # Inserted before the Main.run line of bin/<app>.rb; with
2950
+ # --invite-only it also runs the boot warning.
2951
+ def self.bin_block(app, invite_only = false)
2952
+ if invite_only
2953
+ return <<~RUBY
2954
+ # `./#{app} user EMAIL [PASSWORD]`, `./#{app} user admin EMAIL` and
2955
+ # `./#{app} user unadmin EMAIL`, and a [WARN] at boot while no user exists
2956
+ # (cybertrain generate authentication --invite-only).
2957
+ #{COMMAND_REQUIRE}
2958
+ UserCommand.warn_if_no_user if Cybertrain::Main.server?(ARGV)
2959
+
2960
+ RUBY
2961
+ end
2962
+
947
2963
  <<~RUBY
948
- # `./#{app} user EMAIL [PASSWORD]`, and a [WARN] at boot while no user
949
- # exists (cybertrain generate authentication --invite-only).
2964
+ # `./#{app} user EMAIL [PASSWORD]`, `./#{app} user admin EMAIL` and
2965
+ # `./#{app} user unadmin EMAIL` (cybertrain generate authentication).
950
2966
  #{COMMAND_REQUIRE}
951
- UserCommand.warn_if_no_user if Cybertrain::Main.server?(ARGV)
2967
+
2968
+ RUBY
2969
+ end
2970
+
2971
+ # Inserted (indented) after the configure line of config/app.rb, in
2972
+ # both modes.
2973
+ def self.base_url_block(app)
2974
+ env = base_url_env(app)
2975
+ <<~RUBY
2976
+ # Links in mails (the password reset's) start with this, as in
2977
+ # #{env}=https://#{app}.example.com: set it, with https, wherever the
2978
+ # app is served. Unset, they take the address the request came to,
2979
+ # which is trusted only in development, in tests, or when
2980
+ # CYBERTRAIN_HOSTS lists the app's hosts; anywhere else a reset mail
2981
+ # is not sent and the log says why.
2982
+ c.setting_string :base_url, env: "#{env}", default: ""
952
2983
 
953
2984
  RUBY
954
2985
  end
@@ -967,11 +2998,25 @@ module Cybertrain
967
2998
  RUBY
968
2999
  end
969
3000
 
3001
+ # first + second + third through `<<` on locals: an interpolation of
3002
+ # three method calls could free one result while building the next
3003
+ # under Spinel (spikes/NOTES.md rule 65), and the CLI compiles there
3004
+ # too.
3005
+ def self.join_three(first, second, third)
3006
+ out = +""
3007
+ out << first << second << third
3008
+ out
3009
+ end
3010
+
970
3011
  # Inserted (indented) after the draw line of config/routes.rb.
971
- def self.routes_block(invite_only = false)
3012
+ def self.routes_block(invite_only = false, confirmable = false)
3013
+ confirmations = confirmable ? "#{CONFIRMATIONS_ROUTE}\n" : ""
3014
+ pending = confirmable ? "\n#{PENDING_EMAIL_ROUTE}" : ""
972
3015
  if invite_only
973
3016
  return <<~RUBY
974
3017
  resource :session, only: [:new, :create, :destroy]
3018
+ #{PASSWORDS_ROUTE}
3019
+ #{confirmations}#{ACCOUNT_ROUTE}#{pending}
975
3020
  get "/setup", to: "setup#new", as: "setup"
976
3021
  post "/setup", to: "setup#create"
977
3022
  RUBY
@@ -979,550 +3024,12 @@ module Cybertrain
979
3024
 
980
3025
  <<~RUBY
981
3026
  resource :session, only: [:new, :create, :destroy]
3027
+ #{PASSWORDS_ROUTE}
3028
+ #{confirmations}#{ACCOUNT_ROUTE}#{pending}
982
3029
  get "/sign_up", to: "registrations#new", as: "sign_up"
983
3030
  post "/sign_up", to: "registrations#create"
984
3031
  RUBY
985
3032
  end
986
-
987
- # ---- tests --------------------------------------------------------
988
-
989
- # The same shape as examples/blog/test/support/blog_test.rb: boots the
990
- # app on a fresh test database. Shared by every test file; copy
991
- # helpers into it as the app grows.
992
- def self.app_test_support
993
- <<~RUBY
994
- # Shared setup for the integration tests (test/*.rb): the app booted in
995
- # the test environment on a fresh storage/test.sqlite3. Required by the
996
- # test files, not run (`spin test` runs test/*.rb only).
997
- ENV["CYBERTRAIN_ENV"] = "test"
998
-
999
- require "cybertrain"
1000
- require "cybertrain/test/client"
1001
- require_relative "../../config/app"
1002
- require_relative "../../gen/app"
1003
- require_relative "../../gen/migrations"
1004
-
1005
- # No request log: `spin test` diffs the whole output against the
1006
- # snapshot, and "Completed 303 in 246ms" is never the same twice.
1007
- Cybertrain.config.log_level = :none
1008
-
1009
- # Webhooks and e-mail the app sends are received in-process: require
1010
- # "cybertrain/test/http_receiver" or "cybertrain/test/smtp_receiver",
1011
- # then `port = receiver.start`, point the app at 127.0.0.1:port
1012
- # (HttpClient needs `Cybertrain.config.http_allow_private = true`, the
1013
- # Mailer `tls: "none"`), and read `receiver.received_request` /
1014
- # `received_message` before `receiver.stop`. Every wait is bounded.
1015
-
1016
- module AppTest
1017
- # Deletes the test database (and its WAL files), migrates a new one
1018
- # and boots the application on it.
1019
- def self.boot
1020
- path = Cybertrain.config.database_path
1021
- [path, "\#{path}-wal", "\#{path}-shm"].each { |f| File.delete(f) if File.exist?(f) }
1022
- connection = Cybertrain::DB::Connection.new(path)
1023
- Cybertrain::DB::Migrator.new(connection).migrate(Cybertrain::Migration.all)
1024
- connection.close
1025
-
1026
- app = Cybertrain::Application.new(
1027
- router: Gen::Routes.build(Cybertrain::Router.new),
1028
- url_resolver: Gen::Routes.url_resolver
1029
- )
1030
- app.boot
1031
- end
1032
-
1033
- # The authenticity_token of the first form in the last response, as
1034
- # a browser would submit it back.
1035
- def self.form_token(client)
1036
- body = client.response.body
1037
- marker = "name=\\"authenticity_token\\" value=\\""
1038
- at = body.index(marker)
1039
- raise "no authenticity_token in the last response" if at.nil?
1040
-
1041
- start = at + marker.size
1042
- stop = body.index("\\"", start)
1043
- raise "unterminated authenticity_token" if stop.nil?
1044
-
1045
- body[start, stop - start].to_s
1046
- end
1047
-
1048
- # A user with this address and password (both normalized the way the
1049
- # forms are).
1050
- def self.user(email_address = "ann@example.com", password = "s3cr3t-s3cr3t")
1051
- user = User.new(email_address: email_address)
1052
- user.password = password
1053
- user.save!
1054
- user
1055
- end
1056
-
1057
- # Signs `client` in through the form, as a browser would. Every test
1058
- # client has the same address, so the sign-in rate limit's counts
1059
- # are forgotten first: a suite signs in far more than ten times.
1060
- def self.sign_in(client, email_address = "ann@example.com", password = "s3cr3t-s3cr3t")
1061
- Cybertrain::RateLimit.reset_all!
1062
- client.get("/session/new")
1063
- client.post("/session", { "authenticity_token" => form_token(client),
1064
- "email_address" => email_address,
1065
- "password" => password })
1066
- end
1067
- end
1068
-
1069
- APP = AppTest.boot
1070
- RUBY
1071
- end
1072
-
1073
- # test/authentication.rb: the head (requires, new_client, the sign-in
1074
- # form), the sign-up or first-run tests, then the sign-in and sign-out
1075
- # tests both variants share.
1076
- # The pieces go through locals and `<<`: an interpolation of three
1077
- # method calls could free one result while building the next under
1078
- # Spinel (spikes/NOTES.md rule 65), and the CLI compiles there too.
1079
- def self.authentication_test
1080
- head = authentication_test_head(false)
1081
- middle = sign_up_tests
1082
- join_three(head, middle, authentication_test_tail)
1083
- end
1084
-
1085
- # --invite-only's test/authentication.rb.
1086
- def self.invite_only_test(app)
1087
- head = authentication_test_head(true)
1088
- middle = setup_tests(app)
1089
- join_three(head, middle, authentication_test_tail)
1090
- end
1091
-
1092
- def self.join_three(first, second, third)
1093
- out = +""
1094
- out << first << second << third
1095
- out
1096
- end
1097
-
1098
- def self.authentication_test_head(invite_only)
1099
- what = invite_only ? "First-run setup, the user command, sign-in" : "Sign-up, sign-in"
1100
- command = invite_only ? "require_relative \"../app/commands/user_command\"\n" : ""
1101
- open_actions = invite_only ? "sign-in and setup" : "sign-in and sign-up"
1102
- link = if invite_only
1103
- 'refute res.body.include?("/sign_up")'
1104
- else
1105
- 'assert_includes res.body, "<a href=\"/sign_up\">Sign up</a>"'
1106
- end
1107
- <<~RUBY
1108
- # #{what} and sign-out through the full stack (session cookie,
1109
- # CSRF, method override, router). Run with `cybertrain spin test`; its
1110
- # snapshot comes from the compiled binary (the database is FFI):
1111
- # `script/regen-snapshot`-style, see README "Testing an app".
1112
- require_relative "support/app_test"
1113
- #{command}
1114
- def new_client
1115
- Session.all.delete_all
1116
- User.all.delete_all
1117
- Cybertrain::Test::Client.new(APP)
1118
- end
1119
-
1120
- # Every action but #{open_actions} needs a user: DELETE /session is
1121
- # the one such action this test can rely on before the app has pages
1122
- # of its own (a `root` route, a scaffold).
1123
- test "a visitor is sent to the sign-in page" do
1124
- client = new_client
1125
- client.get("/session/new")
1126
- res = client.post("/session", { "_method" => "delete", "authenticity_token" => AppTest.form_token(client) })
1127
- assert_redirected_to res, "/session/new"
1128
- assert_response res, :see_other
1129
- end
1130
-
1131
- test "GET /session/new renders the sign-in form" do
1132
- client = new_client
1133
- res = client.get("/session/new")
1134
- assert_response res, :ok
1135
- assert_includes res.body, "<h1>Sign in</h1>"
1136
- assert_includes res.body, "<form action=\\"/session\\" method=\\"post\\">"
1137
- assert_includes res.body, "name=\\"email_address\\""
1138
- assert_includes res.body, "type=\\"password\\" name=\\"password\\""
1139
- #{link}
1140
- end
1141
-
1142
- RUBY
1143
- end
1144
-
1145
- # --invite-only: /setup and `./<app> user` in place of the sign-up tests.
1146
- def self.setup_tests(app)
1147
- env = setup_env(app)
1148
- <<~RUBY
1149
- # The form /setup posts, filled in, with the page's one-time token
1150
- # in its hidden field.
1151
- def setup_form(authenticity_token, password, confirmation)
1152
- { "authenticity_token" => authenticity_token,
1153
- "token" => SetupController.setup_token,
1154
- "user[email_address]" => " Ann@Example.com ",
1155
- "user[password]" => password,
1156
- "user[password_confirmation]" => confirmation }
1157
- end
1158
-
1159
- # /setup with this process's token, the link the boot warning prints.
1160
- def setup_link
1161
- "/setup?token=\#{SetupController.setup_token}"
1162
- end
1163
-
1164
- # `./#{app} ARGS...` in-process. Main.run connects a pool of one for
1165
- # the command and disconnects it, so the tests' pool is connected
1166
- # again afterwards (the database file is the same).
1167
- def run_command(argv)
1168
- status = Cybertrain::Main.run("#{app}", argv, router: Gen::Routes.build(Cybertrain::Router.new),
1169
- url_resolver: Gen::Routes.url_resolver,
1170
- views: Cybertrain::Application.no_views)
1171
- reconnect
1172
- status
1173
- end
1174
-
1175
- def reconnect
1176
- Cybertrain::DB.connect(Cybertrain.config.database_path, size: Cybertrain.config.pool_size)
1177
- nil
1178
- end
1179
-
1180
- test "GET /setup with the token shows the form to this machine while no user exists" do
1181
- client = new_client
1182
- res = client.get(setup_link)
1183
- assert_response res, :ok
1184
- assert_includes res.body, "<h1>Set up</h1>"
1185
- assert_includes res.body, "<form action=\\"/setup\\" method=\\"post\\">"
1186
- assert_includes res.body, "<input type=\\"hidden\\" name=\\"token\\" value=\\"\#{SetupController.setup_token}\\">"
1187
- assert_includes res.body, "name=\\"user[password_confirmation]\\""
1188
- end
1189
-
1190
- test "/setup without the token, or with a wrong one, is a 404" do
1191
- client = new_client
1192
- assert_equal 32, SetupController.setup_token.size
1193
- res = client.get("/setup")
1194
- assert_response res, :not_found
1195
- res = client.get("/setup?token=")
1196
- assert_response res, :not_found
1197
- res = client.get("/setup?token=0123456789abcdef0123456789abcdef")
1198
- assert_response res, :not_found
1199
- res = client.get("/setup?token=\#{SetupController.setup_token}x")
1200
- assert_response res, :not_found
1201
- refute res.body.include?(SetupController.setup_token)
1202
- end
1203
-
1204
- test "/setup is a 404 to another machine, through a proxy, and once a user exists" do
1205
- client = new_client
1206
- client.peer_address = "203.0.113.7"
1207
- res = client.get(setup_link)
1208
- assert_response res, :not_found
1209
- client.peer_address = "127.0.0.1"
1210
- res = client.get(setup_link, { "x-forwarded-for" => "203.0.113.7" })
1211
- assert_response res, :not_found
1212
- res = client.get(setup_link)
1213
- assert_response res, :ok
1214
- AppTest.user
1215
- res = client.get(setup_link)
1216
- assert_response res, :not_found
1217
- end
1218
-
1219
- test "POST /setup from another machine, or without the token, creates nothing" do
1220
- client = new_client
1221
- client.get(setup_link)
1222
- authenticity_token = AppTest.form_token(client)
1223
- client.peer_address = "203.0.113.7"
1224
- res = client.post("/setup", setup_form(authenticity_token, "s3cr3t-s3cr3t", "s3cr3t-s3cr3t"))
1225
- assert_response res, :not_found
1226
- client.peer_address = "127.0.0.1"
1227
- form = setup_form(authenticity_token, "s3cr3t-s3cr3t", "s3cr3t-s3cr3t")
1228
- form["token"] = "0123456789abcdef0123456789abcdef"
1229
- res = client.post("/setup", form)
1230
- assert_response res, :not_found
1231
- form.delete("token")
1232
- res = client.post("/setup", form)
1233
- assert_response res, :not_found
1234
- assert_equal 0, User.count
1235
- end
1236
-
1237
- test "#{env} opens /setup to any address with the token until a user exists" do
1238
- client = new_client
1239
- client.peer_address = "203.0.113.7"
1240
- Cybertrain.config.set_bool_setting(:setup_open, true)
1241
- res = client.get(setup_link)
1242
- without = client.get("/setup")
1243
- Cybertrain.config.set_bool_setting(:setup_open, false)
1244
- assert_response res, :ok
1245
- assert_response without, :not_found
1246
- AppTest.user
1247
- Cybertrain.config.set_bool_setting(:setup_open, true)
1248
- res = client.get(setup_link)
1249
- Cybertrain.config.set_bool_setting(:setup_open, false)
1250
- assert_response res, :not_found
1251
- end
1252
-
1253
- test "POST /setup with the token creates the first user and signs them in" do
1254
- client = new_client
1255
- client.get(setup_link)
1256
- res = client.post("/setup", setup_form(AppTest.form_token(client), "s3cr3t-s3cr3t", "s3cr3t-s3cr3t"))
1257
- assert_redirected_to res, "/"
1258
- assert_equal 1, User.count
1259
- assert_equal "ann@example.com", User.first.email_address
1260
- assert_equal 1, Session.count
1261
- res = client.get("/session/new")
1262
- assert_includes res.body, "<span>ann@example.com</span>"
1263
- res = client.get(setup_link)
1264
- assert_response res, :not_found
1265
- end
1266
-
1267
- test "POST /setup with a short or mismatched password re-renders the form" do
1268
- client = new_client
1269
- client.get(setup_link)
1270
- res = client.post("/setup", setup_form(AppTest.form_token(client), "short", "other"))
1271
- assert_response res, :unprocessable_entity
1272
- assert_includes res.body, "<li>Password is too short (minimum is 8 characters)</li>"
1273
- assert_includes res.body, "<li>Password confirmation doesn&#39;t match Password</li>"
1274
- assert_includes res.body, "<input type=\\"hidden\\" name=\\"token\\" value=\\"\#{SetupController.setup_token}\\">"
1275
- assert_equal 0, User.count
1276
- end
1277
-
1278
- test "./#{app} user creates a user, then sets its password" do
1279
- new_client
1280
- assert_equal 0, run_command(["user", "Bob@Example.com", "s3cr3t-s3cr3t"])
1281
- assert_equal 1, User.count
1282
- assert_equal "bob@example.com", User.first.email_address
1283
- assert User.first.authenticate("s3cr3t-s3cr3t")
1284
- assert_equal 0, run_command(["user", "bob@example.com", "another-s3cr3t"])
1285
- assert_equal 1, User.count
1286
- assert User.first.authenticate("another-s3cr3t")
1287
- refute User.first.authenticate("s3cr3t-s3cr3t")
1288
- end
1289
-
1290
- test "./#{app} user refuses bad arguments and an empty or short password" do
1291
- new_client
1292
- assert_equal 1, run_command(["user"])
1293
- assert_equal 1, run_command(["user", "ann@example.com", "s3cr3t-s3cr3t", "extra"])
1294
- assert_equal 1, run_command(["user", "--help"])
1295
- assert_equal 1, run_command(["user", "ann@example.com", ""])
1296
- assert_equal 1, run_command(["user", "ann@example.com", "short"])
1297
- assert_equal 0, User.count
1298
- end
1299
-
1300
- test "a password read from standard input loses one trailing newline" do
1301
- assert_equal "s3cr3t s3cr3t", UserCommand.password_from("s3cr3t s3cr3t\\n")
1302
- assert_equal "s3cr3t", UserCommand.password_from("s3cr3t\\r\\n")
1303
- assert_equal "s3cr3t\\n", UserCommand.password_from("s3cr3t\\n\\n")
1304
- assert_equal "", UserCommand.password_from("")
1305
- end
1306
-
1307
- test "the boot warning is due while no user exists" do
1308
- new_client
1309
- assert UserCommand.no_user?
1310
- reconnect
1311
- AppTest.user
1312
- refute UserCommand.no_user?
1313
- reconnect
1314
- end
1315
-
1316
- RUBY
1317
- end
1318
-
1319
- def self.sign_up_tests
1320
- <<~RUBY
1321
- test "POST /sign_up creates the user and signs them in" do
1322
- client = new_client
1323
- client.get("/sign_up")
1324
- res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1325
- "user[email_address]" => " Ann@Example.com ",
1326
- "user[password]" => "s3cr3t-s3cr3t",
1327
- "user[password_confirmation]" => "s3cr3t-s3cr3t" })
1328
- assert_redirected_to res, "/"
1329
- assert_equal 1, User.count
1330
- assert_equal "ann@example.com", User.first.email_address
1331
- assert User.first.password_digest.start_with?("$pbkdf2-sha256$")
1332
- assert_equal 1, Session.count
1333
- res = client.get("/session/new")
1334
- assert_includes res.body, "<span>ann@example.com</span>"
1335
- assert_includes res.body, "Sign out"
1336
- end
1337
-
1338
- test "POST /sign_up with a short or mismatched password re-renders the form" do
1339
- client = new_client
1340
- client.get("/sign_up")
1341
- res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1342
- "user[email_address]" => "ann@example.com",
1343
- "user[password]" => "short",
1344
- "user[password_confirmation]" => "other" })
1345
- assert_response res, :unprocessable_entity
1346
- assert_includes res.body, "<li>Password is too short (minimum is 8 characters)</li>"
1347
- assert_includes res.body, "<li>Password confirmation doesn&#39;t match Password</li>"
1348
- assert_equal 0, User.count
1349
- res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1350
- "user[email_address]" => "ann@example.com",
1351
- "user[password]" => "",
1352
- "user[password_confirmation]" => "" })
1353
- assert_includes res.body, "<li>Password can&#39;t be blank</li>"
1354
- end
1355
-
1356
- test "an email address can be registered once" do
1357
- client = new_client
1358
- AppTest.user("ann@example.com")
1359
- client.get("/sign_up")
1360
- res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1361
- "user[email_address]" => "ANN@example.com",
1362
- "user[password]" => "another-one",
1363
- "user[password_confirmation]" => "another-one" })
1364
- assert_response res, :unprocessable_entity
1365
- assert_includes res.body, "<li>Email address has already been taken</li>"
1366
- assert_equal 1, User.count
1367
- end
1368
-
1369
- RUBY
1370
- end
1371
-
1372
- def self.authentication_test_tail
1373
- <<~RUBY
1374
- test "POST /session signs in with the right password" do
1375
- client = new_client
1376
- AppTest.user
1377
- res = AppTest.sign_in(client)
1378
- assert_redirected_to res, "/"
1379
- assert_response res, :see_other
1380
- assert_equal 1, Session.count
1381
- assert_equal "127.0.0.1", Session.first.ip_address
1382
- end
1383
-
1384
- test "authentication returns to a local path once" do
1385
- ctx = Cybertrain::Context.new(Cybertrain::Request.new("GET", "/", {}, ""))
1386
- ctx.session = Cybertrain::Session.new
1387
- controller = ApplicationController.new(ctx)
1388
- assert_equal "/", controller.after_authentication_url
1389
- ["/", "/products", "/products/1?tab=details#title", "/products//1", "/caf%C3%A9"].each do |path|
1390
- controller.session[:return_to_after_authenticating] = path
1391
- assert_equal path, controller.after_authentication_url
1392
- refute controller.session.key?(:return_to_after_authenticating)
1393
- assert_equal "/", controller.after_authentication_url
1394
- end
1395
- end
1396
-
1397
- test "authentication rejects unsafe return destinations and consumes them" do
1398
- ctx = Cybertrain::Context.new(Cybertrain::Request.new("GET", "/", {}, ""))
1399
- ctx.session = Cybertrain::Session.new
1400
- controller = ApplicationController.new(ctx)
1401
- unsafe = ["", "products", "https://evil.example/", "//evil.example/", "///evil.example/",
1402
- "/\\\\evil.example/", "/products\\\\evil", " //evil.example/", "/記事", "/" + "a" * 2048]
1403
- (0..32).each { |byte| unsafe << "/\#{Cybertrain::Test.binary([byte])}/evil.example/" }
1404
- unsafe << "/\#{Cybertrain::Test.binary([127])}/evil.example/"
1405
- unsafe.each do |path|
1406
- controller.session[:return_to_after_authenticating] = path
1407
- assert_equal "/", controller.after_authentication_url
1408
- refute controller.session.key?(:return_to_after_authenticating)
1409
- end
1410
- end
1411
-
1412
- test "POST /session with the wrong password shows an alert" do
1413
- client = new_client
1414
- AppTest.user
1415
- res = AppTest.sign_in(client, "ann@example.com", "wrong-password")
1416
- assert_redirected_to res, "/session/new"
1417
- res = client.follow_redirect!
1418
- assert_includes res.body, "<p class=\\"alert\\">Try another email address or password.</p>"
1419
- assert_equal 0, Session.count
1420
- res = AppTest.sign_in(client, "nobody@example.com", "s3cr3t-s3cr3t")
1421
- assert_redirected_to res, "/session/new"
1422
- end
1423
-
1424
- # SessionsController's rate_limit: ten attempts per address, then even
1425
- # the right password goes back to the form until the window closes.
1426
- test "POST /session past ten attempts is refused for a while" do
1427
- client = new_client
1428
- AppTest.user
1429
- Cybertrain::RateLimit.reset_all!
1430
- client.get("/session/new")
1431
- wrong_password = { "authenticity_token" => AppTest.form_token(client),
1432
- "email_address" => "ann@example.com", "password" => "wrong-password" }
1433
- right_password = { "authenticity_token" => AppTest.form_token(client),
1434
- "email_address" => "ann@example.com", "password" => "s3cr3t-s3cr3t" }
1435
- 10.times { client.post("/session", wrong_password) }
1436
- res = client.post("/session", right_password)
1437
- assert_redirected_to res, "/session/new"
1438
- assert_equal 0, Session.count
1439
- res = client.follow_redirect!
1440
- assert_includes res.body, "<p class=\\"alert\\">Try again later.</p>"
1441
- Cybertrain::RateLimit.current_time = Time.now.to_i + 3 * 60
1442
- res = client.post("/session", right_password)
1443
- Cybertrain::RateLimit.current_time = -1
1444
- assert_redirected_to res, "/"
1445
- assert_equal 1, Session.count
1446
- end
1447
-
1448
- test "DELETE /session signs out and drops the Session row" do
1449
- client = new_client
1450
- AppTest.user
1451
- AppTest.sign_in(client)
1452
- client.get("/session/new")
1453
- res = client.post("/session", { "_method" => "delete", "authenticity_token" => AppTest.form_token(client) })
1454
- assert_redirected_to res, "/session/new"
1455
- assert_equal 0, Session.count
1456
- res = client.follow_redirect!
1457
- assert_includes res.body, "<p class=\\"notice\\">You have been signed out.</p>"
1458
- assert_includes res.body, "<a href=\\"/session/new\\">Sign in</a>"
1459
- end
1460
-
1461
- test "a session the database no longer has signs the browser out" do
1462
- client = new_client
1463
- AppTest.user
1464
- AppTest.sign_in(client)
1465
- Session.all.delete_all
1466
- client.get("/session/new")
1467
- res = client.post("/session", { "_method" => "delete", "authenticity_token" => AppTest.form_token(client) })
1468
- assert_redirected_to res, "/session/new"
1469
- end
1470
-
1471
- test "changing the password signs out the sessions started before" do
1472
- client = new_client
1473
- user = AppTest.user
1474
- AppTest.sign_in(client)
1475
- res = client.get("/session/new")
1476
- assert_includes res.body, "<span>ann@example.com</span>"
1477
- user.password = "another-s3cr3t"
1478
- user.save!
1479
- res = client.get("/session/new")
1480
- refute res.body.include?("<span>ann@example.com</span>")
1481
- assert_equal 0, Session.count
1482
- AppTest.sign_in(client, "ann@example.com", "another-s3cr3t")
1483
- res = client.get("/session/new")
1484
- assert_includes res.body, "<span>ann@example.com</span>"
1485
- end
1486
-
1487
- test "an expired cookie cannot restore its user or reach a protected action" do
1488
- max_age = Cybertrain.config.session_absolute_max_age
1489
- Cybertrain.config.session_absolute_max_age = 60
1490
- begin
1491
- client = new_client
1492
- AppTest.user
1493
- AppTest.sign_in(client)
1494
- name = Cybertrain.config.session_cookie_name
1495
- cookie = "\#{name}=\#{client.cookies[name]}"
1496
- res = client.get("/session/new", { "cookie" => cookie })
1497
- assert_includes res.body, "<span>ann@example.com</span>"
1498
- token = AppTest.form_token(client)
1499
-
1500
- # Keep the signed cookie and its row, but move the creation time
1501
- # to the expiration boundary. Saving updates updated_at too;
1502
- # neither that nor a rewritten cookie extends authentication.
1503
- row = Session.first
1504
- row.created_at = Time.at(Time.now.to_i - Cybertrain.config.session_absolute_max_age).utc
1505
- row.save!
1506
- res = client.post("/session", { "_method" => "delete", "authenticity_token" => token },
1507
- { "cookie" => cookie })
1508
- assert_redirected_to res, "/session/new"
1509
- assert_equal 1, Session.count
1510
- res = client.get("/session/new")
1511
- refute res.body.include?("<span>ann@example.com</span>")
1512
- assert_includes res.body, "<a href=\\"/session/new\\">Sign in</a>"
1513
-
1514
- # Replaying the original credential again still fails, even
1515
- # after the server removed its id from the client's cookie.
1516
- res = client.get("/session/new", { "cookie" => cookie })
1517
- refute res.body.include?("<span>ann@example.com</span>")
1518
- ensure
1519
- Cybertrain.config.session_absolute_max_age = max_age
1520
- end
1521
- end
1522
-
1523
- Cybertrain::Test.run!
1524
- RUBY
1525
- end
1526
3033
  end
1527
3034
  end
1528
3035
  end