2016-06-07 58 views
0

我正在開發一個新的Rails 5(RC1)應用程序。我使用AuthLogic進行用戶身份驗證,並且它一直很好,直到我有了ActionCable。使AuthLogic與ActionCable一起工作

#app/channels/application_cable/connection.rb 
module ApplicationCable 
    class Connection < ActionCable::Connection::Base 
    identified_by :current_user 

    def connect 
     self.current_user = UserSession.find 
    end 
    end 
end 

我得到的錯誤:你必須用一個控制器對象激活Authlogic ::會議:: Base.controller創建對象

我嘗試過:

Authlogic::Session::Base.controller = Authlogic::ControllerAdapters::RailsAdapter.new(self) 

但是,這並不因爲Connection類不是控制器。

我看着AuthLogic代碼,但我無法弄清楚如何繞過它對控制器對象的依賴。我只需要加載用戶的會話。有什麼想法嗎?

回答

3

我想出了我自己的想法。我覺得這是有點怪異的,基本上在我的ApplicationController中,我使用AuthLogic persistence_token設置了一個安全的cookie,然後我可以讀取該令牌並手動加載ActionCable中的用戶。

class ApplicationController < ActionController::Base 
    before_action :set_verify_cookie 

    def set_verify_cookie 
    #action cable needs a way outside of controller logic to lookup a user 
    return unless current_user 
    cookies.signed[:vvc] = current_user.persistence_token 
    end 
end 

#app/channels/connection.rb 
module ApplicationCable 
    class Connection < ActionCable::Connection::Base 
    identified_by :current_user 


    def connect 
     self.current_user = find_verified_user 
     logger.add_tags 'ActionCable', self.current_user.username unless self.current_user.nil? 
    end 

    protected 

    def find_verified_user_or_guest 
     User.find_by(:persistence_token => cookies.signed[:vvc]) 
    end 
end 

一個潛在gotch,餅乾需要在註銷被清除或ActionCable仍然會發現在後續頁面加載的用戶。

#app/controllers/user_sessions_controller.rb 
class UserSessionsController < ApplicationController 

    def destroy 
    cookies.signed[:vvc] = nil 
    current_user_session.destroy 
    flash[:success] = "Logout successful!" 
    redirect_to root_url 
    end 
end 
+0

很不錯的解決方案!很好的答案。 請只編輯這一行:'self.current_user = find_verified_user' For:'self.current_user = find_verified_user_or_guest' – ZombieBsAs

0

假設您使用的是Authlogic默認值,持久性令牌存儲在Cookie'user_credentials'下的cookie中。

所以,你可以查找你的用戶是這樣的:

# app/channels/application_cable/connection.rb 
module ApplicationCable 
    class Connection < ActionCable::Connection::Base 

    def connect 
     verify_user 
    end 

    private 
    def verify_user 
     reject_unauthorized_connection unless verified_user? 
    end 

    def verified_user? 
     cookie_key && User.find_by_persistence_token(token) 
    end 

    def token 
     cookie && cookie.include?('::') && cookie.split("::")[0] 
    end 

    def cookie 
    cookies['user_credentials'] 
    end 

    end 
end