From 64bf1090eb1695e1981c56169a3be1c562581fa0 Mon Sep 17 00:00:00 2001 From: James Mead Date: Wed, 16 Apr 2025 17:27:21 +0100 Subject: [PATCH] Fix use of User#expires_at in SpecHelpers#stub_auth_for 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). 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 --- CHANGELOG.md | 1 + lib/rpi_auth/spec_helpers.rb | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac8acd7..5e2e9fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added ### Fixed +- Fix use of `User#expires_at` in `SpecHelpers#stub_auth_for` (#82) ### Removed diff --git a/lib/rpi_auth/spec_helpers.rb b/lib/rpi_auth/spec_helpers.rb index f371d26..4c6fc8d 100644 --- a/lib/rpi_auth/spec_helpers.rb +++ b/lib/rpi_auth/spec_helpers.rb @@ -6,7 +6,8 @@ module SpecHelpers # model has an `:user_id` method which returns the users ID, but this can # be changed by setting the `id_param` option. def stub_auth_for(user:, id_param: :user_id) # rubocop:disable Metrics/AbcSize - expires_in = user.respond_to?(:expires_at) ? user.expires_at.to_i - Time.zone.now.to_i : 3600 + expires_at = user.respond_to?(:expires_at) && user.expires_at + expires_in = expires_at.present? ? expires_at.to_i - Time.zone.now.to_i : 3600 token = user.respond_to?(:access_token) ? user.access_token : SecureRandom.hex(16) refresh_token = user.respond_to?(:refresh_token) ? user.refresh_token : SecureRandom.hex(16)