diff --git a/apps/audits/models.py b/apps/audits/models.py index e1ae029f1..11f3d93f9 100644 --- a/apps/audits/models.py +++ b/apps/audits/models.py @@ -12,6 +12,7 @@ from django.utils.translation import gettext, gettext_lazy as _ from common.db.encoder import ModelJSONFieldEncoder from common.utils import lazyproperty, i18n_trans +from notifications.ws import WS_SESSION_KEY from ops.models import JobExecution from orgs.mixins.models import OrgModelMixin, Organization from orgs.utils import current_org @@ -275,6 +276,10 @@ class UserSession(models.Model): def backend_display(self): return gettext(self.backend) + @property + def is_active(self): + return caches.sismember(WS_SESSION_KEY, self.key) + @property def date_expired(self): session_store_cls = import_module(settings.SESSION_ENGINE).SessionStore diff --git a/apps/notifications/ws.py b/apps/notifications/ws.py index 391bb659d..bf9e04bdd 100644 --- a/apps/notifications/ws.py +++ b/apps/notifications/ws.py @@ -1,23 +1,27 @@ -import threading import json -from channels.generic.websocket import JsonWebsocketConsumer -from common.utils import get_logger +from channels.generic.websocket import JsonWebsocketConsumer +from django.core.cache import caches + from common.db.utils import safe_db_connection -from .site_msg import SiteMessageUtil +from common.utils import get_logger from .signal_handlers import new_site_msg_chan +from .site_msg import SiteMessageUtil logger = get_logger(__name__) +WS_SESSION_KEY = 'ws_session_key' class SiteMsgWebsocket(JsonWebsocketConsumer): - refresh_every_seconds = 10 sub = None + refresh_every_seconds = 10 def connect(self): user = self.scope["user"] if user.is_authenticated: self.accept() + session = self.scope['session'] + caches.sadd(WS_SESSION_KEY, session.session_key) self.sub = self.watch_recv_new_site_msg() else: self.close() @@ -58,6 +62,8 @@ class SiteMsgWebsocket(JsonWebsocketConsumer): return new_site_msg_chan.subscribe(handle_new_site_msg_recv) def disconnect(self, code): - if self.sub: - self.sub.unsubscribe() - + if not self.sub: + return + self.sub.unsubscribe() + session = self.scope['session'] + caches.srem(WS_SESSION_KEY, session.session_key)