开发者

Validate password on change of certain fields in RoR

I am building a RoR 3 app, a commu开发者_StackOverflow社区nity. It has a User model and some fields.

So when a user is updating a certain field, like his/her birthday, I want to validate that the User typed in the password that is the same in the database. This way I know that it is the right user trying to change the birthday.

So I ask you how i can create such a validator.

Also I would like to be able to specify an array of which fields the user has to validate the password to change.


This is actually pretty easy to do once you are familiar with the Rails framework.

models/User.rb
class User < ActiveRecord::Base
  validate :correct_password?, :if => :check_password?

  def check_password?
    [birthday_changed?, other_field_changed?].any?
  end

  def correct_password?
    # without knowing more about how you store the password
    # this probably won't work with your code directly
    errors.add_to_base("Must provide password") unless password?
    errors.add_to_base("Incorrect password") unless password == User.find_by_id(id).password
  end
end


Even though building user authentication and authorization is not hard - I would advise to use something like "AuthLogic" or "Devise" gems/plugins which will most likely cover 90% of the functionality that you need. You alsways can customize/add new functionality if needed.

Such plugins will do most of the grunt work for you: generate MVC, create database, do proper security checks, even email password recovery and such.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜