Prev | Current Page 190 | Next

Brad Ediger

"Advanced Rails"


One common reason that people store passwords as plain text is for password recovery.
The reality is that storing and sending passwords in plain text is never a good
idea. The proper way to recover passwords is to send an email to the user with a link
that includes a randomly generated token. The link takes the user to a page that verifies
the token and then allows him to enter a new password.
Password hashing in Rails
In a Rails application, there are some standard best practices for working with
hashed passwords. First, the database contains attributes for the hashed password
and salt:
ActiveRecord::Schema.define do
add_column :users, :crypted_password, :string
add_column :users, :salt, :string
end
ActiveRecord::Schema.define is a simple way to use Rails schema definition
statements from the Rails console or other Rails code outside of
migrations. The full set of schema definition methods (see
ActiveRecord::ConnectionAdapters::SchemaStatements) is available
inside the block.
130 | Chapter 5: Security
The User model has a virtual attribute for the unencrypted password, so that you can
set the password using the instance method User#password= and it will be hashed
automatically. The hashing is performed by a before_save callback:
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
protected
def encrypt_password
return if password.


Pages:
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202