module MinimalistAuthentication::VerifiableToken

Constants

TOKEN_EXPIRATION_HOURS

Public Instance Methods

matches_verification_token?(token) click to toggle source
# File lib/minimalist_authentication/verifiable_token.rb, line 23
def matches_verification_token?(token)
  token.present? && verification_token_valid? && secure_match?(token)
end
regenerate_verification_token() click to toggle source

generate secure verification_token and record generation time

# File lib/minimalist_authentication/verifiable_token.rb, line 10
def regenerate_verification_token
  update_token
end
secure_update(token, attributes) click to toggle source
# File lib/minimalist_authentication/verifiable_token.rb, line 14
def secure_update(token, attributes)
  if matches_verification_token?(token)
    update(attributes) && clear_token
  else
    errors.add(:base, "Verification token check failed")
    false
  end
end
verification_token_valid?() click to toggle source
# File lib/minimalist_authentication/verifiable_token.rb, line 27
def verification_token_valid?
  return false if verification_token.blank? || verification_token_generated_at.blank?

  verification_token_generated_at > TOKEN_EXPIRATION_HOURS.hours.ago
end

Private Instance Methods

clear_token() click to toggle source
# File lib/minimalist_authentication/verifiable_token.rb, line 35
def clear_token
  update_token(token: nil, time: nil)
end
secure_match?(token) click to toggle source

Compare the tokens in a time-constant manner, to mitigate timing attacks.

# File lib/minimalist_authentication/verifiable_token.rb, line 47
def secure_match?(token)
  ActiveSupport::SecurityUtils.secure_compare(
    ::Digest::SHA256.hexdigest(token),
    ::Digest::SHA256.hexdigest(verification_token)
  )
end
update_token(token: self.class.generate_unique_secure_token, time: Time.now.utc) click to toggle source
# File lib/minimalist_authentication/verifiable_token.rb, line 39
def update_token(token: self.class.generate_unique_secure_token, time: Time.now.utc)
  update!(
    verification_token:              token,
    verification_token_generated_at: time
  )
end