我应该如何在Rails中验证用户模型

时间:2011-10-26 14:06:44

标签: ruby-on-rails ruby-on-rails-3 validation models

我的用户模型有以下代码:

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

    email_regex = /\A[\w+\-.]+@[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教程。

1 个答案:

答案 0 :(得分: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比你需要的还多。