Ruby on rails - 使用devise / omniauth进行身份验证后重定向到以前的url

时间:2016-11-29 15:15:59

标签: ruby-on-rails-4 redirect devise omniauth

我正在使用devise gem以及omniauth gem用于Facebook,Twitter& Instagram的。以下是我使用的gem

gem 'devise'
gem 'omniauth'
gem 'omniauth-twitter'
gem 'omniauth-facebook'
gem 'omniauth-instagram'
gem 'twitter'
gem 'instagram'

我跟随this toturial通过Twitter和Facebook设置设计。

在我的omniauth_callbacks_controller.rb内,我设置了generic_callback这样的功能:

def generic_callback( provider )
    @identity = Identity.find_for_oauth env["omniauth.auth"]
    @user = @identity.user || current_user
    if @user.nil?
      @tempUser = User.find_by_email(@identity.email) unless @identity.email.blank?
      if @tempUser.nil?
          @user = User.create(email: @identity.email, display_name: @identity.display_name, avatar: @identity.avatar, provider: @identity.provider || nil )
      else
        @user = @tempUser
      end
      @identity.update_attribute( :user_id, @user.id )
    end
    if @user.email.blank? && @identity.email
      @user.update_attribute( :email, @identity.email)
    end
    if @user.persisted?
      @identity.update_attribute( :user_id, @user.id )

      @user = FormUser.find @user.id
      sign_in_and_redirect @user, event: :authentication
      set_flash_message(:notice, :success, kind: provider.capitalize) if is_navigational_format?
    else
      session["devise.#{provider}_data"] = env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end 

一切正常,我想要实现的是重定向用户签署 sign_up 强>

在设置omniauth gem并且仅使用devise gem之前,我在application_controller.rb中使用了此方法:

def after_sign_in_path_for(resource)
  session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users/ || request.fullpath =~ /\/macbook1/
end 

仅在使用devise时才有效,但现在如果此方法位于application_controller.rb内,我会收到此错误:

Error after sign_in or sign_out

我也尝试了这个错误:

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

sign_in或sign_up 之后,我需要做些什么才能redirect用户以前的网址

1 个答案:

答案 0 :(得分:0)

application_controller.rb内,您需要两种方法:store_location& after_sign_in_path_for

application_controller.rb

class ApplicationController < ActionController::Base
    after_filter :store_location

    def store_location
      return unless request.get?
      if (request.path != new_user_session_path &&
          request.path != new_user_registration_path &&
          request.path != "/users/password/new" &&
          request.path != "/users/password/edit" &&
          request.path != "/users/confirmation" &&
          request.path != "/users/edit" &&
          request.path != destroy_user_session_path &&
          !request.xhr?) # don't store ajax calls
        session[:previous_url] = request.fullpath
      end
    end

    def after_sign_in_path_for(resource)
      request.env['omniauth.origin'] || stored_location_for(resource) || root_path || request.fullpath =~ /\/admin/
    end

end