Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bypass password validation in the following OmniAuth login method?

I have some password validation for my User model, and a create_with_omniauth method to get the information from the user's Facebook account:

user.rb:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation

  has_secure_password

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
                    format:     { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true

  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["info"]["name"]
      user.email = auth["info"]["email"]
    end
  end
end

Now when I click link_to "Sign in with Facebook, "auth/facebook" I get this error:

Validation failed: Password can't be blank, Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank

Because of this two lines in the User model:

 validates :password, presence: true, length: { minimum: 6 }
 validates :password_confirmation, presence: true

How to bypass that validation when the user is trying to log in with the OmniAuth login method?

like image 658
alexchenco Avatar asked Nov 02 '12 02:11

alexchenco


1 Answers

This can be done in 2 ways .

1) Just save a random secure generated number in the password field (better because it's easy and also to maintain the consistency) personally I have applied this method as the users who have signed through a social site will not login through site login.

2) Or, use an attr_accesor

 :login_social (will be treated as boolean  
 validates :password, presence: true, length: { minimum: 6 }, :if => !login_social?
 validates :password_confirmation, presence: true, :if => :login_social?

Whenever logging through any social site just make this field true. I followed the second method then turned to the first solution as it was better.

Personally I suggest you go for the first method

like image 178
Aayush Khandelwal Avatar answered Sep 21 '22 05:09

Aayush Khandelwal