diff --git a/app/models/user.rb b/app/models/user.rb index 19f6cc3..c896ff5 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,11 +1,33 @@ +require 'bcrypt' + class User < ActiveRecord::Base + include BCrypt + + attr_accessor :password + attr_accessible :email, :password, :password_confirmation + validates_presence_of :email - validates_presence_of :password + + validates :password, + :presence => true, + :confirmation => true + + before_save :hash_password def self.authenticate(email, password) user = find_by_email(email) return false if user.nil? - #FIXME use bcrypt - return user if user.password == password + return user if Password.new(user.password_hash) == password + end + + + private + + def hash_password + self.password_hash = bcrypt(password) + end + + def bcrypt(string) + return Password.create(string) end end diff --git a/db/migrate/20110809130610_add_password_hash_to_users.rb b/db/migrate/20110809130610_add_password_hash_to_users.rb new file mode 100644 index 0000000..b38ed33 --- /dev/null +++ b/db/migrate/20110809130610_add_password_hash_to_users.rb @@ -0,0 +1,11 @@ +class AddPasswordHashToUsers < ActiveRecord::Migration + def self.up + add_column :users, :password_hash, :string + remove_column :users, :password + end + + def self.down + remove_column :users, :password_hash + add_column :users, :password, :string + end +end diff --git a/db/schema.rb b/db/schema.rb index d895941..b04519e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20110805201426) do +ActiveRecord::Schema.define(:version => 20110809130610) do create_table "playlists", :force => true do |t| t.string "name" @@ -38,9 +38,9 @@ ActiveRecord::Schema.define(:version => 20110805201426) do create_table "users", :force => true do |t| t.string "email" - t.string "password" t.datetime "created_at" t.datetime "updated_at" + t.string "password_hash" end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 027aae6..99180c7 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -24,6 +24,26 @@ describe User do it { should_not be_valid } end + context 'when password_confirmation does not match password' do + before do + user.password_confirmation = 'WRONG' + end + + it { should_not be_valid } + end + + describe '#hash_password' do + it 'is received when #save is sent' do + user.should_receive(:hash_password) + user.save + end + + it 'stores a bcrypt hash of the password' do + user.save + BCrypt::Password.new(user.password_hash).should == user.password + end + end + describe '.authenticate' do let (:user) { Factory.create(:user) }