Omniauth-facebook cancel button

2019-04-08 08:03发布

问题:

I've started integrating facebook authentication into my Rails 3.1 site, but ran into an issue when I click the cancel button on the fb auth dialog. When I click cancel, I get redirected back to my site at /auth/facebook/callback and then redirected to the /login page (I'm using Devise).

What I want to do is redirect a canceled auth to a page that allows the user to create an account the standard way (email, username, password, etc). How can I override the redirect to the /login page?

Btw, I'm using the omniauth-facebook gem.

Thanks!

回答1:

Add failure method in your omniauth callback controller and define your customized behavior.

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
        @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def failure
    redirect_to root_path // here
  end

end


回答2:

I think you may be able to override the default on_failure behavior in your omniauth config, I'm not using devise, but am using the omniauth-facebook gem and have had success with variations on:

OmniAuth.config.on_failure = Proc.new { |env|
  OmniAuth::FailureEndpoint.new(env).redirect_to_failure
} 

or something more custom like:

OmniAuth.config.on_failure do |env|
  new_path = "#{env['SCRIPT_NAME']}#{OmniAuth.config.path_prefix}/failure?message=#{error_type}"

  [302, {'Location' => new_path, 'Content-Type'=> 'text/html'}, []]
end