2011-10-26 30 views
1

我已經爲我的用戶模型下面的代碼:我應該如何驗證在Rails的用戶模型

class User < ActiveRecord::Base 
    has_secure_password 
    attr_accessible :name, :email, :password, :password_confirmation 

    email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 

    validates :name, :presence => true, 
        :length => { :maximum => 50 } 
    validates :email, :presence => true, 
        :format => { :with => email_regex }, 
        :uniqueness => { :case_sensitive => false } 


    validates_presence_of :password, :on => :create 
end 

我應該怎麼添加或做什麼不同,使這個更好?這大部分來自Rails Cast#270和Michael Hartl的Ruby on Rails教程。

+0

評論:)和正則表達式應該是一個常數,我認爲。 – Bohdan

回答

2

一般來說這看起來不錯。

  • 您允許的電子郵件地址「+」號
  • 您允許的電子郵件地址是混合大小寫。

這裏有doing validation of email addresses based on a regex.

,似乎明顯的對我來說唯一一個相關的問題是,它看起來像你存儲明文密碼,而不是將其存儲加密的和你不驗證密碼確認與密碼匹配。

下面是一個項目中的幾條線,我們有一個非常嚴格的密碼規則。你可能想調整它們。

validates_presence_of  :password, :if => :password_required? 
    validates_confirmation_of :password, :if => :password_required?, :message => "Your password and confirmation must match." 
    validates_format_of  :password, :with => /^[\S]{4,}$/, :message => "Your password must be at least 4 characters and contain no spaces or tabs.", :if => :password_required? 

    def password_required? 
    self.new_record? 
    end 

password_required?到它自己的方法,讓你在指定你想要做驗證的情況下,更多的靈活性。

關於存儲加密的密碼,我已經使用了SHA-1哈希值。基本上,您存儲密碼的SHA-1哈希值,然後在他們進行身份驗證時,將他們輸入的SHA-1哈希值與所存儲的哈希值進行比較。這樣密碼不會以明文形式保存。這裏有一個片段:

# Encrypts some data with the salt. 
    def self.encrypt(password, salt) 
    Digest::SHA1.hexdigest("--#{salt}--#{password}--") 
    end 

    # Encrypts the password with the user salt 
    def encrypt(password) 
    self.class.encrypt(password, salt) 
    end 

這些設置的兩個User.encrypt(password, salt)user.encrypt(password)方法。使用類級方法生成登錄時輸入的內容的加密版本,並在保存某人的密碼時使用對象級別的方法。我遺漏了一些部分,但至少這給了你一些想法。

注意:這裏的more info on SHA-1 hashes比你所需要的。

+2

他使用來自Rails 3.1的has_secure_password負責加密。 http://apidock.com/rails/ActiveModel/SecurePassword/ClassMethods/has_secure_password – Rasmus