From 7f9245570f5ed06c1f4a7bf84069209cd7eceab2 Mon Sep 17 00:00:00 2001 From: cuom1999 Date: Mon, 15 Jun 2020 15:19:00 -0500 Subject: [PATCH] Add authentication to chatbox --- chat_box/consumers.py | 17 ++++++++++++----- templates/chat/chat.html | 4 ---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/chat_box/consumers.py b/chat_box/consumers.py index 60893c9..c38deb5 100644 --- a/chat_box/consumers.py +++ b/chat_box/consumers.py @@ -5,6 +5,7 @@ from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from django.core import serializers +from judge.jinja2.gravatar import gravatar from judge.models.profile import Profile @@ -32,8 +33,15 @@ class ChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] - - message_saved = save_data_and_return(message) + + author = self.scope['user'] + author = Profile.objects.get(id=author.id) + + message['author'] = author.username + message['css_class'] = author.css_class + message['image'] = gravatar(author, 32) + + message_saved = save_data_and_return(message, author) message['time'] = message_saved[0]['fields']['time'] message['id'] = message_saved[0]['pk'] @@ -56,10 +64,9 @@ class ChatConsumer(AsyncWebsocketConsumer): # return time -def save_data_and_return(message): +def save_data_and_return(message, author): new_message = Message(body=message['body'], - author=Profile.objects - .get(pk=message['author_id']), + author=author, ) new_message.save() json_data = serializers.serialize("json", diff --git a/templates/chat/chat.html b/templates/chat/chat.html index 9dd3293..878a673 100644 --- a/templates/chat/chat.html +++ b/templates/chat/chat.html @@ -141,10 +141,6 @@ message = { 'body': body, - 'image': img, - 'author': '{{request.profile}}', - 'author_id': {{request.profile.id}}, - 'css_class': '{{request.profile.css_class}}', } chatSocket.send(JSON.stringify({