Deny access to unauthenticated users with django channels
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life
--
Chapters
00:00 Question
00:51 Accepted answer (Score 3)
01:47 Answer 2 (Score 0)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/4566...
Question links:
[authentication section]: https://channels.readthedocs.io/en/stabl...
Accepted answer links:
[channels docs]: http://channels.readthedocs.io/en/latest...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #djangochannels
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life
--
Chapters
00:00 Question
00:51 Accepted answer (Score 3)
01:47 Answer 2 (Score 0)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/4566...
Question links:
[authentication section]: https://channels.readthedocs.io/en/stabl...
Accepted answer links:
[channels docs]: http://channels.readthedocs.io/en/latest...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #djangochannels
#avk47
ACCEPTED ANSWER
Score 3
Denying the connection on connect attempt is as simple as this: do not send the accept message at all if you don't want to establish a connection. Channels will close it automatically after a configured amount of time (5 seconds or smth like that by default).
def connect(self, message, **kwargs):
if not message.user.is_anonymous:
self.send({"accept": True})
If you do not want to wait and close the connection immediately, just send {"close": True} instead:
def connect(self, message, **kwargs):
if not message.user.is_anonymous:
self.send({"accept": True})
else:
self.send({"close": True})
For the sake of completeness, here is the explanation from the channels docs. Sadly, this information is not listed in the documentation itself, only in release notes to v1.0.
ANSWER 2
Score 0
Just do this:
if user.is_authenticated():
# allow it