/
user.rb
61 lines (51 loc) · 1.58 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# == Schema Information
# Schema version: 20110314070234
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime
# updated_at :datetime
#
require "digest"
class User < ActiveRecord::Base
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
attr_accessor :password
# list of fields that can accept bulk updates
attr_accessible :name, :email, :password, :password_confirmation
validates :name, presence: true, length: {maximum: 50}
validates :email, presence: true, format: {with: email_regex}, uniqueness: {case_sensitive: false}
validates :password,
confirmation: true,
presence: true,
length: {minimum: 6, maximum: 50},
password: true
before_save :encrypt_password
def self.authenticate(email, submitted_password)
user = User.find_by_email(email)
return user if user and user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
def has_password?(submitted_password)
return encrypt(submitted_password)==encrypted_password
end
private
def make_salt
secure_hash("#{Time.now.utc}")
end
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{self.salt}--#{string}") #return string
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end