This commit is contained in:
Raphael Rouiller
2024-07-08 14:06:52 +02:00
commit aa54287126
96 changed files with 2718 additions and 0 deletions

View File

View File

@ -0,0 +1,33 @@
"""
ASGI config for ChatApp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ChatApp.settings')
asgi_app = get_asgi_application()
from chat import routing
application = ProtocolTypeRouter(
{
"http" : asgi_app,
"websocket" : AuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns
)
)
}
)
ASGI_APPLICATION = 'ChatApp.asgi.application'

View File

@ -0,0 +1,176 @@
"""
Django settings for ChatApp project.
Generated by 'django-admin startproject' using Django 4.2.13.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import sys
from pathlib import Path
import environ
env = environ.Env()
sys.path.append('/home/archive/user_auth_system')
SECRET_KEY_ENV = env('SECRET_KEY_USER')
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = SECRET_KEY_ENV
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
IP_ADDRESS= env('IP_ADDRESS')
DB_NAME = env('DB_ARCHIVE_NAME')
DB_USER = env('DB_ARCHIVE_USER')
DB_PASSWORD = env('DB_ARCHIVE_PASSWORD')
DB_HOST = env('DB_ARCHIVE_HOST')
DB_PORT = env('DB_ARCHIVE_PORT')
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'chat.apps.ChatConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'daphne',
'django.contrib.staticfiles',
'channels',
'corsheaders',
'user_management'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ChatApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ChatApp.wsgi.application'
ASGI_APPLICATION = 'ChatApp.asgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': DB_NAME,
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
'CONFIG': {
"hosts": [('redis', 6379)],
},
},
}
LOGIN_REDIRECT_URL = "room"
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = ['https://localhost', 'https://' + IP_ADDRESS]
# Connexion to CustomUser
AUTH_USER_MODEL = 'user_management.CustomUser'

View File

@ -0,0 +1,23 @@
"""
URL configuration for ChatApp project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("chat.urls")),
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for ChatApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ChatApp.settings')
application = get_wsgi_application()

View File

View File

@ -0,0 +1,5 @@
from django.contrib import admin
from .models import *
# Register your models here.
# admin.site.register(User) #?? I don't need this user

View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class ChatConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'chat'

View File

@ -0,0 +1,49 @@
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from .models import ChatMessage, ChatRoom
class ChatConsumer(AsyncWebsocketConsumer):
@database_sync_to_async
def create_chat(self, room_name, message, username):
return ChatMessage.objects.create(room_name=room_name, message=message, username=username)
async def connect(self):
self.user = self.scope['user']
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f"chat_{self.room_name}"
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self , close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json["message"]
username = text_data_json["username"]
room = await self.get_room_instance(self.room_name)
await self.create_chat(room, message, username)
await self.channel_layer.group_send(
self.room_group_name,{
"type" : "sendMessage",
"message" : message,
"username" : username,
})
async def sendMessage(self, event) :
message = event["message"]
username = event["username"]
await self.send(text_data = json.dumps({"message" : message ,"username" : username}))
@database_sync_to_async
def get_room_instance(self, room_name):
return ChatRoom.objects.get(room_name=room_name)

View File

@ -0,0 +1,7 @@
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2']

View File

View File

@ -0,0 +1,24 @@
from django.db import models
from django.conf import settings
class ChatRoom(models.Model):
room_name = models.CharField(max_length=255, unique=True, default='default')
user1 = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user1', on_delete=models.CASCADE)
user2 = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user2', on_delete=models.CASCADE)
def __str__(self):
return self.room_name
class ChatMessage(models.Model):
room_name = models.ForeignKey(ChatRoom, default='99999', related_name='messages', on_delete=models.CASCADE)
message = models.TextField()
username = models.CharField(max_length=100)
timestamp = models.DateTimeField(auto_now_add=True)
def as_dict(self):
return {
"room_name": self.room_name,
"message": self.message,
"username": self.username,
"timestamp": self.timestamp.isoformat(),
}

View File

@ -0,0 +1,8 @@
from django.urls import path , include
from chat.consumers import ChatConsumer
# Here, "" is routing to the URL ChatConsumer which
# will handle the chat functionality.
websocket_urlpatterns = [
path("chat/<str:room_name>/", ChatConsumer.as_asgi()),
]

View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@ -0,0 +1,9 @@
from django.urls import path, include
from chat import views as chat_views
from django.contrib.auth.views import LogoutView, LoginView
urlpatterns = [
path("chat/<str:username>/", chat_views.chatRoom, name="chat_room"),
path('users_list/', chat_views.userList, name='user_list'),
]

View File

@ -0,0 +1,56 @@
from .models import *
from .forms import *
from django.http import JsonResponse
from rest_framework import status
from django.middleware.csrf import get_token
from django.shortcuts import get_object_or_404
from django.db.models import Q
from user_management.models import CustomUser
from django.core import serializers
import json
def chatRoom(request, username):
print("-+--+--+-- chatRoom function in views.py - beginning ---+--+-")
if not request.user.is_authenticated:
return JsonResponse({"error": "User not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
other_user = get_object_or_404(CustomUser, username=username)
if other_user == request.user:
# Prevent users from chatting with themselves
return JsonResponse({"error": "User cannot chat with herself/himself"}, status=status.HTTP_403_FORBIDDEN)
# Check if the other user is blocked by the authenticated user
if request.user.blocked_users.filter(id=other_user.id).exists():
return JsonResponse({"error": "User is blocked"}, status=status.HTTP_403_FORBIDDEN)
room_name = f"{min(request.user.id, other_user.id)}_{max(request.user.id, other_user.id)}"
chat_room = ChatRoom.objects.filter(Q(user1=request.user, user2=other_user) | Q(user1=other_user, user2=request.user)).first()
if not chat_room:
chat_room = ChatRoom.objects.create(user1=request.user, user2=other_user, room_name=room_name)
messages = ChatMessage.objects.filter(room_name=chat_room).order_by('timestamp')
serialized_messages = serializers.serialize('json', messages)
messages_list = json.loads(serialized_messages)
print( "-- room_name: ", room_name)
print( "-- username: ", request.user.username)
print("-- messages: ", serialized_messages)
print("-- other_user: ", other_user.username)
context = {
"room_name": room_name,
"username": request.user.username,
"messages": messages_list,
"other_user": other_user.username,
"status": status.HTTP_200_OK
}
return JsonResponse(context, status=status.HTTP_200_OK)
def userList(request):
if not request.user.is_authenticated:
return JsonResponse({"error": "User not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
if request.method == 'POST':
users = CustomUser.objects.exclude(username=request.user.username)
user_data = [{'username': user.username} for user in users]
return JsonResponse({'users': user_data}, status=status.HTTP_200_OK)
return JsonResponse({"error": "Invalid request method"}, status=status.HTTP_405_METHOD_NOT_ALLOWED)

22
chat/ChatApp/manage.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ChatApp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()