Ruby on rails 环境[';典狱长';]不使用导轨5

Ruby on rails 环境[';典狱长';]不使用导轨5,ruby-on-rails,Ruby On Rails,我按照这个指南使用WebSocket创建聊天功能。 我遇到了一个问题,env['warden']。用户在我使用标准设计表单登录到应用程序时没有重新调整任何内容 如果我使用另一种方法(现在已经被注释了),它将返回错误的用户 module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.

我按照这个指南使用WebSocket创建聊天功能。

我遇到了一个问题,
env['warden']。用户
在我使用标准设计表单登录到应用程序时没有重新调整任何内容

如果我使用另一种方法(现在已经被注释了),它将返回错误的用户

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.email
    end

    protected

    def find_verified_user # this checks whether a user is authenticated with devise
      verified_user = env['warden'].user

      if verified_user
        verified_user
      else
        reject_unauthorized_connection
      end
    end

    # def find_verified_user
    #     user_id = request.headers['HTTP_AUTHORIZATION']
    #     if verified_user = User.find_by(user_id)
    #        verified_user
    #     else
    #        reject_unauthorized_connection
    #     end
    # end

  end
end

我找到了这篇文章的解决方案

我不知道它是如何运作的,但它确实做到了。它将如何帮助有类似问题的人

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.email
    end

    protected
    def find_verified_user
      verified_user = User.find_by(id: cookies.signed['user.id'])
      if verified_user && cookies.signed['user.expires_at'] > Time.now
        verified_user
      else
        reject_unauthorized_connection
      end
    end

  end
end

使用Desive进行身份验证时,我遇到了同样的问题,而接受的答案对我没有帮助。我的错误在routes.rb文件中。 我把:
mount ActionCable.server放在:'/cable'

authenticate:user do
块内。将它移动到:
Rails.application.routes.draw do
块中,为我解决了这个问题。

我也遇到了同样的问题,但结果证明我的问题是因为我有两个设计模型:
User
Customer
,因为用户用于管理,所以Customer被设置为Warden的
默认范围
。因此,要访问
用户
范围,我必须执行以下操作

env['warden'].user(:user)
末尾的符号定义了要使用的范围


我在这里找到了关于Warden范围内用户的信息:

这就是它与活动管理员默认管理员用户和“正常”用户模型结合使用的方式。指向ref的链接已失效。
Warden::Manager.after_set_user do |user,auth,opts|
  scope = opts[:scope]
  auth.cookies.signed["#{scope}.id"] = user.id
  auth.cookies.signed["#{scope}.expires_at"] = 60.minutes.from_now
end

Warden::Manager.before_logout do |user, auth, opts|
  scope = opts[:scope]
  auth.cookies.signed["#{scope}.id"] = nil
  auth.cookies.signed["#{scope}.expires_at"] = nil
end
env['warden'].user(:user)