mirror of https://github.com/rails/rails
Added ability to specify which passwords you want as weak passwords
This commit is contained in:
parent
863de37b05
commit
a39a333769
|
@ -5,8 +5,6 @@ module ActiveModel
|
|||
module SecurePassword
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
WEAK_PASSWORDS = %w( password qwerty 123456 )
|
||||
|
||||
module ClassMethods
|
||||
# Adds methods to set and authenticate against a BCrypt password.
|
||||
# This mechanism requires you to have a password_digest attribute.
|
||||
|
@ -42,6 +40,27 @@ module ActiveModel
|
|||
validates_presence_of :password_digest
|
||||
validate :password_must_be_strong
|
||||
end
|
||||
|
||||
# Allows you to specify the set of weak passwords that will be validated against
|
||||
# if you specify has_secure_password in your model.
|
||||
#
|
||||
# The default set of weak passwords are:
|
||||
#
|
||||
# class User < ActiveRecord::Base
|
||||
# weak_passwords = %w( password qwerty 123456 mypass )
|
||||
# end
|
||||
def weak_passwords=(*values)
|
||||
@weak_passwords = values.flatten
|
||||
end
|
||||
|
||||
# Returns the list of current weak passwords defined. Defaults to the standard
|
||||
# list of 'password', 'qwerty' and '123456'
|
||||
#
|
||||
# User.weak_passwords #=> ['password', 'qwerty', '123456']
|
||||
def weak_passwords
|
||||
@weak_passwords ||= %w( password qwerty 123456 )
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
# Returns self if the password is correct, otherwise false.
|
||||
|
@ -64,7 +83,7 @@ module ActiveModel
|
|||
def password_must_be_strong
|
||||
if password.present?
|
||||
errors.add(:password, :too_short, :count => 7) unless password.size > 6
|
||||
errors.add(:password, :insecure) if WEAK_PASSWORDS.include?(password)
|
||||
errors.add(:password, :insecure) if self.class.weak_passwords.include?(password)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -2,10 +2,30 @@ require 'cases/helper'
|
|||
require 'models/user'
|
||||
|
||||
class SecurePasswordTest < ActiveModel::TestCase
|
||||
|
||||
setup do
|
||||
User.weak_passwords = %w( password qwerty 123456 )
|
||||
@user = User.new
|
||||
end
|
||||
|
||||
test "there should be a list of default weak passwords" do
|
||||
assert_equal %w( password qwerty 123456 ), User.weak_passwords
|
||||
end
|
||||
|
||||
test "specifying the list of passwords" do
|
||||
User.weak_passwords = %w( pass )
|
||||
assert_equal %w( pass ), User.weak_passwords
|
||||
end
|
||||
|
||||
test "adding to the list of passwords" do
|
||||
User.weak_passwords << 'pass'
|
||||
@user.password = "password"
|
||||
assert !@user.valid?
|
||||
|
||||
@user.password = "pass"
|
||||
assert !@user.valid?
|
||||
end
|
||||
|
||||
test "password must be present" do
|
||||
assert !@user.valid?
|
||||
assert_equal 1, @user.errors.size
|
||||
|
|
Loading…
Reference in New Issue