2017-04-06 106 views
0

按照docs我實現了身份驗證。這裏是我的application_controller.rbOmniAuthGoogleOAuth2在Rails 4中成功登錄後重定向到原始請求url

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 
    helper_method :current_user 
    before_action :auth_user 

    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 

    private 
    def auth_user 
    current_user 
    if @current_user.nil? 
     flash[:notice] = "You need to be logged in to access this part of the site" 
     redirect_to root_path(url: request.url) 
    end 
    end 
end 

,我使用這個 「登錄」 鏈接

<%= link_to "Sign in with Google", "/auth/google_oauth2?url=#{@url}", id: "sign_in" %> 

路線:get 'auth/:provider/callback', to: 'user_sessions#create'

控制器:

class UserSessionsController < ApplicationController 
    skip_before_filter :auth_user 
    def create 
    url = params[:url] 
    auth = env["omniauth.auth"] 
    if auth 
     user = User.from_omniauth(auth) 
     session[:user_id] = user.id 
     flash[:notice] = "Login Sucessful!" 
     redirect_to url 
    else 
     flash[:notice] = "error" 
     redirect_to root_path 
    end 

    end 

    def destroy 
    session[:user_id] = nil 
    redirect_to root_path 
    end 
end 

現在,當我沒有一個有效的會話嘗試去localhost:3000/privileged我被重定向到th Ë根URL和登錄鏈接是這樣的:

http://localhost:3000/auth/google_oauth2?url=http://localhost:3000/privileged 

然而,當我點擊它,我得到一個成功登錄,但隨後的錯誤,我不能重定向到零。爲什麼參數下降?或者是否有更好的方式將用戶重定向到通常成功登錄後最初請求的URL?

回答

0

它的工作原理是當我將鏈接中的url parmae​​ter更改爲?origin=...,然後在控制器中,我可以通過url = request.env['omniauth.origin']訪問它。這使得redirect_to url聲明工作