Skip to content

Commit

Permalink
Merge branch 'develop' into 73-create-realtime-pong
Browse files Browse the repository at this point in the history
  • Loading branch information
massahito committed Jul 24, 2024
2 parents 4a8ca99 + 389bb07 commit cf49e99
Show file tree
Hide file tree
Showing 35 changed files with 1,093 additions and 624 deletions.
3 changes: 3 additions & 0 deletions .devcontainer/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ services:
- type: bind
source: ../pong/pong/static
target: /usr/share/nginx/html/static
- type: bind
source: ../pong/media
target: /var/www/uploads
depends_on:
app:
condition: service_healthy
Expand Down
2 changes: 2 additions & 0 deletions .devcontainer/requirements/Django/Containerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ RUN python -m venv /app/.venv && \
. /app/.venv/bin/activate && \
pip install -r requirements.txt

RUN echo 'source /app/.venv/bin/activate' >> ~/.bashrc

COPY ./entrypoint.sh /usr/local/bin/entrypoint.sh

RUN chmod +x /usr/local/bin/entrypoint.sh
Expand Down
2 changes: 2 additions & 0 deletions .devcontainer/requirements/Django/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ uvicorn==0.30.1
channels==4.1.0
channels_redis==4.2.0
websockets==12.0.0
ruff==0.5.2
pillow==10.4.0
5 changes: 5 additions & 0 deletions .devcontainer/requirements/Nginx/conf.d/default.conf
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ server {
alias /usr/share/nginx/html/static;
}

location /media {
alias /var/www/uploads;
try_files $uri =404;
}

location / {
proxy_pass http://django;
}
Expand Down
11 changes: 11 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: ruff
on: push
jobs:
ruff:
name: syntax-check-python
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
with:
args: 'format --check'
41 changes: 40 additions & 1 deletion api/openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ paths:
schema:
type: string
description: 認証トークンとリフレッシュトークン
example: JWTTOKEN=jwttoken; JWTREFRESH=refresh-jwttoken Secure; HttpOnly
example: JWTTOKEN=jwttoken; JWTREFRESH=refresh-jwttoken Secure; HttpOnly
content:
"application/json":
schema:
Expand Down Expand Up @@ -86,6 +86,29 @@ paths:
$ref: "#/components/schemas/postTokenVerifyResponse"
"401":
$ref: "#/components/responses/badRequest"
/pong/api/v1/users/{uuid}:
get:
summary: ユーザー情報取得
description: ユーザー情報取得
parameters:
- name: uuid
in: path
description: ユーザーのUUID
required: true
schema:
type: string
example: b4cf1ef4-1cab-490b-a32c-f6528f95c796
responses:
"200":
description: ユーザー情報取得成功
content:
"application/json":
schema:
$ref: "#/components/schemas/getUserResponse"
"400":
$ref: "#/components/responses/badRequest"
"404":
$ref: "#/components/responses/notFoundError"
components:
responses:
badRequest:
Expand Down Expand Up @@ -180,6 +203,22 @@ components:
type: string
description: ユーザーのUUID
example: b4cf1ef4-1cab-490b-a32c-f6528f95c796
getUserResponse:
type: object
description: ユーザー情報取得成功
properties:
uuid:
type: string
description: ユーザーのUUID
example: b4cf1ef4-1cab-490b-a32c-f6528f95c796
name:
type: string
description: ユーザー名
example: ユーザー名
email:
type: string
description: メールアドレス
example: [email protected]
errorMessage:
type: object
properties:
Expand Down
4 changes: 1 addition & 3 deletions pong/config/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,16 @@

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import re_path
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django_asgi_app = application = get_asgi_application()

# import consumers here
from pong.middleware.auth import ChannelsJWTAuthenticationMiddleware
from .consumers import SampleConsumer
from realtime_pong_game.consumers import PlayerConsumer

application = ProtocolTypeRouter({
Expand Down
3 changes: 1 addition & 2 deletions pong/config/consumers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import AnonymousUser

class SampleConsumer(AsyncWebsocketConsumer):

class SampleConsumer(AsyncWebsocketConsumer):
async def connect(self):
if self.scope["user"] == AnonymousUser():
await self.close()
Expand All @@ -15,4 +15,3 @@ async def connect(self):

async def receive(self, text_data=None, bytes_data=None):
print(text_data)

117 changes: 63 additions & 54 deletions pong/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from pathlib import Path
import datetime
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Expand All @@ -23,12 +22,12 @@
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-f9o0g5c=(hz*lj*=qppxb4$+l-#2#g)+lr2#2f-#m*8fiskm^#'
SECRET_KEY = "django-insecure-f9o0g5c=(hz*lj*=qppxb4$+l-#2#g)+lr2#2f-#m*8fiskm^#"

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

ALLOWED_HOSTS = ['*']
ALLOWED_HOSTS = ["*"]


# Application definition
Expand All @@ -45,48 +44,48 @@
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'pong.middleware.auth.JWTAuthenticationMiddleware'
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"pong.middleware.auth.JWTAuthenticationMiddleware",
]

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


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
import os;

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.getenv("POSTGRES_NAME"),
'USER': os.getenv("POSTGRES_USER"),
'PASSWORD': os.getenv("POSTGRES_PASSWORD"),
'HOST': 'db',
'PORT': 5432
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": os.getenv("POSTGRES_NAME"),
"USER": os.getenv("POSTGRES_USER"),
"PASSWORD": os.getenv("POSTGRES_PASSWORD"),
"HOST": "db",
"PORT": 5432,
}
}

Expand All @@ -96,26 +95,26 @@

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 @@ -125,39 +124,49 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = 'static/'
STATIC_URL = "static/"
STATIC_ROOT = "static/"

# 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"

# 追加
AUTH_USER_MODEL = 'pong.User'
PRIVATE_KEY_PATH = os.path.join(BASE_DIR, 'keys', 'private_key.pem')
PUBLIC_KEY_PATH = os.path.join(BASE_DIR, 'keys', 'public_key.pem')
with open(PRIVATE_KEY_PATH, 'r') as f:
AUTH_USER_MODEL = "pong.User"
PRIVATE_KEY_PATH = os.path.join(BASE_DIR, "keys", "private_key.pem")
PUBLIC_KEY_PATH = os.path.join(BASE_DIR, "keys", "public_key.pem")
with open(PRIVATE_KEY_PATH, "r") as f:
PRIVATE_KEY = f.read()
with open(PUBLIC_KEY_PATH, 'r') as f:
with open(PUBLIC_KEY_PATH, "r") as f:
PUBLIC_KEY = f.read()
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=30),
'JWT_PRIVATE_KEY': PRIVATE_KEY,
'JWT_PUBLIC_KEY': PUBLIC_KEY,
'JWT_ALGORITHM': 'RS256',
"JWT_EXPIRATION_DELTA": datetime.timedelta(days=1),
"JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=30),
"JWT_PRIVATE_KEY": PRIVATE_KEY,
"JWT_PUBLIC_KEY": PUBLIC_KEY,
"JWT_ALGORITHM": "RS256",
}
OAUTH_CALLBACK_42API = os.getenv('OAUTH_CALLBACK_42API')
CLIENT_ID_42API = os.getenv('CLIENT_ID_42API')
CLIENT_SECRET_42API = os.getenv('CLIENT_SECRET_42API')

# channelsのためのlayerの追加 
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

PEPPER = os.getenv("PEPPER")
OAUTH_CALLBACK_42API = os.getenv("OAUTH_CALLBACK_42API")
CLIENT_ID_42API = os.getenv("CLIENT_ID_42API")
CLIENT_SECRET_42API = os.getenv("CLIENT_SECRET_42API")

REDIS_HOST = "redis"
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"

# channelsのためのlayerの追加
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("redis", 6379)],
"hosts": [("redis", REDIS_PORT)],
},
},
}
7 changes: 4 additions & 3 deletions pong/config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
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, re_path, include
from pong.views.index import index

urlpatterns = [
path('admin/', admin.site.urls),
path('pong/', include('pong.urls')),
re_path(r'^.*$', index, name='index'),
path("admin/", admin.site.urls),
path("pong/", include("pong.urls")),
re_path(r"^.*$", index, name="index"),
]
2 changes: 1 addition & 1 deletion pong/config/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

application = get_wsgi_application()
5 changes: 3 additions & 2 deletions pong/manage.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/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', 'config.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
Expand All @@ -18,5 +19,5 @@ def main():
execute_from_command_line(sys.argv)


if __name__ == '__main__':
if __name__ == "__main__":
main()
Binary file added pong/media/defaults/default.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pong/media/uploads/test.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 0 additions & 2 deletions pong/pong/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from django.contrib import admin

# Register your models here.
Loading

0 comments on commit cf49e99

Please sign in to comment.