2016-05-17 45 views
0

我正在使用rails 4應用程序,並且正在使用另一個站點的API使用example.com,它使用3腿oauth授權(與Twitter相同)。爲了實現這個功能,我使用了這個link並且實現了相同的功能。存儲重定向網址,以便以後在rails 4中使用

這是我實現

AuthController

class AuthController < ApplicationController 
    before_filter :authenticate_user! 
    before_filter :fetch_request_token, only: [:authorize] 

    def authorize 
    token = @consumer.get_request_token(oauth_callback: 'http://localhost:3000/auth/fetch_access_token') 
    authorize_url = token.authorize_url 
    redirect_to authorize_url 
    end 

    def fetch_access_token 
    acc_token = request_token.get_access_token(oauth_verifier: params[:oauth_verifier]) 
    # remaining logic 
    redirect_to files_jds_path 
    end 

    private 

    def fetch_request_token 
    #logic for fetching request token 
    end 
end 

JDsController

class JDsController < AuthController 
    before_filter :authorize, only: [:files, :field_info] unless: :check_access_token 

    def files 
    # logic for the files 
    end 

    def field_info 
    # logic for the files 
    end 

    private 

    def check_access_token 
    # logic for checking access_token 
    end 
end 

目前我檢查的access_token存在或不採取任何行動之前,如果ACCESS_TOKEN不存在,那麼我使用授權m來獲取access_token ethod。

如果您看到方法從AuthController(這是我的回調url),其中我有硬編碼重定向路徑爲files_jds_path

由於此實現雖然before_filter應用於field_info,但在獲取access_token後,它將重定向到files_jds_path

但我需要將其推廣,以便對於任何操作它將重定向到相應的路徑。

任何人都可以建議我怎麼能做到這一點

+0

我想我明白你在問什麼。您希望能夠將某人授權後重新發送給他們正在尋找的原始頁面? – bkunzi01

+0

我是否正確地假設您使用基於令牌的身份驗證而不是會話? – max

+0

我正在使用基於會話的身份驗證。目前的實施只關聯帳戶。 –

回答

1

你可能設置OAuth的回調URL中包括一個查詢參數的路徑。 Facebook和Twitter允許這樣做。

class AuthController < ApplicationController 
    before_filter :authenticate_user! 
    before_filter :fetch_request_token, only: [:authorize] 

    def authorize 

    uri = URI('http://localhost:3000/auth/fetch_access_token') 
    uri.query = { redirect_to: params[:referrer] }.to_query if params[:referrer] 


    token = @consumer.get_request_token(oauth_callback: uri) 
    authorize_url = token.authorize_url 
    redirect_to authorize_url 
    end 

    def fetch_access_token 
     acc_token = request_token.get_access_token(
     oauth_verifier: params[:oauth_verifier] 
     ) 
     # remaining logic 
     redirect_to params[:referrer] || files_jds_path 
    end 
end 
+0

在附註上 - 我會通過爲OAuth提供者創建[OmniAuth策略](https://github.com/intridea/omniauth)來做到這一點。 – max

相關問題