Skip to content

Commit

Permalink
Merge pull request #325 from zstenger93/game_home
Browse files Browse the repository at this point in the history
Game home
  • Loading branch information
zstenger93 authored Apr 27, 2024
2 parents 9d2a113 + efdf9b7 commit b86c9cb
Show file tree
Hide file tree
Showing 38 changed files with 1,587 additions and 686 deletions.
2 changes: 1 addition & 1 deletion Makefile
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ all:

runb:
daphne -b 0.0.0.0 backend.asgi:application
# http://localhost:8000/chat/
# http://10.12.2.4:8000/chat/


execbackend:
Expand Down
Empty file modified README.md
100644 → 100755
Empty file.
29 changes: 29 additions & 0 deletions backend/auto_reload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import signal
import subprocess

class MyHandler(FileSystemEventHandler):
def __init__(self, process):
self.process = process

def on_modified(self, event):
if event.src_path.endswith('.py'):
print(f'File changed: {event.src_path}. Restarting server.')
self.process.kill()
self.process = subprocess.Popen(['daphne', '-b', '0.0.0.0', '-p', '8000', 'backend.asgi:application'])

process = subprocess.Popen(['daphne', '-b', '0.0.0.0', '-p', '8000', 'backend.asgi:application'])
event_handler = MyHandler(process)
observer = Observer()
observer.schedule(event_handler, path='.', recursive=True)
observer.start()

try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
16 changes: 10 additions & 6 deletions backend/backend/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@
"""

import os
import game.routing
import chat.routing

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



os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')

# application = ProtocolTypeRouter({
Expand All @@ -28,13 +31,14 @@
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
chat.routing.websocket_urlpatterns +
game.routing.game_websocket_urlpatterns
)
),
})


with open('text.txt', 'a') as f:
f.write('deleting user channel names\n')
from chat.models import UserChannelName
UserChannelName.objects.all().delete()
# with open('text.txt', 'a') as f:
# f.write('deleting user channel names\n')
# from chat.models import UserChannelName
# UserChannelName.objects.all().delete()
161 changes: 78 additions & 83 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG')
SECRET_KEY = os.getenv("SECRET_KEY")
DEBUG = os.getenv("DEBUG")

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

# SECURITY WARNING: don't run with debug turned on in production!

Expand All @@ -32,53 +33,56 @@
if DEBUG == 'True':
REDIRECT_URI = "https://10.12.2.2"
else:
REDIRECT_URI = "https://transcendence-backend-znhl.onrender.com"
REDIRECT_URI = "https://transcendence-backend-znhl.onrender.com"

if DEBUG == 'True':
print("DEBUG: True: ", DEBUG)
if DEBUG == "True":
print("DEBUG: True: ", DEBUG)
else:
print("DEBUG: False: ", DEBUG)
print("DEBUG: False: ", DEBUG)

# Application definition

INSTALLED_APPS = [
"daphne",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_otp',
'django_otp.plugins.otp_totp',
'rest_framework',
'rest_framework_simplejwt.token_blacklist',
'corsheaders',
'user_api.apps.UserApiConfig',
'friendship',
'friendship_api',
'chat',
"daphne",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_otp",
"django_otp.plugins.otp_totp",
"friendship",
"rest_framework",
"rest_framework_simplejwt.token_blacklist",
"corsheaders",
"user_api.apps.UserApiConfig",
"friendship_api",
"user_block",
"game",
"chat",
]

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django_otp.middleware.OTPMiddleware',
'django.middleware.security.SecurityMiddleware',
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django_otp.middleware.OTPMiddleware",
"django.middleware.security.SecurityMiddleware",
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
]
CSRF_ALLOWED_ORIGINS = [

"https://10.12.2.2",
"https://api.intra.42.fr",
"http://localhost:3000",
"http://frontend:3000",
"https://transcendence-frontend-3otz.onrender.com",
"https://zstenger93.github.io"
"https://zstenger93.github.io",
]

CORS_ALLOWED_ORIGINS = [
Expand All @@ -97,37 +101,35 @@
# SESSION_COOKIE_SAMESITE = 'Lax'

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'user_api.authentication.BlacklistCheckJWTAuthentication',
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
"DEFAULT_AUTHENTICATION_CLASSES": (
"user_api.authentication.BlacklistCheckJWTAuthentication",
),
}


ROOT_URLCONF = 'backend.urls'
ROOT_URLCONF = "backend.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',
"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 = 'backend.wsgi.application'
WSGI_APPLICATION = "backend.wsgi.application"

## User model
AUTH_USER_MODEL = 'user_api.AppUser'
AUTH_USER_MODEL = "user_api.AppUser"


# Database
Expand All @@ -142,46 +144,44 @@
# }

# THIS IS THE DATABASE CONFIGURATION FOR THE DOCKER CONTAINER
if DEBUG == 'True':
if DEBUG == "True":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'transcend_users_db',
'USER': 'transcend_user',
'PASSWORD': 'transcend_pwd',
'HOST': 'db',
'PORT': '5432',
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "transcend_users_db",
"USER": "transcend_user",
"PASSWORD": "transcend_pwd",
"HOST": "db",
"PORT": "5432",
}
}
else:
DATABASES = {
'default': dj_database_url.parse(os.getenv('DATABASE_URL'))
}
DATABASES = {"default": dj_database_url.parse(os.getenv("DATABASE_URL"))}

# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]

# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -191,40 +191,35 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_URL = "/static/"
# STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'static'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = BASE_DIR / "static"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# For the custom user model to work we need to include this line
# AUTH_USER_MODEL = 'authentication.User'



MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=99),
"ACCESS_TOKEN_LIFETIME": timedelta(days=99),
}


EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'sayy uonp nado adlm'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = "sayy uonp nado adlm"
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

# chat settings
ASGI_APPLICATION = "backend.asgi.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer'
}
}
CHANNEL_LAYERS = {"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}}
2 changes: 1 addition & 1 deletion backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@
path('api/', include('friendship_api.urls')),
# path('api/', include('friendship.urls')),
path('chat/', include('chat.urls')),

path('game/', include('game.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
7 changes: 4 additions & 3 deletions backend/chat/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
from channels.exceptions import StopConsumer
from asgiref.sync import sync_to_async

import logging

logger = logging.getLogger(__name__)

class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
Expand All @@ -12,7 +15,7 @@ async def connect(self):
if not self.scope['user'].is_authenticated:
await self.close()
raise StopConsumer('User is not authenticated')

logger.info(f'User {self.scope["user"]} connected to the chat.')
username = self.scope['user'].username
self.room_name = username + '_chat_room'
self.room_group_name = 'general_group'
Expand Down Expand Up @@ -48,8 +51,6 @@ async def connect(self):
)




async def disconnect(self, close_code):

################# DELETE USER CHANNEL NAME #################
Expand Down
Loading

0 comments on commit b86c9cb

Please sign in to comment.