让AuthLogic使用ActionCable

问题描述 投票:0回答:2

我正在开发一个新的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代码,但我无法弄清楚如何绕过它对控制器对象的依赖。我只需要加载用户的会话。有什么想法吗?

ruby-on-rails ruby authlogic ruby-on-rails-5 actioncable
2个回答
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

0
投票

假设您使用的是Authlogic默认值,持久性令牌将存储在密钥“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
© www.soinside.com 2019 - 2024. All rights reserved.