Module: NanoAuth

Defined in:
lib/nano_auth.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/nano_auth.rb', line 9

def self.included(base)

  # Virtual attributes
  attr_accessor :password

  # AR Callbacks
  base.before_save :encrypt_password
  
  # Password validation
  base.validates_presence_of     :password, :if => Proc.new { |u| u.password_required? }
  base.validates_confirmation_of :password, :if => Proc.new { |u| u.password_required? }, :allow_nil => true
  base.validates_length_of       :password, :minimum => 6, :if => Proc.new { |u| u.password_required? }, :allow_nil => true

  # Class methods
  base.class_eval do

    # Authenticates a user by their email name and unencrypted password.  Returns the user or nil.
    def self.authenticate(email, password)
      return nil unless email && password
      u = find_by_email(email)
      u && u.authenticated?(password) ? u : nil
    end

  end
  
end

Instance Method Details

#authenticated?(password) ⇒ Boolean

The big question - are we equivalent?

Returns:

  • (Boolean)


42
43
44
# File 'lib/nano_auth.rb', line 42

def authenticated?(password)
  password_hash == encrypt(password)
end

#encrypt(password) ⇒ Object

Encrypts the password with the user salt



37
38
39
# File 'lib/nano_auth.rb', line 37

def encrypt(password)
  BCrypt::Engine.hash_secret(password,password_salt)
end

#password_required?Boolean

Tell us if there’s a password to work with

Returns:

  • (Boolean)


47
48
49
# File 'lib/nano_auth.rb', line 47

def password_required?
  password_hash.blank? || !password.blank?
end