【问题标题】:How should I validate User Model in Rails我应该如何在 Rails 中验证用户模型
【发布时间】:2011-10-26 14:06:44
【问题描述】:

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

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 教程中借来的。

【问题讨论】:

  • 评论 :) 我认为正则表达式应该是一个常数。

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


【解决方案1】:

总的来说,这看起来不错。

  • 您允许在电子邮件地址中使用“+”号
  • 您允许电子邮件地址大小写混合。

这是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 哈希与存储的哈希进行比较。这样密码就不会以明文形式保存。这是一个sn-p:

  # 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 比您需要的更多。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 2016-08-10
相关资源
最近更新 更多