0

I am working on Facebook authentication for Devise and I stumbled upon one problem - when will try to sign up someone with Facebook email that is already in the system, I get an error (which is partially correct).

I would need to redirect this user back to the homepage and there to print out this issue, but at the moment I am having this message printed as an error (on localhost).

Here's how I am doing that (user model):

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info

    if user = User.where(:provider => 'facebook', :uid => data.id).first
      user
    else # Create a user with a stub password. 
      user = User.create!(:first_name => data.first_name,
                          :last_name => data.last_name,
                          :email => data.email, 
                          :password => Devise.friendly_token[0,20],
                          :provider => 'facebook',
                          :uid => data.id,
                          :terms_of_use => true) 
    end
    return user if user
  end

How to redirect the user on a page where would be printed out the validation messages?

Thanks

1 Answer 1

1

Why don't you have something like this in your model and controller

Return just the user object from the method

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    #Look for the first user with provider: :facebook & uid: data.id,
    #If now user is there go ahead and create one with first_or_create.
    user = User.where(:provider => 'facebook', :uid => data.id).first_or_create do |user|
           user.first_name = data.first_name,
           user.last_name = data.last_name,
           user.email = data.email,
           user.password = Devise.friendly_token[0,20],
           user.provider = 'facebook',
           user.uid = data.id,
           user.terms_od_use = true
          end
  end

Controller

def sign_in_method #dummy method
  user = User.find_for_facebook_oauth(access_token, signed_in_resource=nil)
  if user.valid?
    redirect success_url #any url where u want to redirect on success 
  else user.errors
     redirect root_url, error: user.errors.full_messages.join(', ')
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Have you ever heard of first_or_create? This piece of code is awful.
i know it's super bad. I wanted to give him a idea of how to take errors and redirect, rather refactor. Because that's what he asked.
@MichaelSzyndel, added first_or_create ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.