Skip to content
Browse files

Implement secure passwords creation

  • Loading branch information...
1 parent 2308f6f commit 0c14faab7cef65b37db9805ce862f2855e2e524a @chischaschos committed Mar 3, 2014
Showing with 65 additions and 6 deletions.
  1. +30 −4 lib/todo/models/user.rb
  2. +8 −2 lib/todo/services/session_creator.rb
  3. +27 −0 spec/models/user_spec.rb
View
34 lib/todo/models/user.rb
@@ -1,20 +1,40 @@
+require 'bcrypt'
+
module Todo
module Models
class User
include DataMapper::Resource
+ include BCrypt
- property :id, Serial
- property :email, String
- property :password, String
+ property :id, Serial
+ property :email, String
+ property :password_hash, String, length: 250
has 1, :session, 'Todo::Models::Session'
has n, :list_items, 'Todo::Models::ListItem'
validates_presence_of :email
validates_format_of :email, as: :email_address
validates_uniqueness_of :email
+ validates_with_block :password do
+ self.password_hash || [ false, 'Invalid Password' ]
+ end
+
+ def initialize(*args)
+ super(*args)
+ self.password = args.first && args.first[:password]
+ end
+
+ def password
+ @password ||= Password.new(password_hash)
+ end
- validates_presence_of :password
+ def password=(new_password)
+ if valid_password?(new_password)
+ @password = Password.create(new_password)
+ self.password_hash = @password
+ end
+ end
def to_json
{ id: self.id }.to_json
@@ -24,6 +44,12 @@ def h_errors
{ errors: self.errors.to_hash }
end
+ private
+
+ def valid_password?(new_password)
+ new_password && new_password.size > 5
+ end
+
end
end
View
10 lib/todo/services/session_creator.rb
@@ -23,8 +23,14 @@ def valid?
private
def user
- @user ||= Todo::Models::User.first(email: @params[:email],
- password: @params[:password])
+ unless @user
+ user = Todo::Models::User.first(email: @params[:email])
+ if user.password == @params[:password]
+ @user = user
+ end
+ end
+
+ @user
end
def create_session
View
27 spec/models/user_spec.rb
@@ -0,0 +1,27 @@
+require 'spec_helper'
+
+describe Todo::Models::User do
+ context 'when validating the password' do
+ it 'should need a password' do
+ expect(subject).not_to be_valid
+ expect(subject.errors.to_hash.keys).to eq([ :email, :password])
+ end
+
+ it 'should not accept empty passwords' do
+ user = Todo::Models::User.new password: ''
+ expect(user).not_to be_valid
+ expect(user.errors.to_hash.keys).to eq([ :email, :password])
+ end
+
+ it 'should not accept passwords with less than 6 characters' do
+ user1 = Todo::Models::User.new password: '12345'
+ expect(user1).not_to be_valid
+ expect(user1.errors.to_hash.keys).to eq([ :email, :password])
+
+ user2 = Todo::Models::User.new password: '123456'
+ expect(user2).not_to be_valid
+ expect(user2.errors.to_hash.keys).to eq([ :email ])
+ end
+
+ end
+end

0 comments on commit 0c14faa

Please sign in to comment.
Something went wrong with that request. Please try again.