veri 2.0.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 90c72152f71aea2555de8f7788b356e8b957d94df73a0bfc826ee79b1087fed7
4
- data.tar.gz: f552a61efc8b704a9065bca3d785dcb8cd4046299ee94e05dc0cb08b381511e4
3
+ metadata.gz: 75dab586d4e890b7be8f0e8f6caf35ec3932f08d62a90e0d88b5f32dc08bb4a6
4
+ data.tar.gz: a82743b51f7f58f6c6951362b4165608eb35dafcc040376911dbd45f453d2709
5
5
  SHA512:
6
- metadata.gz: 1947901336055c81c82f36c18c6abdeadc76d6d1ce47564de69bd83cb98a75d14e433276df5be08c24506277571121d81eaf6c3c0805c5d1041f8d9272821d31
7
- data.tar.gz: eb186110a8816965a3ae0c7f396fdd8b0fd212ce281602139268e55cf466e3ad7589e0838383840e629c2b6259ab027c1beb343b5f4338b778717a3b5670eaae
6
+ metadata.gz: '09814524d65a467ea91c8a2692355612c682be9b22ca6d9b6052f015b9644b0cd02190fd9ac387902954b94a7c1d263489dcdbf2cf869530631eba9faa2525d7'
7
+ data.tar.gz: 8975d9e8bd2f83cb76aeb58a33291cf7ce18be20ae6a98a0fd156cdcc04b4704b2c0736711e0e6f4ffe00e05e1c37b5e70670e45b7030734c119389914d5dde2
data/CHANGELOG.md CHANGED
@@ -1,3 +1,51 @@
1
+ ## v3.0.0
2
+
3
+ ### Breaking
4
+
5
+ - Dropped support for Rails 8.0 and earlier
6
+ - Dropped support for Ruby 3.2
7
+ - Changed `user_agent` column in `veri_sessions` table from string to text
8
+ - Renamed account locking to suspension
9
+ - Added algorithm markers to stored password hashes
10
+ - `update_password` now terminates all sessions of the user by default
11
+ - The tenant is now passed to `log_in` and `current_tenant` returns the tenant of the current session
12
+ - Models used as tenants must now be declared with `veri_tenant`
13
+
14
+ ### Features
15
+
16
+ - Added `veri_tenant` to declare tenant models and delete their sessions when they are destroyed
17
+ - Added `shapeshifter_sessions` association to fetch the sessions in which a user is impersonating someone
18
+ - Added `Veri::Session.from_request` method to fetch the session from a request object
19
+ - Added `Veri::Session.shapeshifted` to fetch impersonating sessions
20
+ - Added `Veri::Session.in_original_tenant` to fetch impersonating sessions that return to a tenant
21
+ - Added support for binary UUID primary keys in MySQL
22
+
23
+ ### Bugs
24
+
25
+ - Fixed Rails commands failing when the user model cannot be loaded
26
+ - Fixed migration helpers raising when the tenant has no sessions, which broke migrations on fresh databases
27
+ - Fixed `true_tenant` returning the impersonated tenant when the impersonator had no tenant
28
+ - Fixed the generated migration failing when the user table's primary key is not `id`
29
+ - Fixed the generated migration not working with UUID primary keys on some databases
30
+
31
+ ### Misc
32
+
33
+ - The generator now takes the primary key type from the existing user table, making `--uuid` unnecessary
34
+
35
+ To upgrade to v3.0.0, please refer to the [migration guide](https://github.com/brownboxdev/veri-authentication/discussions/28)
36
+
37
+ ## v2.1.0
38
+
39
+ ### Features
40
+
41
+ - Added `Veri::Session#switch_tenant` method to move a session to another tenant
42
+ - Added `password_set?` method to check whether a user has a password
43
+
44
+ ### Bugs
45
+
46
+ - Fixed `log_in` using the previous tenant when `current_tenant` changes within the same request
47
+ - Fixed `Veri::Session.in_tenant` raising an error without a message when given an invalid tenant
48
+
1
49
  ## v2.0.3
2
50
 
3
51
  ### Bugs
@@ -44,7 +92,7 @@
44
92
 
45
93
  - Dropped some unnecessary dependencies
46
94
 
47
- To upgrade to v2.0.0, please refer to the [migration guide](https://github.com/enjaku4/veri/discussions/14)
95
+ To upgrade to v2.0.0, please refer to the [migration guide](https://github.com/brownboxdev/veri-authentication/discussions/14)
48
96
 
49
97
  ## v1.1.0
50
98
 
data/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  [![Gem Version](https://badge.fury.io/rb/veri.svg)](http://badge.fury.io/rb/veri)
4
4
  [![Downloads](https://img.shields.io/gem/dt/veri.svg)](https://rubygems.org/gems/veri)
5
- [![Github Actions badge](https://github.com/enjaku4/veri/actions/workflows/ci.yml/badge.svg)](https://github.com/enjaku4/veri/actions/workflows/ci.yml)
6
- [![License](https://img.shields.io/github/license/enjaku4/veri.svg)](LICENSE)
5
+ [![Github Actions badge](https://github.com/brownboxdev/veri-authentication/actions/workflows/ci.yml/badge.svg)](https://github.com/brownboxdev/veri-authentication/actions/workflows/ci.yml)
6
+ [![License](https://img.shields.io/github/license/brownboxdev/veri-authentication.svg)](LICENSE)
7
7
 
8
8
  Veri is a cookie-based authentication library for Ruby on Rails. It provides only essential building blocks for secure user authentication without cluttering your app with generated controllers, views, and mailers. This makes it ideal for building custom authentication flows.
9
9
 
@@ -11,7 +11,7 @@ Veri supports multi-tenancy, granular session management, multiple password hash
11
11
 
12
12
  **Example of Usage:**
13
13
 
14
- Consider a multi-tenant SaaS application where users need to manage their active sessions across devices and browsers, terminating specific sessions remotely when needed. Administrators require similar capabilities in their admin panel, with additional powers to lock accounts and temporarily assume user identities for troubleshooting. You can build all this easily with Veri.
14
+ Consider a multi-tenant SaaS application where users need to manage their active sessions across devices and browsers, terminating specific sessions remotely when needed. Administrators require similar capabilities in their admin panel, with additional powers to suspend accounts and temporarily assume user identities for troubleshooting. You can build all this easily with Veri.
15
15
 
16
16
  ## Table of Contents
17
17
 
@@ -21,7 +21,7 @@ Consider a multi-tenant SaaS application where users need to manage their active
21
21
  - [Password Management](#password-management)
22
22
  - [Controller Integration](#controller-integration)
23
23
  - [Authentication Sessions](#authentication-sessions)
24
- - [Account Lockout](#account-lockout)
24
+ - [Account Suspension](#account-suspension)
25
25
  - [User Impersonation](#user-impersonation)
26
26
  - [Multi-Tenancy](#multi-tenancy)
27
27
  - [View Helpers](#view-helpers)
@@ -50,13 +50,32 @@ bundle install
50
50
  Generate the migration for your user model (replace `users` with your table name if different):
51
51
 
52
52
  ```shell
53
- # For standard integer IDs
54
53
  rails generate veri:authentication users
54
+ ```
55
+
56
+ Veri's sessions table uses the same primary key type as your users table, so the table must exist before you run the generator.
57
+
58
+ If your database can't handle your UUIDs on its own, apply your app's UUID handling to Veri's session model in an initializer. The examples below show which attributes need it; the code itself depends on how your app handles UUIDs. If your app generates UUIDs:
59
+
60
+ ```rb
61
+ Rails.application.config.to_prepare do
62
+ Veri::Session.before_create { self.id ||= SecureRandom.uuid }
63
+ end
64
+ ```
65
+
66
+ If it also stores them as binary, add your binary type on top of that:
55
67
 
56
- # For UUID primary keys
57
- rails generate veri:authentication users --uuid
68
+ ```rb
69
+ Rails.application.config.to_prepare do
70
+ Veri::Session.before_create { self.id ||= SecureRandom.uuid }
71
+ [:id, :authenticatable_id, :original_authenticatable_id, :tenant_id, :original_tenant_id].each do |name|
72
+ Veri::Session.attribute name, YourBinaryUuidType.new
73
+ end
74
+ end
58
75
  ```
59
76
 
77
+ If your app sets any other kind of id itself, such as its own integer ids, do the same with your own id handling.
78
+
60
79
  Run the migration:
61
80
 
62
81
  ```shell
@@ -93,12 +112,20 @@ user.update_password("password")
93
112
 
94
113
  # Verify a password
95
114
  user.verify_password("password")
115
+
116
+ # Check if a password is set
117
+ user.password_set?
96
118
  ```
97
- Changing a password does not automatically terminate existing sessions. If you want to invalidate the user's sessions after a password change, do so explicitly:
119
+
120
+ Updating a password terminates all of the user's sessions, including the current one. To keep the user signed in, log them in again or opt out of session termination:
98
121
 
99
122
  ```rb
123
+ # Update a password and keep the user signed in
100
124
  user.update_password(new_password)
101
- user.sessions.terminate_all
125
+ log_in(user)
126
+
127
+ # Update a password without terminating sessions
128
+ user.update_password(new_password, terminate_sessions: false)
102
129
  ```
103
130
 
104
131
  ## Controller Integration
@@ -175,7 +202,7 @@ current_user
175
202
  # Returns true if user is authenticated
176
203
  logged_in?
177
204
 
178
- # Authenticates user, returns true on success or false if account is locked
205
+ # Authenticates user, returns true on success or false if account is suspended
179
206
  log_in(user)
180
207
 
181
208
  # Terminates current session
@@ -206,8 +233,6 @@ class ApplicationController < ActionController::Base
206
233
  end
207
234
  ```
208
235
 
209
- The `when_unauthenticated` method can be overridden in any controller to provide controller-specific handling.
210
-
211
236
  ## Authentication Sessions
212
237
 
213
238
  Veri stores authentication sessions in the database, providing session management capabilities:
@@ -220,6 +245,33 @@ user.sessions
220
245
 
221
246
  # Get current session in controller
222
247
  current_session
248
+
249
+ # Get session from a request
250
+ Veri::Session.from_request(request)
251
+ ```
252
+
253
+ ### Sessions Outside Controllers
254
+
255
+ Code that handles a request outside of controllers, such as Action Cable connections and route constraints, can find the current session from the request:
256
+
257
+ ```rb
258
+ module ApplicationCable
259
+ class Connection < ActionCable::Connection::Base
260
+ identified_by :current_user
261
+
262
+ # Runs only when the connection opens; disconnecting it after the session is terminated is up to your application
263
+ def connect
264
+ self.current_user = Veri::Session.from_request(request)&.identity || reject_unauthorized_connection
265
+ end
266
+ end
267
+ end
268
+ ```
269
+
270
+ ```rb
271
+ # Only administrators can open the jobs dashboard
272
+ constraints -> (request) { Veri::Session.from_request(request)&.identity&.admin? } do
273
+ mount Sidekiq::Web => "/jobs"
274
+ end
223
275
  ```
224
276
 
225
277
  ### Session Information
@@ -280,28 +332,30 @@ user.sessions.inactive.terminate_all
280
332
  Veri::Session.expired.terminate_all
281
333
  ```
282
334
 
283
- ## Account Lockout
335
+ When the current session is terminated, the controller still sees it for the rest of the request, so `logged_in?` stays true until the next request unless you call `log_in` or `log_out`. The same applies when a password update or an account suspension terminates it.
336
+
337
+ ## Account Suspension
284
338
 
285
- Veri provides account lockout functionality to temporarily disable user accounts.
339
+ Veri provides account suspension functionality to temporarily disable user accounts.
286
340
 
287
341
  ```rb
288
- # Lock a user account
289
- user.lock!
342
+ # Suspend a user account
343
+ user.suspend!
290
344
 
291
- # Unlock a user account
292
- user.unlock!
345
+ # Unsuspend a user account
346
+ user.unsuspend!
293
347
 
294
- # Check if account is locked
295
- user.locked?
348
+ # Check if account is suspended
349
+ user.suspended?
296
350
 
297
- # Fetch locked users
298
- User.locked
351
+ # Fetch suspended users
352
+ User.suspended
299
353
 
300
- # Fetch unlocked users
301
- User.unlocked
354
+ # Fetch unsuspended users
355
+ User.unsuspended
302
356
  ```
303
357
 
304
- When an account is locked, the user cannot log in. If they're already logged in, their sessions are terminated and they are treated as unauthenticated.
358
+ When an account is suspended, the user cannot log in. If they're already logged in, their sessions are terminated and they are treated as unauthenticated.
305
359
 
306
360
  ## User Impersonation
307
361
 
@@ -339,6 +393,16 @@ session.shapeshifted?
339
393
 
340
394
  # Returns original user when shapeshifted, otherwise current user
341
395
  session.true_identity
396
+
397
+ # Fetch the sessions in which someone is impersonating this user
398
+ user.sessions.shapeshifted
399
+ ```
400
+
401
+ User method:
402
+
403
+ ```rb
404
+ # Returns the sessions in which a user is impersonating someone
405
+ user.shapeshifter_sessions
342
406
  ```
343
407
 
344
408
  Controller helper:
@@ -350,31 +414,40 @@ shapeshifter?
350
414
 
351
415
  ## Multi-Tenancy
352
416
 
353
- Veri supports multi-tenancy, allowing you to isolate authentication sessions between different tenants such as organizations, clients, or subdomains.
417
+ Veri supports multi-tenancy, allowing you to tie authentication sessions to tenants such as organizations, clients, or subdomains.
354
418
 
355
419
  ### Setup
356
420
 
357
- To isolate authentication sessions between different tenants, override the `current_tenant` method:
421
+ Pass the tenant when logging a user in:
358
422
 
359
423
  ```rb
360
- class ApplicationController < ActionController::Base
361
- include Veri::Authentication
424
+ # Option 1: String-based tenancy (e.g., subdomain)
425
+ log_in(user, tenant: request.subdomain)
362
426
 
363
- with_authentication
364
-
365
- private
427
+ # Option 2: Model-based tenancy (e.g., organization)
428
+ log_in(user, tenant: company)
429
+ ```
366
430
 
367
- def current_tenant
368
- # Option 1: String-based tenancy (e.g., subdomain)
369
- request.subdomain
431
+ Tenants can be represented as either a string or an instance of a model declared as a tenant:
370
432
 
371
- # Option 2: Model-based tenancy (e.g., organization)
372
- Company.find_by(subdomain: request.subdomain)
373
- end
433
+ ```rb
434
+ class Company < ApplicationRecord
435
+ veri_tenant
374
436
  end
375
437
  ```
376
438
 
377
- By default, Veri assumes a single-tenant setup where `current_tenant` returns `nil`. Tenants can be represented as either a string or an `ActiveRecord` model instance.
439
+ Without the `tenant:` argument the session has no tenant, which is the single-tenant setup.
440
+
441
+ Use `current_tenant` in controllers and views to get the tenant of the current session:
442
+
443
+ ```rb
444
+ # Returns the tenant (string, model instance, or nil if the session has no tenant)
445
+ current_tenant
446
+ ```
447
+
448
+ Since `nil` is a valid tenant, `current_tenant` raises an error when no user is logged in.
449
+
450
+ Veri only stores the tenant in the session and returns it. The session itself is found by its cookie alone, whatever its tenant. How your application uses the tenant, if at all, is entirely up to it, so tenant management and scoping are the application's responsibility.
378
451
 
379
452
  ### Session Tenant Access
380
453
 
@@ -396,8 +469,31 @@ user.sessions.in_tenant(tenant)
396
469
 
397
470
  # Terminate all sessions for a specific user within a tenant
398
471
  user.sessions.in_tenant(tenant).terminate_all
472
+
473
+ # If you use impersonation, fetch a user's impersonating sessions that return to a given tenant
474
+ user.shapeshifter_sessions.in_original_tenant(tenant)
475
+ ```
476
+
477
+ ### Switching Tenants
478
+
479
+ A session belongs to one tenant, and a browser holds one session per host. A user is therefore logged in to one tenant at a time, unless your tenants live on separate subdomains, where each subdomain keeps its own session.
480
+
481
+ To move a user to another tenant, call `switch_tenant` on their session:
482
+
483
+ ```rb
484
+ class CompaniesController < ApplicationController
485
+ def switch
486
+ company = current_user.companies.find(params[:id])
487
+
488
+ current_session.switch_tenant(company)
489
+
490
+ redirect_to root_path, notice: "Switched to #{company.name}"
491
+ end
492
+ end
399
493
  ```
400
494
 
495
+ The user stays logged in and the session keeps its expiration. This also covers applications where the tenant is not known at login: log the user in without a tenant and switch once they choose one.
496
+
401
497
  ### User Impersonation with Tenants
402
498
 
403
499
  When using user impersonation in a multi-tenant setup, Veri allows cross-tenant shapeshifting while preserving the original tenant context:
@@ -416,23 +512,17 @@ All other session methods work the same way in multi-tenant applications as in s
416
512
 
417
513
  ### Orphaned Sessions
418
514
 
419
- When a tenant object is deleted from your database, its associated sessions become orphaned.
515
+ Destroying a record of a model declared with `veri_tenant` also deletes its sessions, including the impersonating sessions that return to it, so their users are logged out.
420
516
 
421
- To clean up orphaned sessions, use:
517
+ Sessions become orphaned when their tenant is removed without running Active Record callbacks, for example with `delete` or raw SQL, or is destroyed after its model stopped declaring `veri_tenant`. Users with orphaned sessions remain logged in, and looking up their tenant raises an error. Use `prune` as a fallback to delete orphaned sessions:
422
518
 
423
519
  ```rb
424
520
  Veri::Session.prune
425
521
  ```
426
522
 
427
- Or, for a specific user:
428
-
429
- ```rb
430
- user.sessions.prune
431
- ```
432
-
433
523
  ### Tenant Migrations
434
524
 
435
- When you rename or remove models used as tenants, you need to update Veri's stored data accordingly. Use these irreversible data migrations:
525
+ When you rename or remove models used as tenants, you need to update Veri's stored data accordingly. Veri adds these helpers to your migrations. The changes they make are irreversible:
436
526
 
437
527
  ```rb
438
528
  # Rename a tenant class (e.g., when you rename your Organization model to Company)
@@ -451,9 +541,9 @@ Access authentication state in your views:
451
541
  <p>Welcome, <%= current_user.name %>!</p>
452
542
  <% if shapeshifter? %>
453
543
  <p><em>Currently viewing as <%= current_user.name %> (Original: <%= current_session.true_identity.name %>)</em></p>
454
- <%= link_to "Return to Original Identity", revert_path, method: :patch %>
544
+ <%= button_to "Return to Original Identity", revert_path, method: :patch %>
455
545
  <% end %>
456
- <%= link_to "Logout", logout_path, method: :delete %>
546
+ <%= button_to "Logout", logout_path, method: :delete %>
457
547
  <% else %>
458
548
  <%= link_to "Login", login_path %>
459
549
  <% end %>
@@ -503,11 +593,38 @@ RSpec.configure do |config|
503
593
  end
504
594
  ```
505
595
 
596
+ ### Sessions as Test Data
597
+
598
+ Code that receives a session, such as a service object that terminates all sessions but the current one, can be tested without logging in. Create the session directly:
599
+
600
+ ```rb
601
+ module SessionHelpers
602
+ def create_session_for(user, tenant: nil)
603
+ session = Veri::Session.create!(
604
+ authenticatable: user,
605
+ hashed_token: SecureRandom.hex,
606
+ expires_at: 1.day.from_now,
607
+ last_seen_at: Time.current
608
+ )
609
+ session.switch_tenant(tenant)
610
+ session
611
+ end
612
+ end
613
+
614
+ # In your spec_helper.rb
615
+ RSpec.configure do |config|
616
+ config.include SessionHelpers
617
+ end
618
+
619
+ # In a multi-tenant application
620
+ create_session_for(user, tenant: company)
621
+ ```
622
+
506
623
  ## Getting Help and Contributing
507
624
 
508
625
  ### Getting Help
509
626
 
510
- Have a question or need assistance? Open a discussion in the [discussions section](https://github.com/enjaku4/veri/discussions) for:
627
+ Have a question or need assistance? Open a discussion in the [discussions section](https://github.com/brownboxdev/veri-authentication/discussions) for:
511
628
 
512
629
  - Usage questions
513
630
  - Implementation guidance
@@ -515,7 +632,7 @@ Have a question or need assistance? Open a discussion in the [discussions sectio
515
632
 
516
633
  ### Issues
517
634
 
518
- [Issues](https://github.com/enjaku4/veri/issues) track bugs, planned features, and other work. When reporting a bug, please include:
635
+ [Issues](https://github.com/brownboxdev/veri-authentication/issues) track bugs, planned features, and other work. When reporting a bug, please include:
519
636
 
520
637
  - A clear description of the problem
521
638
  - Steps to reproduce the issue
@@ -523,20 +640,20 @@ Have a question or need assistance? Open a discussion in the [discussions sectio
523
640
 
524
641
  ### Contributing Code
525
642
 
526
- Any open issue is free to pick up or discuss. Check the [project board](https://github.com/users/enjaku4/projects/13) or [issues tab](https://github.com/enjaku4/veri/issues).
643
+ Any open issue is free to pick up or discuss. Check the [issues tab](https://github.com/brownboxdev/veri-authentication/issues).
527
644
 
528
- Before contributing, please read the [contributing guidelines](https://github.com/enjaku4/veri/blob/main/CONTRIBUTING.md).
645
+ Before contributing, please read the [contributing guidelines](https://github.com/brownboxdev/veri-authentication/blob/main/CONTRIBUTING.md).
529
646
 
530
647
  ## License
531
648
 
532
- The gem is available as open source under the terms of the [MIT License](https://github.com/enjaku4/veri/blob/main/LICENSE.txt).
649
+ The gem is available as open source under the terms of the [MIT License](https://github.com/brownboxdev/veri-authentication/blob/main/LICENSE.txt).
533
650
 
534
651
  ## Code of Conduct
535
652
 
536
- Everyone interacting in the Veri project is expected to follow the [code of conduct](https://github.com/enjaku4/veri/blob/main/CODE_OF_CONDUCT.md).
653
+ Everyone interacting in the Veri project is expected to follow the [code of conduct](https://github.com/brownboxdev/veri-authentication/blob/main/CODE_OF_CONDUCT.md).
537
654
 
538
655
  ## Old Versions
539
656
 
540
657
  Only the latest major version is actively maintained. READMEs for older versions are available here for reference:
541
658
 
542
- [v1.x.x](https://github.com/enjaku4/veri/blob/9c188e16a703141b7cd89dd31d5cd49a557f143d/README.md)
659
+ [v2.x.x](https://github.com/brownboxdev/veri-authentication/blob/e6909d2689c2ae11919fc3d1f3c50c19b2995a91/README.md) | [v1.x.x](https://github.com/brownboxdev/veri-authentication/blob/9c188e16a703141b7cd89dd31d5cd49a557f143d/README.md)
@@ -5,11 +5,22 @@ module Veri
5
5
  class Session < ActiveRecord::Base
6
6
  self.table_name = "veri_sessions"
7
7
 
8
+ belongs_to :authenticatable, class_name: Veri::Configuration.user_model_name
9
+ belongs_to :original_authenticatable, class_name: Veri::Configuration.user_model_name, optional: true
8
10
  belongs_to :tenant, polymorphic: true, optional: true
9
11
  belongs_to :original_tenant, polymorphic: true, optional: true
10
12
 
13
+ scope :shapeshifted, -> { where.not(original_authenticatable_id: nil) }
11
14
  scope :in_tenant, -> (tenant) { where(**Veri::Inputs::Tenant.new(tenant).resolve) }
12
- scope :active, -> { where.not(id: expired.select(:id)).where.not(id: inactive.select(:id)) }
15
+ scope :in_original_tenant, -> (tenant) do
16
+ resolved_tenant = Veri::Inputs::Tenant.new(tenant).resolve
17
+ shapeshifted.where(original_tenant_type: resolved_tenant[:tenant_type], original_tenant_id: resolved_tenant[:tenant_id])
18
+ end
19
+ scope :active, -> do
20
+ inactive_session_lifetime = Veri::Configuration.inactive_session_lifetime
21
+ active = where(expires_at: Time.current..)
22
+ inactive_session_lifetime ? active.where(last_seen_at: (Time.current - inactive_session_lifetime)..) : active
23
+ end
13
24
  scope :expired, -> { where(expires_at: ...Time.current) }
14
25
  scope :inactive, -> do
15
26
  inactive_session_lifetime = Veri::Configuration.inactive_session_lifetime
@@ -53,30 +64,30 @@ module Veri
53
64
  end
54
65
 
55
66
  def identity = authenticatable
56
- def shapeshifted? = original_authenticatable.present?
57
- def true_identity = original_authenticatable || authenticatable
58
- def true_tenant = original_tenant || tenant
67
+ def shapeshifted? = original_authenticatable_id.present?
68
+ def true_identity = shapeshifted? ? original_authenticatable : authenticatable
69
+ def true_tenant = shapeshifted? ? original_tenant : tenant
59
70
 
60
71
  def shapeshift(user, tenant: nil)
61
72
  raise Veri::Error, "Cannot shapeshift from a shapeshifted session" if shapeshifted?
62
73
 
63
- resolved_tenant = Veri::Inputs::Tenant.new(
64
- tenant,
65
- error: Veri::InvalidTenantError,
66
- message: "Expected a string, an ActiveRecord model instance, or nil, got `#{tenant.inspect}`"
67
- ).resolve
74
+ processed_authenticatable = Veri::Inputs::Authenticatable.new(user).process
75
+ resolved_tenant = Veri::Inputs::Tenant.new(tenant).resolve
68
76
 
69
- update!(
70
- shapeshifted_at: Time.current,
71
- original_authenticatable: authenticatable,
72
- original_tenant_type: tenant_type,
73
- original_tenant_id: tenant_id,
74
- **resolved_tenant,
75
- authenticatable: Veri::Inputs::Authenticatable.new(
76
- user,
77
- message: "Expected an instance of #{Veri::Configuration.user_model_name}, got `#{user.inspect}`"
78
- ).process
79
- )
77
+ processed_authenticatable.transaction do
78
+ locked_authenticatable = processed_authenticatable.class.unscoped.lock.find(processed_authenticatable.id)
79
+
80
+ raise Veri::Error, "Cannot shapeshift into a suspended user" if locked_authenticatable.suspended?
81
+
82
+ update!(
83
+ shapeshifted_at: Time.current,
84
+ original_authenticatable: authenticatable,
85
+ original_tenant_type: tenant_type,
86
+ original_tenant_id: tenant_id,
87
+ **resolved_tenant,
88
+ authenticatable: processed_authenticatable
89
+ )
90
+ end
80
91
  end
81
92
 
82
93
  def to_true_identity
@@ -91,6 +102,10 @@ module Veri
91
102
  )
92
103
  end
93
104
 
105
+ def switch_tenant(tenant)
106
+ update!(**Veri::Inputs::Tenant.new(tenant).resolve)
107
+ end
108
+
94
109
  def tenant
95
110
  resolve_tenant(tenant_type, tenant_id) { super }
96
111
  end
@@ -104,34 +119,41 @@ module Veri
104
119
  token = SecureRandom.hex(32)
105
120
  expires_at = Time.current + Veri::Configuration.total_session_lifetime
106
121
 
107
- new(
122
+ session = new(
108
123
  hashed_token: digest_token(token),
109
124
  expires_at:,
110
125
  authenticatable: user,
111
126
  **resolved_tenant
112
- ).update_info(request)
127
+ )
128
+ session.update_info(request)
113
129
 
114
130
  token
115
131
  end
116
132
 
117
133
  def prune
118
- orphaned_tenant_sessions = where.not(tenant_id: nil).includes(:tenant).filter_map do |session|
119
- !session.tenant
120
- rescue ActiveRecord::RecordNotFound
121
- session.id
122
- end
134
+ { tenant_type: :tenant_id, original_tenant_type: :original_tenant_id }.each do |type_column, id_column|
135
+ where.not(id_column => nil).distinct.pluck(type_column).each do |tenant_type|
136
+ tenant_class = tenant_type.constantize
123
137
 
124
- where(id: orphaned_tenant_sessions).delete_all if orphaned_tenant_sessions.any?
138
+ where(type_column => tenant_type).where.not(id_column => tenant_class.select(tenant_class.primary_key)).delete_all
139
+ end
140
+ end
125
141
  end
126
142
 
127
143
  alias terminate_all delete_all
128
144
 
129
- def find_active(token, resolved_tenant)
145
+ def from_request(request)
146
+ token = Veri::Inputs::Request.new(request).process.cookie_jar.encrypted["veri_token"]
147
+
130
148
  return nil if token.blank?
131
149
 
132
- session = find_by(hashed_token: digest_token(token), **resolved_tenant)
150
+ session = eager_load(:authenticatable, :original_authenticatable).find_by(hashed_token: digest_token(token))
151
+
152
+ return nil unless session&.active? && session.identity && session.true_identity
153
+
154
+ raise Veri::Error, "Session belongs to a suspended user" if session.identity.suspended? || session.true_identity.suspended?
133
155
 
134
- session&.active? ? session : nil
156
+ session
135
157
  end
136
158
 
137
159
  private
@@ -8,9 +8,17 @@ module Veri
8
8
 
9
9
  argument :table_name, type: :string, required: true
10
10
 
11
- class_option :uuid, type: :boolean, default: false, desc: "Use UUIDs as primary keys"
12
-
13
11
  def create_migrations
12
+ primary_key = ActiveRecord::Base.with_connection do |connection|
13
+ raise Thor::Error, "Table `#{table_name}` does not exist, run its migration first" unless connection.table_exists?(table_name)
14
+
15
+ connection.columns(table_name).find { |column| column.name == connection.primary_key(table_name) }
16
+ end
17
+
18
+ @id_type = primary_key.sql_type
19
+ @sessions_id_type = @id_type unless primary_key.auto_incremented_by_db?
20
+ @sessions_id_default = primary_key.default_function if @sessions_id_type
21
+
14
22
  migration_template "add_veri_authentication.rb.erb", "db/migrate/add_veri_authentication.rb"
15
23
  end
16
24
 
@@ -2,20 +2,20 @@ class AddVeriAuthentication < ActiveRecord::Migration[<%= ActiveRecord::Migratio
2
2
  def change
3
3
  add_column <%= table_name.to_sym.inspect %>, :hashed_password, :text
4
4
  add_column <%= table_name.to_sym.inspect %>, :password_updated_at, :datetime
5
- add_column <%= table_name.to_sym.inspect %>, :locked, :boolean, default: false, null: false
6
- add_column <%= table_name.to_sym.inspect %>, :locked_at, :datetime
5
+ add_column <%= table_name.to_sym.inspect %>, :suspended, :boolean, default: false, null: false
6
+ add_column <%= table_name.to_sym.inspect %>, :suspended_at, :datetime
7
7
 
8
- create_table :veri_sessions<%= ", id: :uuid" if options[:uuid] %> do |t|
8
+ create_table :veri_sessions<%= ", id: #{@sessions_id_type.inspect}" if @sessions_id_type %><%= ", default: -> { #{@sessions_id_default.inspect} }" if @sessions_id_default %> do |t|
9
9
  t.string :hashed_token, null: false, index: { unique: true }
10
10
  t.datetime :expires_at, null: false
11
- t.belongs_to :authenticatable, null: false, foreign_key: { to_table: <%= table_name.to_sym.inspect %> }, index: true<%= ", type: :uuid" if options[:uuid] %>
12
- t.belongs_to :original_authenticatable, foreign_key: { to_table: <%= table_name.to_sym.inspect %> }, index: true<%= ", type: :uuid" if options[:uuid] %>
13
- t.belongs_to :tenant, polymorphic: true, index: true<%= ", type: :uuid" if options[:uuid] %>
14
- t.belongs_to :original_tenant, polymorphic: true, index: true<%= ", type: :uuid" if options[:uuid] %>
11
+ t.belongs_to :authenticatable, null: false, foreign_key: { to_table: <%= table_name.to_sym.inspect %>, primary_key: primary_key(<%= table_name.to_sym.inspect %>) }, index: true, type: <%= @id_type.inspect %>
12
+ t.belongs_to :original_authenticatable, foreign_key: { to_table: <%= table_name.to_sym.inspect %>, primary_key: primary_key(<%= table_name.to_sym.inspect %>) }, index: true, type: <%= @id_type.inspect %>
13
+ t.belongs_to :tenant, polymorphic: true, index: true, type: <%= @id_type.inspect %>
14
+ t.belongs_to :original_tenant, polymorphic: true, index: true, type: <%= @id_type.inspect %>
15
15
  t.datetime :shapeshifted_at
16
16
  t.datetime :last_seen_at, null: false
17
17
  t.string :ip_address
18
- t.string :user_agent
18
+ t.text :user_agent
19
19
 
20
20
  t.timestamps
21
21
  end