/
user.rb
91 lines (73 loc) · 2.34 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class User < ApplicationRecord
CONFIRMATION_TOKEN_EXPIRATION_IN_SECONDS = 10.minutes.to_i
MAILER_FROM_EMAIL = "no-reply@example.com"
PASSWORD_RESET_TOKEN_EXPIRATION_IN_SECONDS = 10.minutes.to_i
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
attr_accessor :current_password
has_secure_password
has_secure_token :confirmation_token
has_secure_token :password_reset_token
has_secure_token :remember_token
before_save :downcase_email
before_save :downcase_unconfirmed_email
validates :email, format: {with: VALID_EMAIL_REGEX}, presence: true, uniqueness: true
validates :unconfirmed_email, format: {with: VALID_EMAIL_REGEX, allow_blank: true}
validate :unconfirmed_email_must_be_available
def confirm!
if unconfirmed_email.present?
update(email: unconfirmed_email, unconfirmed_email: nil)
end
update_columns(confirmed_at: Time.current)
end
def confirmed?
confirmed_at.present?
end
def confirmable_email
if unconfirmed_email.present?
unconfirmed_email
else
email
end
end
def confirmation_token_has_not_expired?
return false if confirmation_sent_at.nil?
(Time.current - confirmation_sent_at) <= User::CONFIRMATION_TOKEN_EXPIRATION_IN_SECONDS
end
def password_reset_token_has_expired?
return true if password_reset_sent_at.nil?
(Time.current - password_reset_sent_at) >= User::PASSWORD_RESET_TOKEN_EXPIRATION_IN_SECONDS
end
def send_confirmation_email!
regenerate_confirmation_token
update_columns(confirmation_sent_at: Time.current)
UserMailer.confirmation(self).deliver_now
end
def send_password_reset_email!
regenerate_password_reset_token
update_columns(password_reset_sent_at: Time.current)
UserMailer.password_reset(self).deliver_now
end
def reconfirming?
unconfirmed_email.present?
end
def unconfirmed?
confirmed_at.nil?
end
def unconfirmed_or_reconfirming?
unconfirmed? || reconfirming?
end
private
def downcase_email
self.email = email.downcase
end
def downcase_unconfirmed_email
return if unconfirmed_email.nil?
self.unconfirmed_email = unconfirmed_email.downcase
end
def unconfirmed_email_must_be_available
return if unconfirmed_email.nil?
if User.find_by(email: unconfirmed_email.downcase)
errors.add(:unconfirmed_email, "is already in use.")
end
end
end