Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do you return validation errors ? #24

Closed
thecritic opened this issue Oct 16, 2016 · 3 comments
Closed

How do you return validation errors ? #24

thecritic opened this issue Oct 16, 2016 · 3 comments

Comments

@thecritic
Copy link

thecritic commented Oct 16, 2016

First of all, thank you for creating this gem!

I created the auth providers for Google/FB as shown in the Wiki, however, there is a use case where a user has already signed up with a normal account in the past and then tries to log in with Facebook/Google where the email already exists. This would throw an ActiveRecord::RecordInvalid exception upon account creation, how am I supposed to get that into the response to let the user know that an account with that email already exists ?

Here is the code:

doorkeeper.rb

resource_owner_from_assertion do
    provider = params[:provider]
    case provider
    when "google"
      g = ExternalAuth::Google.new(params[:assertion])
      g.get_user!
    when "facebook"
      f = ExternalAuth::Facebook.new(params[:assertion])
      begin
        f.get_user!
      rescue ActiveRecord::RecordInvalid => e
        #what happens here ? 
      end 
      end
    end
  end

facebook_auth.rb

def get_user!
  if user_data.present?
    user = User.where(fb_id: user_data["id"]).first
    if user.blank?
      user = User.new(
        remote_profile_image_url: image["data"]["url"], 
        fb_id: user_data["id"], 
        firstname: user_data["first_name"], 
        lastname: user_data["last_name"], 
        email: user_data["email"]
      )
      user.password = SecureRandom.hex
      user.save!
    end
      user
  else
    nil
  end
end
@matfiz
Copy link
Collaborator

matfiz commented Oct 26, 2016

I guess the easiest would be to raise an instance of DoorkeeperError (aka StandardError), eg:
raise Doorkeeper::Errors::DoorkeeperError.new('email already exists')

@matfiz
Copy link
Collaborator

matfiz commented Oct 26, 2016

Or another idea, however I do not know if it will serve your case. Why not to check the existing users against fb_id OR email? Something like

user=User.where('fb_id=? or email=?',user_data["id"],user_data["email"]).first

In such a way, you can match and log in the user by email, possibly updating the fb_id if it is empty.

@thecritic
Copy link
Author

Thanks a lot @matfiz, second solution was bang on!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants