Validate password on change of certain fields in RoR - ruby-on-rails

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.

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.

Related

Rails, can validate a user crating a record is admin, from the model?

I am attempting to make a new record object invalid if the user_id of the object is associated with an account that is not admin.
In the model I'd like to make a validation checks if the object to be created user_id.admin == true.
Neither of these solutions work:
validates :user_id, User.find(:user_id).admin?
before_save :user_is_admin, User.find(self.user_id).admin?
So, my question is, how do I write a validation that looks up the user and checks if they are an admin, and throws an error if they are not?
P.S. I am already doing admin checking in the controller as a before_action, but I'd like to invalidate the object if a non admin user manages to create one somehow...and for testing purposes.
If this isn't a best practice I'd still like to know a bit more about creating validity checks in rails.
I generally wouldn't encourage doing this type of authorization at the model/database level. Rather I would suggest that you abstract your authorization code into it's own layer and handle this at the controller level, then rely on tests to verify that nobody can create an object except through the controller.
https://github.com/elabs/pundit is a great gem for integrating an authorization layer into your Rails application.
If you still did want to do this validation at the model level, you could do something like this:
validate :creator_is_admin
def creator_is_admin
errors[:base] << I18n.t('object_class.activerecord.validations.admin_create_check_failure') unless User.find(user_id).try(:admin?)
end
I mostly validating before action goes to the Model, controller could be good for it.
###Post Model Sample
validate :is_admin?
def is_admin?
unless User.find_by_id(user_id).admin
errors.add(:not_admin, "The post not belongs to you || not admin :) ")
end
end

Ruby on Rails: How to validate if on specific page?

In my Ruby on Rails application I am trying to add in validations that will ensure the user has entered a value in a text box. In my system I have a table called Account which stores users' email account information, when they go onto the views/accounts/_form.html.erb page to add a new email account I want to validate the presence of a port number. I can do this through the following code:
validates :port, presence: true
This successfully ensures that users enter their port number, but when a user signs up through the views/users/_new.html.erb page they have to enter only an email address (e.g example#example.com) and the users_controller will then create a record in the Account table for this email address. My problem is that on the views/accounts/_form.html.erb page the port number is required but on the views/users/_new.html.erb it is not.
Is there a way of validating that the user enters the port number if they are on the views/accounts/_form.html.erb page or invoking the create method in the accounts_controller?
I am aware that I could do this through the HTML required validation like so: <%= f.text_field :port, :required => true %> but I need to add in further validation as well as presence, so this is not suitable.
You can create an attr_accessor field that determines if the validation should occur...
class Account < ActiveRecord:Base
attr_accessor :port_needs_validation
validates :port, presence: true, if: -> {port_needs_validation}
Then just set the accessor in your create method...
def create
#account = Account.new
#account.assign_attributes(account_params)
#account.port_needs_validation = true
if #account.save
...
Extract that part of the logic into a form object, check out the legendary 2012 blog entry from CodeClimate. Things have changed since then, the author uses Virtus to build form objects, more popular & up-to-date gems these days are:
reform
dry-rb
active type
but really you can make anything behave like an ActiveModel object
if it's a one-off thing, just do what Steve said in the other answer but that is a sure way to hell, safe-hate and divorce (at least from personal experience) in any slightly teeny weeny bigger project (i.e. you mean to spend some hours more working on it, it's not like you just finished everything and want to go home).
Actually, just use form classes everywhere and avoid model validations & other callbacks at all. You don't want things sending account activation mails or validating your password complexity when you're writing tests and just need a "post" that belongs to "user".
My own favorite personal fuckup due to model callbacks is sending 240.000 "your account has been upgraded/downgraded" emails because of an innocent spelling change update in an account_type attribute migration just because account_type_changed? was true.
So.. Form classes for ever, model callbacks never.
I would not recommend you have model aware of views. In #SteveTurczyn 's solution, an abstract field is introduced into model to identified the which page it come from, which is an good solution.
As from Ruby on Rail MVC, both View and Model talk to the controller, another solution will be have controller handle validation of params before passing the value to create account.

Rails 3 + Devise: How do I change other user's passwords from an admin role?

I've developed a Rails 3 application with Devise for registration and login control. I want to be able to modify any user's password to one I provide.
The solution I've come up with (I haven't had the chance to test it yet) is to make a fake new registration with the password I choose, copy the password from the table record to the user's record in question, and then delete the fake record I generated in the DB. It's not the most elegant thing to do, but it is all I've got. I wait for better suggestions.
I might be misunderstanding the question but it should be as simple as;
#user = User.find(<some id>)
#user.update_attributes(:password => 'anewpassword', :password_confirmation => 'anewpassword')
then their password will be 'anewpassword'

Is there a way in Rails to say "run all the validates EXCEPT :password"?

I am using Devise for my authentication. If a hashed_password isn't set, Rails/Devise's validations will require a password to be set, as well as the password_confirmation.
When I invite new users, I obviously don't want to set their password, so when I create the invitation in my system, it fails because user.password is blank.
I can set a temporary hashed_password on the user, but when they enter their own password, the validation checks for :password and :password_confirmation will not happen because hashed_password is set, which is a real problem.
Is there any way to tell Rails that I want to run all the validations except for the ones associated with :password?
I know Rails has :if conditions, which might fix my problem, but Devise declares the :password validation on my behalf, so that essentially is hidden.
How can I get the desired result here?, hopefully in a way that is not a hack.
My current hypothetical solution that is somewhat messy: The only thing I can think of is to create a new Invitation model that is not the User model, and use the Invitation model for the form. When the invitation is submitted I can validate that Invitation and copy over all the values to the new User model. I can save that User without any validations at all.
That's the best solution I dreamed up.
It seems like my solution will be a lot more work than saying something simple like:
user.save(validations => {:except => :password})
EDIT: I have found one part of the solution, but I am still having problems. In our user model, we can override a Devise method to prevent the validation of the password for invitations with this bit of code:
#protected
def password_required?
!is_invited && super
end
The is_invited attribute is just a column I added to the users table/model.
However, there is one gotcha here. When a user accepts an invitation and they arrive to the form where they need to set their password/password_confirmation, valid? will always return true.
This one has me deeply perplexed. I don't see how requires_password? and valid? can be true at the same time. If it requires the password, it should do a validation check and cause the validations to fail.
I'm starting to hate Devise - or just the idea of using gems to build parts of your application in a blackbox. I think the real solution probably is to rip out Devise and just do it all from scratch. That way your app has total control of how all of this works :(
I recently started using this great devise add-on: devise_invitable
It's commonly used so users (or any model) can invite other users to join.
But I adapt it for manually (via an admin panel) invite new potential users to my app.
Hope this helps!

Authenticate users by Customer, Login and Password with Authlogic

I've got a typical Authlogic setup that I need to enhance to require Customer ID in addition to Login and Password.
I've read a bit about using a custom find method and another about using a global variable for accessing the additional parameter and a third referring to documentation about using scopes that doesn't seem to exist.
Seems like this should be easy, but I can't seem to find the right approach.
Anyone got a solution?
In your UserSession class, add:
find_by_login_method :find_by_customer_id_or_login
In your User class, create this customer finder:
def self.find_by_customer_id_or_login(login)
User.find_by_customer_id(login) || User.find_by_login(login)
end
This is assuming a User has both a customer_id field and a login field.
Add a customer_id column through a migration and validate_presence_of :customer_id on your model. It doesn't have anything to do with authlogic. Unless there is more that you are trying to do.

Resources