Skip to content

Commit e54cc7a

Browse files
authored
Fix use of User#expires_at in SpecHelpers#stub_auth_for (#82)
Previously, if `User#expires_at` was defined, but it was set to `nil`, the `expires_in` calculation was returning a large negative integer. This was because `nil.to_i` is 0 and thus `user.expires_at.to_i - Time.zone.now.to_i` was a value like `-1744820986` (for 2025-04-16 17:30) which meant the credentials were effectively immediately expired some time ago. This isn't a problem in e.g. `code-club-frontend`, because [the user factory sets `User#expires_at` to a time a random number of seconds in the future, i.e. `rand(60..300).seconds.from_now][1]. We've had to do [something similar in `experience-cs`][2], but I think a better solution is to default to using the 3600 fallback value if `User#expires_at` is `nil` just like we do if `User#expires_at` is not defined. [1]: https://github.com/RaspberryPiFoundation/code-club-frontend/blob/f7e965798d910584fed0d1eb7867f32a899f9ce8/spec/factories/user.rb#L21 [2]: https://github.com/RaspberryPiFoundation/experience-cs/blob/47d11bd60da7b7bd93968534542f84edca4054aa/spec/factories/user.rb#L5
2 parents cbd4006 + 64bf109 commit e54cc7a

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Added
1111

1212
### Fixed
13+
- Fix use of `User#expires_at` in `SpecHelpers#stub_auth_for` (#82)
1314

1415
### Removed
1516

lib/rpi_auth/spec_helpers.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ module SpecHelpers
66
# model has an `:user_id` method which returns the users ID, but this can
77
# be changed by setting the `id_param` option.
88
def stub_auth_for(user:, id_param: :user_id) # rubocop:disable Metrics/AbcSize
9-
expires_in = user.respond_to?(:expires_at) ? user.expires_at.to_i - Time.zone.now.to_i : 3600
9+
expires_at = user.respond_to?(:expires_at) && user.expires_at
10+
expires_in = expires_at.present? ? expires_at.to_i - Time.zone.now.to_i : 3600
1011
token = user.respond_to?(:access_token) ? user.access_token : SecureRandom.hex(16)
1112
refresh_token = user.respond_to?(:refresh_token) ? user.refresh_token : SecureRandom.hex(16)
1213

0 commit comments

Comments
 (0)