diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f1a9fa1 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,20 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.yml] +indent_size = 2 + +[*.yaml] +indent_size = 2 + +[Makefile] +indent_style = tab +indent_size = 4 diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..6deafc2 --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 120 diff --git a/.gitignore b/.gitignore index b6e4761..b6c4e54 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.vscode + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8285b54 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.8 + +ADD . /app +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + bash \ + default-libmysqlclient-dev \ + build-essential \ + && pip install --no-cache-dir -r /app/requirements.txt + +CMD ["/app/commands/run-prod.sh"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9861ac6 --- /dev/null +++ b/Makefile @@ -0,0 +1,20 @@ +all: help + +help: + @echo "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――" + @echo "ℹ️ Available commands ℹ️" + @echo "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――" + @echo "⭐️ help : Show this message" + @echo "⭐️ clean : Removes all python cache and temporary files" + @echo "⭐️ run : Runs the application using docker-compose" + @echo "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――" + +clean: + @find . -name '*.pyc' -exec rm -f {} + + @find . -name '*.pyo' -exec rm -f {} + + @find . -name '*~' -exec rm -f {} + + @find . -name '__pycache__' -exec rm -fr {} + + + +run: + @docker-compose up diff --git a/README.md b/README.md index 216c7ab..33e1c09 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -# minesweeper-backend \ No newline at end of file +# Minesweeper (backend) + diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/asgi.py b/app/asgi.py new file mode 100644 index 0000000..1e15a3b --- /dev/null +++ b/app/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for app 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.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") + +application = get_asgi_application() diff --git a/app/settings.py b/app/settings.py new file mode 100644 index 0000000..cb66b0c --- /dev/null +++ b/app/settings.py @@ -0,0 +1,114 @@ +import os + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = os.getenv("SECRET_KEY", "changeme") + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = os.getenv("DEBUG", "0") in ["1", "true"] + +ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "127.0.0.1,localhost").split(",") + +# Application definition +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "core", +] + +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", +] + +ROOT_URLCONF = "app.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 = "app.wsgi.application" + +AUTH_USER_MODEL = "core.User" + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases +DATABASES = { + "default": { + "ENGINE": "django.db.backends.mysql", + "NAME": os.getenv("DB_NAME"), + "USER": os.getenv("DB_USER"), + "PASSWORD": os.getenv("DB_PASS"), + "HOST": os.getenv("DB_HOST"), + "PORT": os.getenv("DB_PORT"), + "OPTIONS": { + "charset": "utf8mb4", + }, + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/ + +STATIC_URL = "/static/" diff --git a/app/urls.py b/app/urls.py new file mode 100644 index 0000000..cf094ce --- /dev/null +++ b/app/urls.py @@ -0,0 +1,21 @@ +"""app URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.1/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 + +urlpatterns = [ + path("admin/", admin.site.urls), +] diff --git a/app/wsgi.py b/app/wsgi.py new file mode 100644 index 0000000..43c02cc --- /dev/null +++ b/app/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for app 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/3.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") + +application = get_wsgi_application() diff --git a/commands/run-prod.sh b/commands/run-prod.sh new file mode 100755 index 0000000..32be8d5 --- /dev/null +++ b/commands/run-prod.sh @@ -0,0 +1,2 @@ +#!/bin/bash +uwsgi --module app.wsgi --http 0.0.0.0:8000 --enable-threads --thunder-lock diff --git a/commands/run.sh b/commands/run.sh new file mode 100755 index 0000000..1440cc6 --- /dev/null +++ b/commands/run.sh @@ -0,0 +1,2 @@ +#!/bin/bash +/commands/wait-for-it.sh "${DB_HOST}:${DB_PORT}" --timeout=90 --strict -- python manage.py runserver 0.0.0.0:8000 diff --git a/commands/wait-for-it.sh b/commands/wait-for-it.sh new file mode 100755 index 0000000..4d7c2be --- /dev/null +++ b/commands/wait-for-it.sh @@ -0,0 +1,177 @@ +#!/bin/bash +# Use this script to test if a given TCP host/port are available + +cmdname=$(basename $0) + +echoerr() { if [[ $QUIET -ne 1 ]]; then echo "$@" 1>&2; fi } + +usage() +{ + cat << USAGE >&2 +Usage: + $cmdname host:port [-s] [-t timeout] [-- command args] + -h HOST | --host=HOST Host or IP under test + -p PORT | --port=PORT TCP port under test + Alternatively, you specify the host and port as host:port + -s | --strict Only execute subcommand if the test succeeds + -q | --quiet Don't output any status messages + -t TIMEOUT | --timeout=TIMEOUT + Timeout in seconds, zero for no timeout + -- COMMAND ARGS Execute command with args after the test finishes +USAGE + exit 1 +} + +wait_for() +{ + if [[ $TIMEOUT -gt 0 ]]; then + echoerr "$cmdname: waiting $TIMEOUT seconds for $HOST:$PORT" + else + echoerr "$cmdname: waiting for $HOST:$PORT without a timeout" + fi + start_ts=$(date +%s) + while : + do + if [[ $ISBUSY -eq 1 ]]; then + nc -z $HOST $PORT + result=$? + else + (echo > /dev/tcp/$HOST/$PORT) >/dev/null 2>&1 + result=$? + fi + if [[ $result -eq 0 ]]; then + end_ts=$(date +%s) + echoerr "$cmdname: $HOST:$PORT is available after $((end_ts - start_ts)) seconds" + break + fi + sleep 1 + done + return $result +} + +wait_for_wrapper() +{ + # In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692 + if [[ $QUIET -eq 1 ]]; then + timeout $BUSYTIMEFLAG $TIMEOUT $0 --quiet --child --host=$HOST --port=$PORT --timeout=$TIMEOUT & + else + timeout $BUSYTIMEFLAG $TIMEOUT $0 --child --host=$HOST --port=$PORT --timeout=$TIMEOUT & + fi + PID=$! + trap "kill -INT -$PID" INT + wait $PID + RESULT=$? + if [[ $RESULT -ne 0 ]]; then + echoerr "$cmdname: timeout occurred after waiting $TIMEOUT seconds for $HOST:$PORT" + fi + return $RESULT +} + +# process arguments +while [[ $# -gt 0 ]] +do + case "$1" in + *:* ) + hostport=(${1//:/ }) + HOST=${hostport[0]} + PORT=${hostport[1]} + shift 1 + ;; + --child) + CHILD=1 + shift 1 + ;; + -q | --quiet) + QUIET=1 + shift 1 + ;; + -s | --strict) + STRICT=1 + shift 1 + ;; + -h) + HOST="$2" + if [[ $HOST == "" ]]; then break; fi + shift 2 + ;; + --host=*) + HOST="${1#*=}" + shift 1 + ;; + -p) + PORT="$2" + if [[ $PORT == "" ]]; then break; fi + shift 2 + ;; + --port=*) + PORT="${1#*=}" + shift 1 + ;; + -t) + TIMEOUT="$2" + if [[ $TIMEOUT == "" ]]; then break; fi + shift 2 + ;; + --timeout=*) + TIMEOUT="${1#*=}" + shift 1 + ;; + --) + shift + CLI=("$@") + break + ;; + --help) + usage + ;; + *) + echoerr "Unknown argument: $1" + usage + ;; + esac +done + +if [[ "$HOST" == "" || "$PORT" == "" ]]; then + echoerr "Error: you need to provide a host and port to test." + usage +fi + +TIMEOUT=${TIMEOUT:-15} +STRICT=${STRICT:-0} +CHILD=${CHILD:-0} +QUIET=${QUIET:-0} + +# check to see if timeout is from busybox? +# check to see if timeout is from busybox? +TIMEOUT_PATH=$(realpath $(which timeout)) +if [[ $TIMEOUT_PATH =~ "busybox" ]]; then + ISBUSY=1 + BUSYTIMEFLAG="-t" +else + ISBUSY=0 + BUSYTIMEFLAG="" +fi + +if [[ $CHILD -gt 0 ]]; then + wait_for + RESULT=$? + exit $RESULT +else + if [[ $TIMEOUT -gt 0 ]]; then + wait_for_wrapper + RESULT=$? + else + wait_for + RESULT=$? + fi +fi + +if [[ $CLI != "" ]]; then + if [[ $RESULT -ne 0 && $STRICT -eq 1 ]]; then + echoerr "$cmdname: strict mode, refusing to execute subprocess" + exit $RESULT + fi + exec "${CLI[@]}" +else + exit $RESULT +fi diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/admin.py b/core/admin.py new file mode 100644 index 0000000..699edc2 --- /dev/null +++ b/core/admin.py @@ -0,0 +1,16 @@ +from django.contrib import admin + +from .models import User + + +@admin.register(User) +class UserAdmin(admin.ModelAdmin): + search_fields = ("id", "email", "first_name", "last_name") + list_display = ( + "id", + "first_name", + "last_name", + "is_active", + "email", + "date_joined", + ) diff --git a/core/apps.py b/core/apps.py new file mode 100644 index 0000000..26f78a8 --- /dev/null +++ b/core/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class CoreConfig(AppConfig): + name = 'core' diff --git a/core/managers.py b/core/managers.py new file mode 100644 index 0000000..cb82257 --- /dev/null +++ b/core/managers.py @@ -0,0 +1,29 @@ +from django.contrib.auth.base_user import BaseUserManager + + +class UserManager(BaseUserManager): + use_in_migrations = True + + def _create_user(self, email, password, **extra_fields): + """ + Creates and saves a User with the given email and password. + """ + if not email: + raise ValueError("The given email must be set") + email = self.normalize_email(email) + user = self.model(email=email, **extra_fields) + user.set_password(password) + user.save(using=self._db) + return user + + def create_user(self, email, password=None, **extra_fields): + extra_fields.setdefault("is_superuser", False) + return self._create_user(email, password, **extra_fields) + + def create_superuser(self, email, password, **extra_fields): + extra_fields.setdefault("is_superuser", True) + + if extra_fields.get("is_superuser") is not True: + raise ValueError("Superuser must have is_superuser=True.") + + return self._create_user(email, password, **extra_fields) diff --git a/core/migrations/0001_initial.py b/core/migrations/0001_initial.py new file mode 100644 index 0000000..cfa9dea --- /dev/null +++ b/core/migrations/0001_initial.py @@ -0,0 +1,42 @@ +# Generated by Django 3.1.3 on 2020-11-05 00:51 + +import core.managers +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('email', models.EmailField(max_length=254, unique=True, verbose_name='E-mail')), + ('first_name', models.CharField(blank=True, max_length=30, verbose_name='First name')), + ('last_name', models.CharField(blank=True, max_length=30, verbose_name='Last name')), + ('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='date joined')), + ('is_active', models.BooleanField(default=True, verbose_name='User active?')), + ('is_staff', models.BooleanField(default=False, verbose_name='Staff?')), + ('is_superuser', models.BooleanField(default=False, verbose_name='Superuser?')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'User', + 'verbose_name_plural': 'Users', + 'db_table': 'users', + 'ordering': ['first_name', 'last_name'], + }, + managers=[ + ('objects', core.managers.UserManager()), + ], + ), + ] diff --git a/core/migrations/__init__.py b/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/models.py b/core/models.py new file mode 100644 index 0000000..c89b937 --- /dev/null +++ b/core/models.py @@ -0,0 +1,41 @@ +from django.db import models +from django.contrib.auth.models import PermissionsMixin +from django.contrib.auth.base_user import AbstractBaseUser + +from .managers import UserManager + + +class User(AbstractBaseUser, PermissionsMixin): + email = models.EmailField("E-mail", unique=True) + + first_name = models.CharField("First name", max_length=30, blank=True) + last_name = models.CharField("Last name", max_length=30, blank=True) + + date_joined = models.DateTimeField("date joined", auto_now_add=True) + + is_active = models.BooleanField("User active?", default=True) + is_staff = models.BooleanField("Staff?", default=False) + is_superuser = models.BooleanField("Superuser?", default=False) + + objects = UserManager() + + USERNAME_FIELD = "email" + + class Meta: + ordering = ["first_name", "last_name"] + verbose_name = "User" + verbose_name_plural = "Users" + db_table = "users" + + def get_full_name(self): + """ + Returns the first_name plus the last_name, with a space in between. + """ + full_name = f"{self.first_name} {self.last_name}" + return full_name.strip() + + def get_short_name(self): + """ + Returns the short name for the user. + """ + return self.first_name or "Unamed" diff --git a/core/tests.py b/core/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/core/views.py b/core/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/core/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..9ac3b41 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,29 @@ +version: "3" +services: + app: + build: . + container_name: mines-app + volumes: + - ./commands:/commands + - .:/app + command: /app/commands/run.sh + environment: + - DB_USER=root + - DB_PASS=minesweeper + - DB_HOST=db + - DB_NAME=minesweeper + - DB_PORT=3306 + - DEBUG=1 + ports: + - 8000:8000 + links: + - db + db: + image: mysql:8 + container_name: mines-db + command: --default-authentication-plugin=mysql_native_password + ports: + - 3306:3306 + environment: + - MYSQL_ROOT_PASSWORD=minesweeper + - MYSQL_DATABASE=minesweeper diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..1a64b14 --- /dev/null +++ b/manage.py @@ -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", "app.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() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..72dada4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,36 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile requirements.txt +# +appdirs==1.4.4 # via -r requirements.txt, black +asgiref==3.3.0 # via -r requirements.txt, django +black==20.8b1 # via -r requirements.txt +click==7.1.2 # via -r requirements.txt, black +django-dbml==0.3.5 # via -r requirements.txt +django-mysql==3.9.0 # via -r requirements.txt +django==3.1.3 # via -r requirements.txt, django-mysql, djangorestframework +djangorestframework==3.12.1 # via -r requirements.txt +gevent==20.9.0 # via -r requirements.txt +greenlet==0.4.17 # via -r requirements.txt, gevent +mypy-extensions==0.4.3 # via -r requirements.txt, black +mysqlclient==2.0.1 # via -r requirements.txt +pathspec==0.8.0 # via -r requirements.txt, black +pendulum==2.1.2 # via -r requirements.txt +python-dateutil==2.8.1 # via -r requirements.txt, pendulum +pytz==2020.4 # via -r requirements.txt, django +pytzdata==2020.1 # via -r requirements.txt, pendulum +regex==2020.10.28 # via -r requirements.txt, black +six==1.15.0 # via -r requirements.txt, python-dateutil +sqlparse==0.4.1 # via -r requirements.txt, django +toml==0.10.2 # via -r requirements.txt, black +typed-ast==1.4.1 # via -r requirements.txt, black +typing-extensions==3.7.4.3 # via -r requirements.txt, black +uwsgi==2.0.19.1 # via -r requirements.txt +zope.event==4.5.0 # via -r requirements.txt, gevent +zope.interface==5.1.2 # via -r requirements.txt, gevent +flake8 + +# The following packages are considered to be unsafe in a requirements file: +# setuptools