Method: ActiveRecord::SignedId::ClassMethods#find_signed
- Defined in:
- activerecord/lib/active_record/signed_id.rb
#find_signed(signed_id, purpose: nil) ⇒ Object
Lets you find a record based on a signed id that’s safe to put into the world without risk of tampering. This is particularly useful for things like password reset or email verification, where you want the bearer of the signed id to be able to interact with the underlying record, but usually only within a certain time period.
You set the time period that the signed id is valid for during generation, using the instance method signed_id(expires_in: 15.minutes). If the time has elapsed before a signed find is attempted, the signed id will no longer be valid, and nil is returned.
It’s possible to further restrict the use of a signed id with a purpose. This helps when you have a general base model, like a User, which might have signed ids for several things, like password reset or email verification. The purpose that was set during generation must match the purpose set when finding. If there’s a mismatch, nil is again returned.
Examples
signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
User.find_signed signed_id # => nil, since the purpose does not match
travel 16.minutes
User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
travel_back
User.find_signed signed_id, purpose: :password_reset # => User.first
52 53 54 55 56 57 58 |
# File 'activerecord/lib/active_record/signed_id.rb', line 52 def find_signed(signed_id, purpose: nil) raise UnknownPrimaryKey.new(self) if primary_key.nil? if id = signed_id_verifier.verified(signed_id, purpose: combine_signed_id_purposes(purpose)) find_by primary_key => id end end |