Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rock paper scissors solution #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added backend/game/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions backend/game/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from .models import Game

# Register your models here.
admin.site.register(Game)
6 changes: 6 additions & 0 deletions backend/game/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class GameConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'game'
27 changes: 27 additions & 0 deletions backend/game/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 3.2.6 on 2021-08-02 15:54

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Game',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('won', models.BooleanField(default=False)),
('user_throw', models.CharField(max_length=8, null=True)),
('computer_throw', models.CharField(max_length=8, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='games', to=settings.AUTH_USER_MODEL)),
],
),
]
Empty file.
15 changes: 15 additions & 0 deletions backend/game/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.db import models
from django.contrib.auth.models import User


# Create your models here.
class Game(models.Model):
user = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='games')
won = models.BooleanField(default=False)
user_throw = models.CharField(max_length=8, null=True)
computer_throw = models.CharField(max_length=8, null=True)

def __str__(self) -> str:
return f"Won?: {self.won}"
49 changes: 49 additions & 0 deletions backend/game/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from .models import User, Game


class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'id',
'username',
)


class UserSerializerWithToken(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
password = serializers.CharField(write_only=True)

def get_token(self, obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(obj)
token = jwt_encode_handler(payload)
return token

def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance

class Meta:
model = User
fields = ('id', 'token', 'username', 'password')


class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
fields = (
'id',
'user',
'won',
'user_throw',
'computer_throw',
)
3 changes: 3 additions & 0 deletions backend/game/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
9 changes: 9 additions & 0 deletions backend/game/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from .views import current_user, UserList, get_games, create_game
from django.urls import path

urlpatterns = [
path('current_user/', current_user),
path('users/', UserList.as_view()),
path('users/<int:user_id>/games/', get_games),
path('users/<int:user_id>/games/new/', create_game),
]
81 changes: 81 additions & 0 deletions backend/game/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.http import response
from django.http.response import HttpResponse, JsonResponse
from rest_framework import permissions, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserSerializer, UserSerializerWithToken, GameSerializer
from .models import Game
from django.views.decorators.csrf import csrf_exempt
from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer
import json


# Auth stuff
@api_view(['GET'])
def current_user(request):
"""
Determine the current user by their token, and return their data
"""

serializer = UserSerializer(request.user)
return Response(serializer.data)


class UserList(APIView):
"""
Create a new user. It's called 'UserList' because normally we'd have a get
method here too, for retrieving a list of all User objects.
"""

permission_classes = (permissions.AllowAny, )

def post(self, request, format=None):
serializer = UserSerializerWithToken(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# Will manually define views (vs. using DRF) b/c we only need the CR from CRUD. I manually implemented JWT token validation, but probably should use DRF to handle it automatically.


def get_games(request, user_id):
if not _validate_request(request):
return JsonResponse({'error': 'Could not get games.'})

games_queryset = Game.objects.filter(user_id=user_id)
games_dict = {'games': []}
for game in games_queryset:
game_serializer = GameSerializer(game)
games_dict['games'].append(game_serializer.data)
return JsonResponse(games_dict)


@csrf_exempt
def create_game(request, user_id):
if request.method != 'POST':
return JsonResponse({'error': 'Must be a POST method.'})
if _validate_request(request):
game_obj = json.loads(request.body)
game_obj['user'] = User.objects.get(id=game_obj['user'])
# print(game_obj)
new_game = Game.objects.create(**game_obj)
new_game_serializer = GameSerializer(new_game)
return JsonResponse(new_game_serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse({'error': 'Could not create game.'})


def _validate_request(request):
if 'Authorization' in request.headers:
token = request.headers['Authorization'][4:]
data = {'token': token}
try:
valid_data = VerifyJSONWebTokenSerializer().validate(data)
if 'user' in valid_data:
return True
except:
pass
return False
22 changes: 22 additions & 0 deletions backend/manage.py
Original file line number Diff line number Diff line change
@@ -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', 'rock_scissors_paper.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()
Empty file.
16 changes: 16 additions & 0 deletions backend/rock_scissors_paper/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for rock_scissors_paper 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/3.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

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

application = get_asgi_application()
145 changes: 145 additions & 0 deletions backend/rock_scissors_paper/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import datetime
from pathlib import Path

# 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/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-guy3+4d&wu8qfko+(cl_0&ejbt261b-zr$%rpssqy&=@hm23$v'

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

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

INSTALLED_APPS += [
'game',
'rest_framework',
'corsheaders',
]

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 = 'rock_scissors_paper.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 = 'rock_scissors_paper.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'rock_scissors_paper',
}
}

# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':
('rest_framework.permissions.IsAuthenticated', ),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}

CORS_ORIGIN_WHITELIST = ('https://localhost:3000', 'http://localhost:3000')

JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rock_scissors_paper.utils.my_jwt_response_handler',
# how long the original token is valid for
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),

# allow refreshing of tokens
'JWT_ALLOW_REFRESH': True,

# this is the maximum time AFTER the token was issued that
# it can be refreshed. exprired tokens can't be refreshed.
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
Loading