实例公共方法
find_by_token_for(purpose, token) 链接
使用给定的 token
查找记录,用于预定义的 purpose
。如果令牌无效或未找到记录,则返回 nil
。
来源:显示 | 在 GitHub 上
# File activerecord/lib/active_record/token_for.rb, line 90 def find_by_token_for(purpose, token) raise UnknownPrimaryKey.new(self) unless primary_key token_definitions.fetch(purpose).resolve_token(token) { |id| find_by(primary_key => id) } end
find_by_token_for!(purpose, token) 链接
使用给定的 token
查找记录,用于预定义的 purpose
。如果令牌无效(例如过期、格式错误等),则引发 ActiveSupport::MessageVerifier::InvalidSignature
。如果令牌有效但未找到记录,则引发 ActiveRecord::RecordNotFound
。
来源:显示 | 在 GitHub 上
# File activerecord/lib/active_record/token_for.rb, line 99 def find_by_token_for!(purpose, token) token_definitions.fetch(purpose).resolve_token(token) { |id| find(id) } || (raise ActiveSupport::MessageVerifier::InvalidSignature) end
generates_token_for(purpose, expires_in: nil, &block) 链接
定义为特定 purpose
生成的令牌的行为。令牌可以通过在记录上调用 TokenFor#generate_token_for
来生成。稍后,可以通过使用相同的 purpose 和令牌调用 find_by_token_for
(或 find_by_token_for!
)来获取该记录。
令牌已签名,因此它们是防篡改的。因此,它们可以作为外部世界公开,例如密码重置令牌。
默认情况下,令牌不会过期。可以通过通过 expires_in
选项指定持续时间来配置它们以使其过期。持续时间成为令牌签名的组成部分,因此更改 expires_in
的值将自动使先前生成的令牌失效。
还可以指定一个块。在使用 TokenFor#generate_token_for
生成令牌时,将在记录的上下文中评估该块,其返回值将作为 JSON 嵌入到令牌中。稍后,在使用 find_by_token_for
获取记录时,将在获取的记录的上下文中再次评估该块。如果两个 JSON 值不匹配,则令牌将被视为无效。请注意,块返回的值不应包含敏感信息,因为它将作为人类可读的明文 JSON 嵌入到令牌中。
示例
class User < ActiveRecord::Base
has_secure_password
generates_token_for :password_reset, expires_in: 15.minutes do
# Last 10 characters of password salt, which changes when password is updated:
password_salt&.last(10)
end
end
user = User.first
token = user.generate_token_for(:password_reset)
User.find_by_token_for(:password_reset, token) # => user
# 16 minutes later...
User.find_by_token_for(:password_reset, token) # => nil
token = user.generate_token_for(:password_reset)
User.find_by_token_for(:password_reset, token) # => user
user.update!(password: "new password")
User.find_by_token_for(:password_reset, token) # => nil
来源: 显示 | 在 GitHub 上
# File activerecord/lib/active_record/token_for.rb, line 84 def generates_token_for(purpose, expires_in: nil, &block) self.token_definitions = token_definitions.merge(purpose => TokenDefinition.new(self, purpose, expires_in, block)) end