Module: Mongokit::SecureToken::ClassMethods
- Defined in:
- lib/mongokit/secure_token.rb
Instance Method Summary collapse
- #generate_unique_secure_token(attribute) ⇒ Object
-
#has_secure_token(attribute, options = {}) ⇒ Object
Example.
Instance Method Details
#generate_unique_secure_token(attribute) ⇒ Object
55 56 57 58 59 60 61 62 |
# File 'lib/mongokit/secure_token.rb', line 55 def generate_unique_secure_token(attribute) = @_st_options_[attribute] loop do token = SecureRandom.base64([:token_length]).tr('0+/=', [:random_string]) break token unless where(attribute => token).exists? end end |
#has_secure_token(attribute, options = {}) ⇒ Object
Example
class User
include Mongoid::Document
mongokit :secure_token
has_secure_token :auth_token
# has_secure_token :auth_token, token_length: 20
# multiple tokens
# has_secure_token :public_key
# has_secure_token :private_key, token_length: 20
end
user = User.new
user.save
user.auth_token # => "77TMHrHJFvFDwodq8w7Ev2m7"
user.regenerate_auth_token! # => true
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/mongokit/secure_token.rb', line 28 def has_secure_token(attribute, = {}) field(attribute, type: String) index({ attribute => 1 }, { unique: true }) @_st_options_ ||= {} @_st_options_[attribute] = ( || {}).tap do |o| o[:random_string] = (('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a - ['0', 'O', 'I', 'l']).sample(4).join o[:token_length] ||= 16 end before_create do |doc| doc[attribute] = doc.class.generate_unique_secure_token(attribute) end class_eval <<-RUBY, __FILE__, __LINE__ + 1 def regenerate_#{attribute}! update_attributes(#{attribute}: self.class.generate_unique_secure_token(:#{attribute})) end RUBY self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def find_by_#{attribute}(token) where(#{attribute}: token).first end RUBY end |