Devise doesn't redirect properly to stored loc

2020-02-02 12:55发布

问题:

I have in my app some actions which are protected and need user authentication. Since I'm using devise, I use authenticate_user! before filter to protect them. Whenever user hits the protected page, devise ask the user to login and then redirects back to the protected page. This part works perfectly.

The problem is that when user tries to login with Facebook through my app, devise doesn't redirect the user to the protected page after login. It always throw the user back to root url. With standard authentication this is not a problem

I am suspecting it has something to do with passthru method which devise - omniauth integration requires. Any help would be greatly appreciated

Here is my code snippet for omniauth callback:

def facebook
# You need to implement the method below in your model
omniauth = request.env["omniauth.auth"]
@user = User.find_for_facebook_oauth(omniauth, current_user)

if @user.persisted?
  flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
  sign_in_and_redirect @user, :event => :authentication
else
  session["devise.facebook_data"] = env["omniauth.auth"]
  redirect_to new_user_registration_url
end
end

def passthru
  render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end

回答1:

We use Facebook JS to get the access code which then returns back to the omniauth_callback_controller.rb and signs the user in.

I found that the origin URL is saved in the request. Worked a treat for us.

in application_controller.rb

def after_sign_in_path_for(resource_or_scope)
   if request.env['omniauth.origin']
      request.env['omniauth.origin']
    end
end