views:

24

answers:

2

Hello, I am building a RoR 3 app, a community. 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.

Thanks, Micke

A: 

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.

Zepplock
Bit i want to do it myself :)
Micke
+1  A: 

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
Samuel
That's great! Thanks!
Micke