File tree Expand file tree Collapse file tree 4 files changed +38
-1
lines changed
activerecord/lib/active_record Expand file tree Collapse file tree 4 files changed +38
-1
lines changed Original file line number Diff line number Diff line change
1
+ * ` has_secure_password ` now generates an ` #{attribute}_salt ` method that returns the salt
2
+ used to compute the password digest. The salt will change whenever the password is changed,
3
+ so it can be used to create single-use password reset tokens with ` generates_token_for ` :
4
+
5
+ ``` ruby
6
+ class User < ActiveRecord ::Base
7
+ has_secure_password
8
+
9
+ generates_token_for :password_reset , expires_in: 15 .minutes do
10
+ password_salt&.last(10 )
11
+ end
12
+ end
13
+ ```
14
+
15
+ * L ázaro Nixon *
16
+
1
17
* Improve typography of user facing error messages. In English contractions,
2
18
the Unicode APOSTROPHE (` U+0027` ) is now RIGHT SINGLE QUOTATION MARK
3
19
(` U+2019` ). For example, " can't be blank" is now " can’t be blank" .
Original file line number Diff line number Diff line change @@ -170,6 +170,12 @@ def initialize(attribute)
170
170
attribute_digest . present? && BCrypt ::Password . new ( attribute_digest ) . is_password? ( unencrypted_password ) && self
171
171
end
172
172
173
+ # Returns the salt, a small chunk of random data added to the password before it's hashed.
174
+ define_method ( "#{ attribute } _salt" ) do
175
+ attribute_digest = public_send ( "#{ attribute } _digest" )
176
+ attribute_digest . present? ? BCrypt ::Password . new ( attribute_digest ) . salt : nil
177
+ end
178
+
173
179
alias_method :authenticate , :authenticate_password if attribute == :password
174
180
end
175
181
end
Original file line number Diff line number Diff line change @@ -265,6 +265,21 @@ class SecurePasswordTest < ActiveModel::TestCase
265
265
assert_equal false , @user . authenticate ( " " )
266
266
end
267
267
268
+ test "password_salt" do
269
+ @user . password = "secret"
270
+ assert_equal @user . password_digest . salt , @user . password_salt
271
+ end
272
+
273
+ test "password_salt should return nil when password is nil" do
274
+ @user . password = nil
275
+ assert_nil @user . password_salt
276
+ end
277
+
278
+ test "password_salt should return nil when password digest is nil" do
279
+ @user . password_digest = nil
280
+ assert_nil @user . password_salt
281
+ end
282
+
268
283
test "Password digest cost defaults to bcrypt default cost when min_cost is false" do
269
284
ActiveModel ::SecurePassword . min_cost = false
270
285
Original file line number Diff line number Diff line change @@ -67,7 +67,7 @@ module ClassMethods
67
67
#
68
68
# generates_token_for :password_reset, expires_in: 15.minutes do
69
69
# # Last 10 characters of password salt, which changes when password is updated:
70
- # BCrypt::Password.new(password_digest).salt[-10..]
70
+ # password_salt&.last(10)
71
71
# end
72
72
# end
73
73
#
You can’t perform that action at this time.
0 commit comments