2017-08-14 51 views
1

我基本上是在django頻道的login_required/LoginRequiredMixin等效之後。該文檔有一個authentication section,它描述瞭如何獲得用戶,但它似乎錯過了實際上拒絕訪問未經身份驗證的用戶訪問的位置。拒絕用django頻道訪問未經身份驗證的用戶

from channels.generic.websockets import JsonWebsocketConsumer 

class MyConsumer(JsonWebsocketConsumer): 

    channel_session_user = True 

    def connection_groups(self, **kwargs): 
     return ["test"] 

    def connect(self, message, **kwargs): 
     print message.user # AnonymousUser 
     self.send({"accept": True}) # False here still accepts and sends a message 

如果message.user.is_anonymous爲真,我該如何拒絕/丟棄連接?

回答

2

拒絕對連接嘗試的連接是如此簡單:不發送在所有接受消息,如果你不希望建立一個連接。通道將在配置的時間量後自動關閉(5秒或默認情況下爲默認值)。

def connect(self, message, **kwargs): 
    if not message.user.is_anonymous: 
     self.send({"accept": True}) 

如果你不想等待,並立即關閉連接,只需發送{"close": True}代替:

def connect(self, message, **kwargs): 
    if not message.user.is_anonymous: 
     self.send({"accept": True}) 
    else: 
     self.send({"close": True}) 

爲了完整起見,這裏距離channels docs的解釋。可惜的是,這些信息並沒有在文檔中列出,只在V1.0的發佈說明中列出。

+0

頻道可以關閉還是需要等待超時? – jozxyqk

+0

@jozxyqk:當然,如果你想明確地關閉連接並且不想等待'channels'關閉它,發送'{「close」:True}'而不是'{「accept」:True}'。我會更新答案。 – hoefling

0

只是這樣做:

if user.is_authenticated(): 
    # allow it 
+0

只是爲了澄清,'AnonymousUser.is_authenticated'將始終返回false?我的問題也在問如何禁止它。 – jozxyqk

相關問題