Skip to content

Commit eceb1ff

Browse files
committed
Add Secure Passwords With Rails And Bcrypt as a rails til
1 parent ee36333 commit eceb1ff

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_758 TILs and counting..._
13+
_759 TILs and counting..._
1414

1515
---
1616

@@ -481,6 +481,7 @@ _758 TILs and counting..._
481481
- [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md)
482482
- [Rescue From](rails/rescue-from.md)
483483
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)
484+
- [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md)
484485
- [Select A Select By Selector](rails/select-a-select-by-selector.md)
485486
- [Select Value For SQL Counts](rails/select-value-for-sql-counts.md)
486487
- [Set Schema Search Path](rails/set-schema-search-path.md)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Secure Passwords With Rails And Bcrypt
2+
3+
If you are using [`bcrypt`](https://github.com/codahale/bcrypt-ruby) (at
4+
least version 3.1.7), then you can easily add secure password functionality
5+
to an
6+
[ActiveRecord](https://github.com/rails/rails/tree/master/activerecord)
7+
model. First, ensure that the table backing the model has a
8+
`password_digest` column. Then add
9+
[`has_secure_password`](https://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html)
10+
to your model.
11+
12+
```ruby
13+
class User < ActiveRecord::Base
14+
has_secure_password
15+
16+
# other logic ...
17+
end
18+
```
19+
20+
You can now instantiate a `User` instance with any required fields as well
21+
as `password` and `password_confirmation`. As long as `password` and
22+
`password_confirmation` match then an encrypted `password_digest` will be
23+
created and stored. You can later check a given password for the user using
24+
the `authenticate` method.
25+
26+
```ruby
27+
user = User.find_by(email: user_params[:email])
28+
29+
if(user.authenticate(user_params[:password]))
30+
puts 'That is the correct password!'
31+
else
32+
puts 'That password did not match!'
33+
end
34+
```

0 commit comments

Comments
 (0)