Skip to content

Commit 4fe4125

Browse files
authored
Merge pull request rails#54373 from AliSepehri/signed_id_on_rotation
Accept `on_rotation` argument in `find_signed`
2 parents fd4e570 + 86d8428 commit 4fe4125

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

activerecord/lib/active_record/signed_id.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,10 @@ module ClassMethods
4949
#
5050
# travel_back
5151
# User.find_signed signed_id, purpose: :password_reset # => User.first
52-
def find_signed(signed_id, purpose: nil)
52+
def find_signed(signed_id, purpose: nil, on_rotation: nil)
5353
raise UnknownPrimaryKey.new(self) if primary_key.nil?
5454

55-
if id = signed_id_verifier.verified(signed_id, purpose: combine_signed_id_purposes(purpose))
55+
if id = signed_id_verifier.verified(signed_id, purpose: combine_signed_id_purposes(purpose), on_rotation: on_rotation)
5656
find_by primary_key => id
5757
end
5858
end
@@ -69,8 +69,8 @@ def find_signed(signed_id, purpose: nil)
6969
# signed_id = User.first.signed_id
7070
# User.first.destroy
7171
# User.find_signed! signed_id # => ActiveRecord::RecordNotFound
72-
def find_signed!(signed_id, purpose: nil)
73-
if id = signed_id_verifier.verify(signed_id, purpose: combine_signed_id_purposes(purpose))
72+
def find_signed!(signed_id, purpose: nil, on_rotation: nil)
73+
if id = signed_id_verifier.verify(signed_id, purpose: combine_signed_id_purposes(purpose), on_rotation: on_rotation)
7474
find(id)
7575
end
7676
end

activerecord/test/cases/signed_id_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,23 @@ def set_signed_id
192192
Account.signed_id_verifier = old_verifier
193193
end
194194

195+
test "on_rotation callback using find_signed & find_signed!" do
196+
old_verifier = Account.signed_id_verifier
197+
198+
Account.signed_id_verifier = ActiveSupport::MessageVerifier.new("old secret")
199+
old_account_signed_id = @account.signed_id
200+
Account.signed_id_verifier = ActiveSupport::MessageVerifier.new("new secret")
201+
Account.signed_id_verifier.rotate("old secret")
202+
on_rotation_is_called = false
203+
assert Account.find_signed(old_account_signed_id, on_rotation: -> { on_rotation_is_called = true })
204+
assert on_rotation_is_called
205+
on_rotation_is_called = false
206+
assert Account.find_signed!(old_account_signed_id, on_rotation: -> { on_rotation_is_called = true })
207+
assert on_rotation_is_called
208+
ensure
209+
Account.signed_id_verifier = old_verifier
210+
end
211+
195212
test "cannot get a signed ID for a new record" do
196213
assert_raises ArgumentError, match: /Cannot get a signed_id for a new record/ do
197214
Account.new.signed_id

0 commit comments

Comments
 (0)