我正在为应用程序使用 django channel channels ,并且我想限制对套接字的访问(仅限授权用户)。
有这个:
@channel_session_user_from_http
def connect_blog(message, username):
user = message.user
try:
user_blog = User.objects.get(username=username)
has_perm = user_blog.check_perm(user.pk)
if not has_perm:
return
except ObjectDoesNotExist:
message.reply_channel.send({
# WebSockets send either a text or binary payload each frame.
# We do JSON over the text portion.
"text": json.dumps({"error": "bad_slug"}),
"close": True,
})
return
Group(user_blog.group_name).add(message.reply_channel)
但是当我检查权限已经连接到套接字时,我该如何控制呢? (如何关闭套接字或控制这种情况)。
感谢和问候。
有一个good tutorial关于 Django channel 。
我的身份验证解决方案:
async def connect(self):
self.user = self.scope["user"]
self.room_name = self.scope['url_route']['kwargs']['id']
self.room_group_name = 'chat_%s' % self.room_name
if self.user.is_authenticated: # also you can add more restrictions here
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
不要忘记根目录中的routing.py
:
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import rooms.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
rooms.routing.websocket_urlpatterns
)
),
})
你可以查看我的consumers.py
的完整代码here .
我是一名优秀的程序员,十分优秀!