Reputation: 137
I am using django channels for an application channels, and i want to restrict access to the socket (authorized users only).
Have this:
@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)
But when I check the permissions has already been connected to the socket, how can I control this? (How to close the socket or control this case).
Thanks and regards.
Upvotes: 2
Views: 1192
Reputation:
There is a good tutorial about Django channels.
And my solution for authentication:
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()
Don't foget about routing.py
in the root:
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
)
),
})
You can view the full code of my consumers.py
here.
Upvotes: 2