2016-06-07 56 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