Skip to content

Commit

Permalink
[FEATURE-REQUEST]: Websocket via channels[daphne]
Browse files Browse the repository at this point in the history
  • Loading branch information
amadolid committed Aug 14, 2023
1 parent e68e9f5 commit 32f5c87
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 19 deletions.
11 changes: 9 additions & 2 deletions jaseci_serv/jaseci_serv/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,16 @@
"""

import os

from .socket.routing import websocket_urlpatterns
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jaseci_serv.settings")

application = get_asgi_application()
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns)),
}
)
3 changes: 2 additions & 1 deletion jaseci_serv/jaseci_serv/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
# Application definition

INSTALLED_APPS = [
"daphne",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
Expand Down Expand Up @@ -96,7 +97,7 @@
},
]

WSGI_APPLICATION = "jaseci_serv.wsgi.application"
ASGI_APPLICATION = "jaseci_serv.asgi.application"

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
Expand Down
Empty file.
65 changes: 65 additions & 0 deletions jaseci_serv/jaseci_serv/socket/consumer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from json import loads, dumps
from .event_action import authenticated_user
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
from uuid import uuid4
from jaseci_serv.base.models import lookup_global_config
from channels.layers import settings


class SocketConsumer(WebsocketConsumer):
def connect(self):
self.accept()
session_id = None
authenticated = False
target = self.scope["url_route"]["kwargs"]["target"]

if target == "anonymous":
self.target = session_id = str(uuid4())
else:
user = authenticated_user(target)
if user:
self.target = user.master.urn[9:]
authenticated = True
else:
self.target = session_id = str(uuid4())

async_to_sync(self.channel_layer.group_add)(self.target, self.channel_name)
self.send(
text_data=dumps(
{
"type": "connect",
"authenticated": authenticated,
"session_id": session_id,
}
)
)

def receive(self, text_data=None, bytes_data=None):
data = loads(text_data)

async_to_sync(self.channel_layer.group_send)(
self.target, {"type": "notify", "data": data}
)

def notify(self, data):
self.send(text_data=dumps(data))


setattr(
settings,
"CHANNEL_LAYERS",
{
"default": loads(
lookup_global_config(
"CHANNEL_LAYER",
{
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
)
)
},
)
39 changes: 39 additions & 0 deletions jaseci_serv/jaseci_serv/socket/event_action.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
try:
from hmac import compare_digest
except ImportError:

def compare_digest(a, b):
return a == b


import binascii
from knox.crypto import hash_token
from knox.models import AuthToken
from knox.settings import CONSTANTS
from jaseci.jsorc.live_actions import jaseci_action
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.utils import timezone


def authenticated_user(token: str):
for auth_token in AuthToken.objects.filter(
token_key=token[: CONSTANTS.TOKEN_KEY_LENGTH]
):
try:
digest = hash_token(token)
if (
compare_digest(digest, auth_token.digest)
and auth_token.expiry > timezone.now()
):
return auth_token.user
except (TypeError, binascii.Error):
pass
return None


@jaseci_action(act_group=["wb"])
def notify(target: str, data: dict):
async_to_sync(get_channel_layer().group_send)(
target, {"type": "notify", "data": data}
)
6 changes: 6 additions & 0 deletions jaseci_serv/jaseci_serv/socket/routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.urls import path
from . import consumer

websocket_urlpatterns = [
path(r"ws/socket-server/<str:target>", consumer.SocketConsumer.as_asgi())
]
16 changes: 0 additions & 16 deletions jaseci_serv/jaseci_serv/wsgi.py

This file was deleted.

1 change: 1 addition & 0 deletions jaseci_serv/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def get_ver():
"dj-rest-auth[with_social]",
"django-allauth>=0.52.0",
"tzdata>=2022.7",
"channels[daphne]==4.0.0",
],
package_data={
"": [
Expand Down
14 changes: 14 additions & 0 deletions jaseci_serv/templates/examples/social_auth.html
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,18 @@ <h1>Google Identity Services Authorization Token model</h1>
});
{% endif %}
{% endif %}

{% if provider == "google" %}
socket = new WebSocket(`ws://${window.location.host}/ws/socket-server/276a40aec1dffc48a25463c3e2545473b45a663364adf3a2f523b903aa254c9f`)
{% else %}
socket = new WebSocket(`ws://${window.location.host}/ws/socket-server/anonymous`)
{% endif %}
socket.onmessage = (event) => {
console.log(event)
}

function notify-server() {
socket.send(JSON.stringify({"message": "test"}))
}

</script>

0 comments on commit 32f5c87

Please sign in to comment.