2016-01-13 49 views
0

我对这个主题进行了很多研究,但由于某些原因,我无法在我的Ruby on Rails Web应用程序上执行密码复杂性实现。我已经安装了设计宝石,并遵循Best flexible rails password security implementationHow to validate password strength with Devise in Ruby on Rails?无法在Ruby on Rails中执行密码复杂性实现?

我正则表达式似乎是工作,当我检查它的在线

/\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/x 

,但一旦我实现它我user.rb里面是行不通的。

我user.rb文件:

#Active Record for Users 
class User < ActiveRecord::Base 
    belongs_to :entity 
    has_and_belongs_to_many :groups, :join_table => "users_groups" 
    has_many :surveys, inverse_of: :user 
    has_many :results, inverse_of: :user 

    validates :password, :firstName, :email, :salt, :role, :timezone, presence: true 
    validates :email, :uniqueness => {:scope => :entity_id} 
    validates_format_of :email, :with => /[email protected]+\..+/i 

    devise :database_authenticatable, :validatable 
    validate :password_complexity 

    #User Authentication 
    def self.authenticate(email="", lpassword="") 
    users = User.where(email: email) 
    results = [] 
    users.each do |user| 
     if user && user.match_password(lpassword) 
     results.push(user) 
     end 
    end 
    if(results.length == 0) 
    return false 
    else 
    return results 
    end 
    end 

    #Password Check 
    def match_password(lpassword="") 
     return (BCrypt::Password.new(password).is_password?(lpassword+salt)) 
    end 

    #Password Authentication 
    def password_complexity 
     if password.present? and not password.match(/\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/x) 
     errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit" 
     end 
    end 

end 
+1

你是什么意思它“只是不工作”?请修改您的问题,以包括您正在测试此代码的步骤,您期望的结果以及您获得的结果。 –

+0

将'pry'断点设置为'#password_complexity'方法并尝试手动匹配为:'/ \ A(?=。{8,})(?=。* \ d)(?=。* [az])(? =。* [AZ])(?=。* [[:^ alnum:]])/ x =〜password' –

+0

这不起作用,这意味着如果输入的密码与正则表达式不匹配,接受它。 –

回答

1

你是应该的工作是什么,但为什么不这样做只是这样

validates :password, format: { with: /\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/, message: "must include at least one lowercase letter, one uppercase letter, and one digit" } 
+0

为什么我在函数内部做这件事的唯一原因是因为我想稍后将其分解,以便用户可以完全知道他错过了什么,而不仅仅是一般的消息。 –