让AuthLogic使用ActionCable

时间:2016-06-07 05:54:06

标签: ruby-on-rails ruby authlogic ruby-on-rails-5 actioncable

我正在开发一款新的Rails 5(RC1)应用。我使用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 :: Session :: Base.controller

我试过了:

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

但这不起作用,因为Connection类不是Controller。

我看一下AuthLogic代码,但我无法弄清楚如何绕过它对控制器对象的依赖。我只需要加载用户的会话。有什么想法吗?

2 个答案:

答案 0 :(得分:5)

我自己想通了。我觉得它有点hacky,基本上在我的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

一个潜在的问题是,需要在注销时清除cookie,或者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

答案 1 :(得分:0)

假设您使用Authlogic默认设置,则持久性令牌会存储在密钥“user_credentials&#39;”下的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