我应该如何验证 Rails 中的用户模型
我的用户模型有以下代码:
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 教程借用的。
I have the following code for my user model:
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
What should I add or do differently to make this better? This is mostly borrowed from the Rails Cast #270 and Michael Hartl's ruby on rails tutorial.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
总的来说,这看起来相当不错。
这是关于 根据以下内容验证电子邮件地址的相关问题正则表达式。
对我来说唯一引人注目的是,您似乎以明文形式存储密码,而不是加密存储密码,并且您没有验证密码确认是否与密码匹配。
以下是一个项目中的几行内容,其中我们有相当严格的密码规则。您可能想要调整它们。
将
password_required?
放入其自己的方法中可以让您更灵活地指定要进行验证的环境。关于存储加密的密码,我为此使用了 SHA-1 哈希值。基本上,您存储密码的 SHA-1 哈希值,然后当他们进行身份验证时,您将他们输入的密码的 SHA-1 哈希值与存储的哈希值进行比较。这样密码就不会以明文形式保存。这是一个片段:
这些设置了
User.encrypt(password, salt)
和user.encrypt(password)
方法。使用类级方法生成某人在登录时键入的内容的加密版本,并在保存某人的密码时使用对象级方法。我遗漏了一些内容,但至少这给了你一些思考的机会。注意:这里有有关 SHA-1 哈希值的更多信息,超出您的需要。
In general this looks pretty good.
Here's a related question on doing validation of email addresses based on a regex.
The only thing that seems glaring to me is that it looks like you're storing the password in clear text instead of storing it encrypted and that you're not validating that the password confirmation matches the password.
Here are a couple lines from a project where we had pretty restrictive password rules. You may want to adapt them.
Putting
password_required?
into its own method gives you more flexibility in specifying the circumstances where you want to do the validation.Regarding storing the passwords encrypted, I've used SHA-1 hashes for this. Basically, you store the password's SHA-1 hash, then when they authenticate you compare the SHA-1 hash of the password they enter to the stored hash. That way the password's aren't saved in clear text. Here's a snippet:
These setup both of
User.encrypt(password, salt)
anduser.encrypt(password)
methods. Use the class-level method to generate an encrypted version of what someone types in at login, and use the object-level method when saving someone's password. I've left out some of the pieces, but at least this gives you something to think about.Note: Here's more info on SHA-1 hashes than you'll ever need.