/
user.rb
112 lines (87 loc) · 2.3 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
require 'digest/sha1'
require 'email_validator'
module Clearance
module User
extend ActiveSupport::Concern
included do
attr_accessor :password_changing
attr_reader :password
include Validations
include Callbacks
include password_strategy
end
module ClassMethods
def authenticate(email, password)
if user = find_by_normalized_email(email)
if password.present? && user.authenticated?(password)
return user
end
end
end
def find_by_normalized_email(email)
find_by_email normalize_email(email)
end
def normalize_email(email)
email.to_s.downcase.gsub(/\s+/, "")
end
private
def password_strategy
Clearance.configuration.password_strategy || PasswordStrategies::BCrypt
end
end
module Validations
extend ActiveSupport::Concern
included do
validates :email,
email: { strict_mode: true },
presence: true,
uniqueness: { allow_blank: true },
unless: :email_optional?
validates :password, presence: true, unless: :skip_password_validation?
end
end
module Callbacks
extend ActiveSupport::Concern
included do
before_validation :normalize_email
before_create :generate_remember_token
end
end
def forgot_password!
generate_confirmation_token
save validate: false
end
def reset_remember_token!
generate_remember_token
save validate: false
end
def update_password(new_password)
self.password_changing = true
self.password = new_password
if valid?
self.confirmation_token = nil
generate_remember_token
end
save
end
private
def normalize_email
self.email = self.class.normalize_email(email)
end
def email_optional?
false
end
def password_optional?
false
end
def skip_password_validation?
password_optional? || (encrypted_password.present? && !password_changing)
end
def generate_confirmation_token
self.confirmation_token = SecureRandom.hex(20).encode('UTF-8')
end
def generate_remember_token
self.remember_token = SecureRandom.hex(20).encode('UTF-8')
end
end
end