gpt4 book ai didi

devise - ActionCable 中的多个连接

转载 作者:行者123 更新时间:2023-12-02 17:30:37 24 4
gpt4 key购买 nike

我的应用程序中有两个设计身份验证模型,并且想要在它们之间创建聊天。有人可以帮我为用户编写连接吗?以下是我所拥有的。我想检查是否可以让两个连接根据不同用户的个人登录拒绝其连接。如有任何帮助,我们将不胜感激。

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

def connect
self.current_user = find_verified_user
self.current_supplier = find_verified_supplier
end

private
def find_verified_user
if current_user = env['warden'].user('user')
current_user
end
end

def find_verified_supplier
if current_supplier = env['warden'].user('supplier')
current_supplier
else
reject_unauthorized_connection
end
end
end
end

最佳答案

稍微改编自this tutorial :

# app/channels/application_cable/connection.rb

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

def connect
find_verified
end

protected

def find_verified
setup_user if verified_user
setup_supplier if verified_supplier

reject_unauthorized_connection unless [current_supplier, current_user].any?
end

def verified_user
cookies.signed['user.expires_at'].present? &&
cookies.signed['user.expires_at'] > Time.zone.now
end

def verified_supplier
cookies.signed['supplier.expires_at'].present? &&
cookies.signed['supplier.expires_at'] > Time.zone.now
end

def setup_supplier
self.current_supplier = Supplier.find_by(id: cookies.signed['supplier.id'])
logger.add_tags 'ActionCable', "#{current_supplier.model_name.name} #{current_supplier.id}"
end

def setup_user
self.current_user = User.find_by(id: cookies.signed['user.id'])
logger.add_tags 'ActionCable', "#{current_user.model_name.name} #{current_user.id}"
end
end
end

还有:

# config/initializers/warden_hooks.rb

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"] = 30.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

关于devise - ActionCable 中的多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com