ruby-on-railsdeviseomniauth-facebook

How can I show an error if user signs in via Facebook and desn't provide his email


In my web app, I have a devise gem for registration and 2 omniauth gems (Google and Facebook). The situation is as follows: If a user doesn't provide an email signing up with Facebook, the application raises an exception: Validation failed: Email can't be blank. This is how my from_omniauth method looks like in a User model:

def self.from_omniauth(auth, sign_in_resource = nil)

    # Get the identity and usesr if they exist
    identity = Identity.find_from_oauth(auth)

    # If a signed_in_resosurce is provided it always overrides the existing user
    # to prvent the identity being locked with accidentally created accounts.
    user = sign_in_resource ? sign_in_resource : identity.user

    # Create the user if needed
    if user.nil?

      # Get the exsiting user by email *Assuming that they provide valid_email address.
      user = User.where(email: auth.info.email ).first

      # Create the user if its a new registeration
      if user.nil?
        user = User.new email: auth.info.email, password: Devise.friendly_token[0,20]

        #Disable confirmation so we don't need to send confirmation email
        # user.skip_confirmation!

        user.save!
      end
    end

    # Associate the identity with the user if needed
    if identity.user != user
      identity.user = user
      identity.save!
    end

    # Get the basic information and create Profile, Address model
    unless user.profile.present?
      first_name = auth.info.first_name.present? ? auth.info.first_name : auth.info.name.split(' ')[0]
      last_name = auth.info.last_name.present? ? auth.info.last_name : auth.info.name.split(' ')[1]
      profile = Profile.new(user_id: user.id,
                            first_name: first_name,
                            last_name: last_name,
                            gender: auth.extra.raw_info.gender)
      profile.save(validate: false)
      address = Address.new(addressable_id: profile.id, addressable_type: 'Profile')
      address.save(validate: false)
    end
    user.reload
  end

The exception raises on user.save! Is it possible to redirect the user to some other page, or just to show a flash message? I know that the business logic, such as redirect and other stuff, has to be executed in the controller. So, maybe, there is a way to move the method I've written above to the controller? Thanks ahead.


Solution

  • Use rescue_from class method in your controller.

    class YourController < ApplicationController
    
        rescue_from ::ActiveRecord::RecordInvalid, with: :validation_failed
    
        ...
    
        def validation_failed(exception)
           flash[:error] = exception.message
           redirect_to request.referer || root_path
        end
    
    end