Lee Eather Lee Eather - 14 days ago 5
Ruby Question

bypassing methods in model from two different variables in controller?

I have this code in my controller and model

SessionsController

def create
user = User.from_omniauth(env["omniauth.auth"])
user.skip_password_validation = true

unless user.present?
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
# Log the user in and redirect to the user's show page.
else
# Create an error message.
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
else
log_in user
redirect_to user
end
end


user model

def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)

end

def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
end


As i have two, different, login methods in my sessions controller I need to skip methods in my User model. I have looked in to a few things such as before filters, before actions and attribute accessors and search the web but cant seem to find out how to skip methods in the model so I can bypass those for each user variable I have assigned in the sessions controller? Ie, one for omniauth facebook and the other for just standard login.

Answer

If I understood the question properly, in case of plain auth there would be no env["omniauth.auth"] set, so one might go with:

def create
  user = if env["omniauth.auth"]
    User.from_omniauth(env["omniauth.auth"]).tap do |u|
      u.skip_password_validation = true
    end
  else
    User.find_by(email: params[:session][:email].downcase).tap do |u|
      unless user && user.authenticate(params[:session][:password])
        # Create an error message.
        flash.now[:danger] = 'Invalid email/password combination'
        render 'new'
        return
      end
    end
  end

  log_in user
  redirect_to user
end
Comments