Module: ModelMixin::ClassMethods

Defined in:
app/models/model_mixin.rb

Instance Method Summary collapse

Instance Method Details

#authenticatesObject

Adds methods to set and authenticate against a password stored encrypted by BCrypt. Also adds methods to generate and clear a token, used to retrieve the record of a user who has forgotten their password.

Note that if a password isn’t supplied when creating a user, the error will be on the ‘password_digest` attribute.



16
17
18
19
20
21
22
23
24
25
26
27
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
54
55
56
57
58
59
60
# File 'app/models/model_mixin.rb', line 16

def authenticates
  send :include, InstanceMethodsOnActivation

  attr_reader    :password
  attr_protected :password_digest

  validates :username,        :presence => true, :uniqueness => {case_sensitive: false}, :if => :should_authenticate?
  validates :password_digest, :presence => true, :if => :should_authenticate?

  scope :valid_token, lambda { |token| where("token = ? AND token_created_at > ?", token, 24.hours.ago) }

  instance_eval <<-END, __FILE__, __LINE__ + 1
    # Returns the user with the given <tt>username</tt> if the given password is
    # correct, and <tt>nil</tt> otherwise.
    def authenticate(username, plain_text_password)
      return nil unless username.present?
      user = where(:username => username).first
      if user && user.has_matching_password?(plain_text_password)
        user
      else
        nil
      end
    end

    def find_by_salt(id, salt) # :nodoc:
      user = find_by_id id
      if user && user.has_matching_salt?(salt)
        user
      else
        nil
      end
    end

    # Instantiates a user suitable for user-activation.
    def new_for_activation(attributes = nil)
      user = new attributes
      # Satisfy username and password validations by setting to random values.
      begin
        user.username = SecureRandom.base64(10)
      end while exists?(:username => user.username)
      user.password = SecureRandom.base64(10)
      user
    end
  END
end