2016-01-13 48 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

爲什麼我在函數內部做這件事的唯一原因是因爲我想稍後將其分解,以便用戶可以完全知道他錯過了什麼,而不僅僅是一般的消息。 –