Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Application Issues | 129

def generate_salt(login)
Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")
end

def store_password(login, password)
salt = $salts[login] = generate_salt(login)
$hashes[login] = hash(password, salt)
end

def verify_password(login, password)
$hashes[login] == hash(password, $salts[login])
end

store_password('alice', 'kittens')
store_password('bob', 'kittens')

$hashes # => {"alice"=>"955b034a284ed2405c8f1a275e2191484161b1c5",
# "bob"=> "2f7ef18f0f50efd2b8684c49e85befc95509a74f"}
$salts # => {"alice"=>"0682a0e26655e234ee45ea6a68af8ebd3e2c0eaf",
# "bob"=> "6116fb3dc0e9824b7c99e81f6dac6c17b7a6257b"}

verify_password('alice', 'kittens') # => true
verify_password('alice', 'mittens') # => false
verify_password('bob', 'kittens') # => true

This method ensures that the same password will hash to different values with a high
probability. The acts_as_authenticated plugin (http://technoweenie.stikipad.com/
plugins/show/Acts+as+Authenticated) salts passwords by default.


One common reason that people store passwords as plain text is for password recov-
ery. 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 veri-
fies 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 defi-
nition 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.
Free download pdf