2017-04-06 2 views
0

docs에 따라 인증을 구현했습니다. 여기 내 application_controller.rb레일 4의 OmniAuthGoogleOAuth2 로그인 성공 후 원래 요청 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으로 이동하려고 시도합니다. 나는 그것을 클릭하면

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

그러나, 나는 전무로 리디렉션 할 수 없습니다 성공적으로 로그인하지만 오류가 발생 : 전자 루트 URL과 로그인 링크는이입니다. 왜 매개 변수가 삭제 되었습니까? 또는 일반적으로 로그인 성공 후 원래 요청한 URL로 사용자를 리디렉션하는 더 좋은 방법이 있습니까?

답변

0

링크의 URL 매개 변수를 ?origin=...으로 변경하면 컨트롤러에서 url = request.env['omniauth.origin']을 통해 액세스 할 수 있습니다. 이로 인해 redirect_to url 성명서가 작성됩니다.