-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.rb
41 lines (33 loc) · 1.13 KB
/
user.rb
1
2
3
4
5
6
7
8
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
35
36
37
38
39
40
41
class User < ActiveRecord::Base
attr_reader :password
validates :password_digest, :presence => true
validates :password, :length => { :minimum => 6, :allow_nil => true }
validates :session_token, :presence => true, :uniqueness => true
validates :username, :presence => true, :uniqueness => true
before_validation :ensure_session_token
def self.find_by_credentials(username, password)
user = User.find_by_username(username)
user.try(:is_password?, password) ? user : nil
end
def self.generate_session_token
SecureRandom::urlsafe_base64(16)
end
def is_password?(unencrypted_password)
BCrypt::Password.new(self.password_digest).is_password?(unencrypted_password)
end
def password=(unencrypted_password)
if unencrypted_password.present?
@password = unencrypted_password
self.password_digest = BCrypt::Password.create(unencrypted_password)
end
end
def reset_session_token!
self.session_token = self.class.generate_session_token
self.save!
self.session_token
end
private
def ensure_session_token
self.session_token ||= self.class.generate_session_token
end
end