问题描述
为什么我无法在频道内检索current_user
或应该如何检索current_user
?
Why am I not able to retrieve current_user
inside my channel or how should I retrieve current_user
?
我用什么?
- Rails 5.0.1 --api (我没有任何意见,也不使用咖啡)
- 我使用react-native应用程序测试此 (无需授权即可正常运行)
- 我不使用devise进行身份验证 (我使用JWT而不是使用Knock ,因此没有cookie)
如 rubydoc所述,尝试在ActionCable频道内获取current_user
.info
Trying to get current_user
inside my ActionCable channel as described in rubydoc.info
代码看起来像
class MessageChannel < ApplicationCable::Channel
identified_by :current_user
def subscribed
stream_from 'message_' + find_current_user_privileges
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
protected
def find_current_user_privileges
if current_user.has_role? :admin
'admin'
else
'user_' + current_user.id
end
end
end
运行它,我得到这个错误:
And running it, I get this error:
[NoMethodError - undefined method `identified_by' for MessageChannel:Class]
如果我删除identified_by :current_user
,我会得到
[NameError - undefined local variable or method `current_user' for #<MessageChannel:0x7ace398>]
推荐答案
如果看到提供的文档,您将知道identified_by
不是Channel
实例的方法.这是Actioncable::Connection
的方法.从Rails的《 Actioncable概述》指南中,这是Connection
类的样子:
If you see the doc you provided, you will know that identified_by
is not a method for a Channel
instance. It is a method for Actioncable::Connection
.From Rails guide for Actioncable Overview, this is how a Connection
class looks like:
#app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
private
def find_verified_user
if current_user = User.find_by(id: cookies.signed[:user_id])
current_user
else
reject_unauthorized_connection
end
end
end
end
如您所见,current_user
在此处不可用.相反,您必须在连接中在此处创建current_user
.
As you can see, current_user
is not available here. Instead, you have to create a current_user
here in connection.
websocket服务器没有会话,但是可以读取与主应用程序相同的cookie.所以我想,您需要在身份验证后保存cookie.
The websocket server doesn't have a session, but it can read the same cookies as the main app. So I guess, you need to save cookie after authentication.
这篇关于如何在ActionCable rails-5-api应用中获取current_user?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!