From 1e1b590803d5d0d2da3e6994936ebe0dac0b7297 Mon Sep 17 00:00:00 2001 From: Kumi Date: Fri, 2 Aug 2024 17:33:08 +0200 Subject: [PATCH] feat: initial project setup for CaffeinatedDomains Set up the initial Django project structure including custom user model, domain management app, and associated configurations. Added models for Domain, DNSRecord, LeaseAgreement, Payment, and Registrar. Configured serializers, views, and URLs for basic operations. Implemented JWT-based authentication and login via email link. Included necessary admin configurations and migrations. - Added .gitignore to exclude unnecessary files. - Added .vscode/launch.json for VSCode debug configuration. - Added LICENSE file with MIT license. - Created README.md and initialized project directories. - Configured settings for different environments and database support. - Configured basic Celery integration and REST framework settings. --- .gitignore | 8 + .vscode/launch.json | 20 ++ LICENSE | 19 ++ README.md | 0 caffeinateddomains/__init__.py | 0 caffeinateddomains/asgi.py | 16 ++ caffeinateddomains/domains/__init__.py | 0 caffeinateddomains/domains/admin.py | 10 + caffeinateddomains/domains/apps.py | 6 + .../domains/migrations/0001_initial.py | 139 ++++++++++ .../domains/migrations/0002_initial.py | 63 +++++ ...domain_additional_info_request_and_more.py | 30 +++ .../domains/migrations/__init__.py | 0 caffeinateddomains/domains/models.py | 82 ++++++ caffeinateddomains/domains/serializers.py | 14 + caffeinateddomains/domains/tests.py | 3 + caffeinateddomains/domains/urls.py | 7 + caffeinateddomains/domains/views.py | 27 ++ caffeinateddomains/settings.py | 243 ++++++++++++++++++ caffeinateddomains/urls.py | 23 ++ caffeinateddomains/users/__init__.py | 0 caffeinateddomains/users/admin.py | 7 + caffeinateddomains/users/apps.py | 6 + .../users/migrations/0001_initial.py | 79 ++++++ .../users/migrations/__init__.py | 0 caffeinateddomains/users/models.py | 46 ++++ caffeinateddomains/users/serializers.py | 34 +++ caffeinateddomains/users/tests.py | 3 + caffeinateddomains/users/urls.py | 10 + caffeinateddomains/users/utils.py | 17 ++ caffeinateddomains/users/views.py | 45 ++++ caffeinateddomains/wsgi.py | 16 ++ manage.py | 22 ++ pyproject.toml | 52 ++++ 34 files changed, 1047 insertions(+) create mode 100644 .gitignore create mode 100644 .vscode/launch.json create mode 100644 LICENSE create mode 100644 README.md create mode 100644 caffeinateddomains/__init__.py create mode 100644 caffeinateddomains/asgi.py create mode 100644 caffeinateddomains/domains/__init__.py create mode 100644 caffeinateddomains/domains/admin.py create mode 100644 caffeinateddomains/domains/apps.py create mode 100644 caffeinateddomains/domains/migrations/0001_initial.py create mode 100644 caffeinateddomains/domains/migrations/0002_initial.py create mode 100644 caffeinateddomains/domains/migrations/0003_domain_accept_offers_domain_additional_info_request_and_more.py create mode 100644 caffeinateddomains/domains/migrations/__init__.py create mode 100644 caffeinateddomains/domains/models.py create mode 100644 caffeinateddomains/domains/serializers.py create mode 100644 caffeinateddomains/domains/tests.py create mode 100644 caffeinateddomains/domains/urls.py create mode 100644 caffeinateddomains/domains/views.py create mode 100644 caffeinateddomains/settings.py create mode 100644 caffeinateddomains/urls.py create mode 100644 caffeinateddomains/users/__init__.py create mode 100644 caffeinateddomains/users/admin.py create mode 100644 caffeinateddomains/users/apps.py create mode 100644 caffeinateddomains/users/migrations/0001_initial.py create mode 100644 caffeinateddomains/users/migrations/__init__.py create mode 100644 caffeinateddomains/users/models.py create mode 100644 caffeinateddomains/users/serializers.py create mode 100644 caffeinateddomains/users/tests.py create mode 100644 caffeinateddomains/users/urls.py create mode 100644 caffeinateddomains/users/utils.py create mode 100644 caffeinateddomains/users/views.py create mode 100644 caffeinateddomains/wsgi.py create mode 100755 manage.py create mode 100644 pyproject.toml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b777fe9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +settings.ini +*.pyc +__pycache__/ +db.sqlite3 +node_modules/ +media/ +.venv/ +venv/ \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..cd42d66 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,20 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python Debugger: Django", + "type": "debugpy", + "request": "launch", + "args": [ + "runserver", + "8111" + ], + "django": true, + "autoStartBrowser": false, + "program": "${workspaceFolder}/manage.py" + } + ] +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cff7346 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2024 Kumi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/caffeinateddomains/__init__.py b/caffeinateddomains/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/caffeinateddomains/asgi.py b/caffeinateddomains/asgi.py new file mode 100644 index 0000000..cf0c095 --- /dev/null +++ b/caffeinateddomains/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for caffeinateddomains 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/5.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'caffeinateddomains.settings') + +application = get_asgi_application() diff --git a/caffeinateddomains/domains/__init__.py b/caffeinateddomains/domains/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/caffeinateddomains/domains/admin.py b/caffeinateddomains/domains/admin.py new file mode 100644 index 0000000..424250e --- /dev/null +++ b/caffeinateddomains/domains/admin.py @@ -0,0 +1,10 @@ +from django.contrib import admin + +from .models import Domain, DNSRecord, LeaseAgreement, Payment, Registrar + +admin.site.register(Domain) +admin.site.register(DNSRecord) +admin.site.register(LeaseAgreement) +admin.site.register(Payment) +admin.site.register(Registrar) + diff --git a/caffeinateddomains/domains/apps.py b/caffeinateddomains/domains/apps.py new file mode 100644 index 0000000..acac0c5 --- /dev/null +++ b/caffeinateddomains/domains/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class DomainsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'caffeinateddomains.domains' diff --git a/caffeinateddomains/domains/migrations/0001_initial.py b/caffeinateddomains/domains/migrations/0001_initial.py new file mode 100644 index 0000000..25f9c3a --- /dev/null +++ b/caffeinateddomains/domains/migrations/0001_initial.py @@ -0,0 +1,139 @@ +# Generated by Django 5.0.7 on 2024-08-02 14:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [] + + operations = [ + migrations.CreateModel( + name="DNSRecord", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "record_type", + models.CharField( + choices=[("A", "A"), ("CNAME", "CNAME"), ("MX", "MX")], + max_length=10, + ), + ), + ("record_value", models.CharField(max_length=255)), + ("ttl", models.IntegerField(default=3600)), + ("priority", models.IntegerField(blank=True, null=True)), + ], + ), + migrations.CreateModel( + name="Domain", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=255, unique=True)), + ( + "status", + models.CharField( + choices=[ + ("available", "Available"), + ("parked", "Parked"), + ("leased", "Leased"), + ("for_sale", "For Sale"), + ], + max_length=20, + ), + ), + ("registration_date", models.DateField()), + ("expiration_date", models.DateField()), + ( + "price", + models.DecimalField( + blank=True, decimal_places=2, max_digits=10, null=True + ), + ), + ("description", models.TextField(blank=True, null=True)), + ], + ), + migrations.CreateModel( + name="LeaseAgreement", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("start_date", models.DateField()), + ("end_date", models.DateField()), + ("payment_terms", models.CharField(max_length=255)), + ( + "status", + models.CharField( + choices=[ + ("active", "Active"), + ("expired", "Expired"), + ("terminated", "Terminated"), + ], + max_length=20, + ), + ), + ], + ), + migrations.CreateModel( + name="Payment", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("amount", models.DecimalField(decimal_places=2, max_digits=10)), + ("payment_date", models.DateTimeField(auto_now_add=True)), + ("payment_method", models.CharField(max_length=50)), + ("transaction_id", models.CharField(max_length=255)), + ("status", models.CharField(max_length=20)), + ], + ), + migrations.CreateModel( + name="Registrar", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=255)), + ("api_key", models.CharField(max_length=255)), + ("api_secret", models.CharField(max_length=255)), + ("contact_info", models.TextField()), + ("supported_tlds", models.TextField()), + ], + ), + ] diff --git a/caffeinateddomains/domains/migrations/0002_initial.py b/caffeinateddomains/domains/migrations/0002_initial.py new file mode 100644 index 0000000..8aa2606 --- /dev/null +++ b/caffeinateddomains/domains/migrations/0002_initial.py @@ -0,0 +1,63 @@ +# Generated by Django 5.0.7 on 2024-08-02 14:58 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ("domains", "0001_initial"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name="domain", + name="owner", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="domains", + to=settings.AUTH_USER_MODEL, + ), + ), + migrations.AddField( + model_name="dnsrecord", + name="domain", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="dns_records", + to="domains.domain", + ), + ), + migrations.AddField( + model_name="leaseagreement", + name="domain", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="lease_agreements", + to="domains.domain", + ), + ), + migrations.AddField( + model_name="leaseagreement", + name="lessee", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="leases", + to=settings.AUTH_USER_MODEL, + ), + ), + migrations.AddField( + model_name="payment", + name="user", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="payments", + to=settings.AUTH_USER_MODEL, + ), + ), + ] diff --git a/caffeinateddomains/domains/migrations/0003_domain_accept_offers_domain_additional_info_request_and_more.py b/caffeinateddomains/domains/migrations/0003_domain_accept_offers_domain_additional_info_request_and_more.py new file mode 100644 index 0000000..0997de0 --- /dev/null +++ b/caffeinateddomains/domains/migrations/0003_domain_accept_offers_domain_additional_info_request_and_more.py @@ -0,0 +1,30 @@ +# Generated by Django 5.0.7 on 2024-08-02 15:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("domains", "0002_initial"), + ] + + operations = [ + migrations.AddField( + model_name="domain", + name="accept_offers", + field=models.BooleanField(default=False), + ), + migrations.AddField( + model_name="domain", + name="additional_info_request", + field=models.TextField(blank=True, null=True), + ), + migrations.AddField( + model_name="domain", + name="buy_now_price", + field=models.DecimalField( + blank=True, decimal_places=2, max_digits=10, null=True + ), + ), + ] diff --git a/caffeinateddomains/domains/migrations/__init__.py b/caffeinateddomains/domains/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/caffeinateddomains/domains/models.py b/caffeinateddomains/domains/models.py new file mode 100644 index 0000000..eb8820b --- /dev/null +++ b/caffeinateddomains/domains/models.py @@ -0,0 +1,82 @@ +from django.db import models +from django.contrib.auth import get_user_model + +User = get_user_model() + + +class Domain(models.Model): + STATUS_CHOICES = [ + ("available", "Available"), + ("parked", "Parked"), + ("leased", "Leased"), + ("for_sale", "For Sale"), + ] + + name = models.CharField(max_length=255, unique=True) + status = models.CharField(max_length=20, choices=STATUS_CHOICES) + owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="domains") + registration_date = models.DateField() + expiration_date = models.DateField() + price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + description = models.TextField(blank=True, null=True) + accept_offers = models.BooleanField(default=False) + buy_now_price = models.DecimalField( + max_digits=10, decimal_places=2, null=True, blank=True + ) + additional_info_request = models.TextField(blank=True, null=True) + + def __str__(self): + return self.name + + +class DNSRecord(models.Model): + RECORD_TYPE_CHOICES = [ + ("A", "A"), + ("CNAME", "CNAME"), + ("MX", "MX"), + # TODO: Add other record types as needed + ] + + domain = models.ForeignKey( + Domain, on_delete=models.CASCADE, related_name="dns_records" + ) + record_type = models.CharField(max_length=10, choices=RECORD_TYPE_CHOICES) + record_value = models.CharField(max_length=255) + ttl = models.IntegerField(default=3600) + priority = models.IntegerField(null=True, blank=True) + + +class LeaseAgreement(models.Model): + STATUS_CHOICES = [ + ("active", "Active"), + ("expired", "Expired"), + ("terminated", "Terminated"), + ] + + domain = models.ForeignKey( + Domain, on_delete=models.CASCADE, related_name="lease_agreements" + ) + lessee = models.ForeignKey( + get_user_model(), on_delete=models.CASCADE, related_name="leases" + ) + start_date = models.DateField() + end_date = models.DateField() + payment_terms = models.CharField(max_length=255) + status = models.CharField(max_length=20, choices=STATUS_CHOICES) + + +class Payment(models.Model): + user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="payments") + amount = models.DecimalField(max_digits=10, decimal_places=2) + payment_date = models.DateTimeField(auto_now_add=True) + payment_method = models.CharField(max_length=50) + transaction_id = models.CharField(max_length=255) + status = models.CharField(max_length=20) + + +class Registrar(models.Model): + name = models.CharField(max_length=255) + api_key = models.CharField(max_length=255) + api_secret = models.CharField(max_length=255) + contact_info = models.TextField() + supported_tlds = models.TextField() diff --git a/caffeinateddomains/domains/serializers.py b/caffeinateddomains/domains/serializers.py new file mode 100644 index 0000000..d745966 --- /dev/null +++ b/caffeinateddomains/domains/serializers.py @@ -0,0 +1,14 @@ +from rest_framework import serializers +from .models import Domain, Offer + + +class DomainSerializer(serializers.ModelSerializer): + class Meta: + model = Domain + fields = "__all__" + + +class OfferSerializer(serializers.ModelSerializer): + class Meta: + model = Offer + fields = "__all__" diff --git a/caffeinateddomains/domains/tests.py b/caffeinateddomains/domains/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/caffeinateddomains/domains/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/caffeinateddomains/domains/urls.py b/caffeinateddomains/domains/urls.py new file mode 100644 index 0000000..2a16df8 --- /dev/null +++ b/caffeinateddomains/domains/urls.py @@ -0,0 +1,7 @@ +from django.urls import path +from .views import DomainListCreateView, OfferListCreateView + +urlpatterns = [ + path('domains/', DomainListCreateView.as_view(), name='domain_list_create'), + path('offers/', OfferListCreateView.as_view(), name='offer_list_create'), +] diff --git a/caffeinateddomains/domains/views.py b/caffeinateddomains/domains/views.py new file mode 100644 index 0000000..9fb6ab7 --- /dev/null +++ b/caffeinateddomains/domains/views.py @@ -0,0 +1,27 @@ +from rest_framework import generics, serializers + +from .models import Domain, Offer +from .serializers import DomainSerializer, OfferSerializer + +from rest_framework.permissions import IsAuthenticated + + +class DomainListCreateView(generics.ListCreateAPIView): + queryset = Domain.objects.all() + serializer_class = DomainSerializer + permission_classes = [IsAuthenticated] + + def perform_create(self, serializer): + serializer.save(owner=self.request.user) + + +class OfferListCreateView(generics.ListCreateAPIView): + queryset = Offer.objects.all() + serializer_class = OfferSerializer + permission_classes = [IsAuthenticated] + + def perform_create(self, serializer): + domain = serializer.validated_data["domain"] + if not domain.accept_offers: + raise serializers.ValidationError("This domain is not accepting offers.") + serializer.save(user=self.request.user) diff --git a/caffeinateddomains/settings.py b/caffeinateddomains/settings.py new file mode 100644 index 0000000..3ab612d --- /dev/null +++ b/caffeinateddomains/settings.py @@ -0,0 +1,243 @@ +from autosecretkey import AutoSecretKey + +from pathlib import Path + +from django.urls import reverse_lazy + +import datetime + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent + +ASK = AutoSecretKey("settings.ini") + +SECRET_KEY = ASK.secret_key + +DEBUG = ASK.config.getboolean("CaffeinatedDomains", "Debug", fallback=False) + +ALLOWED_HOSTS = [ + host.strip() + for host in ASK.config.get("CaffeinatedDomains", "Host", fallback="*").split(",") +] + +CSRF_TRUSTED_ORIGINS = [f"https://{host}" for host in ALLOWED_HOSTS] +FRONTEND_URL = CSRF_TRUSTED_ORIGINS[0] + +USE_X_FORWARDED_HOST = True +SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") + +# Application definition + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "polymorphic", + "rest_framework", + "rest_framework_simplejwt", + "django_celery_beat", + "django_celery_results", + "drf_spectacular", + "drf_spectacular_sidecar", + "crispy_forms", + "crispy_bootstrap5", + "caffeinateddomains", + "caffeinateddomains.users", + "caffeinateddomains.domains", +] + +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 = "caffeinateddomains.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 = "caffeinateddomains.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/5.0/ref/settings/#databases + +if (dbtype := "MySQL") in ASK.config or (dbtype := "MariaDB") in ASK.config: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.mysql", + "NAME": ASK.config.get(dbtype, "Database"), + "USER": ASK.config.get(dbtype, "Username"), + "PASSWORD": ASK.config.get(dbtype, "Password"), + "HOST": ASK.config.get(dbtype, "Host", fallback="localhost"), + "PORT": ASK.config.getint(dbtype, "Port", fallback=3306), + } + } + +elif (dbtype := "Postgres") in ASK.config or (dbtype := "PostgreSQL") in ASK.config: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": ASK.config.get(dbtype, "Database"), + "USER": ASK.config.get(dbtype, "Username"), + "PASSWORD": ASK.config.get(dbtype, "Password"), + "HOST": ASK.config.get(dbtype, "Host", fallback="localhost"), + "PORT": ASK.config.getint(dbtype, "Port", fallback=5432), + } + } + +else: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": "db.sqlite3", + } + } + + +# Password validation +# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators + +AUTH_USER_MODEL = "users.User" + +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", + }, +] + +PASSWORD_HASHERS = [ + "django.contrib.auth.hashers.Argon2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", + "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", + "django.contrib.auth.hashers.ScryptPasswordHasher", +] + +# Internationalization +# https://docs.djangoproject.com/en/5.0/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/5.0/howto/static-files/ + +STATIC_URL = "static/" + +STATICFILES_DIRS = [ + "static", +] + +# Settings for uploaded files + +MEDIA_URL = "/media/" +MEDIA_ROOT = ASK.config.get("CaffeinatedDomains", "MediaRoot", fallback="media") + +if "S3" in ASK.config: + DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" + + if not ASK.config.getboolean("S3", "LocalStatic", fallback=False): + STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage" + + AWS_ACCESS_KEY_ID = ASK.config.get("S3", "AccessKey") + AWS_SECRET_ACCESS_KEY = ASK.config.get("S3", "SecretKey") + AWS_STORAGE_BUCKET_NAME = ASK.config.get("S3", "Bucket") + AWS_S3_ENDPOINT_URL = ASK.config.get("S3", "Endpoint") + +# Default primary key field type +# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + +# Django Rest Framework settings + +SPECTACULAR_SETTINGS = { + "SWAGGER_UI_DIST": "SIDECAR", + "SWAGGER_UI_FAVICON_HREF": "SIDECAR", + "REDOC_DIST": "SIDECAR", +} + +REST_FRAMEWORK = { + "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", + "DEFAULT_AUTHENTICATION_CLASSES": [ + "rest_framework_simplejwt.authentication.JWTAuthentication", + ], +} + +SIMPLE_JWT = { + "ACCESS_TOKEN_LIFETIME": datetime.timedelta(minutes=5), + "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=1), + "ROTATE_REFRESH_TOKENS": True, + "AUTH_HEADER_TYPES": ("Bearer",), +} + +# Celery settings + +CELERY_BROKER_URL = ASK.config.get( + "CaffeinatedDomains", "Redis", fallback="redis://localhost:6379/0" +) +CELERY_RESULT_BACKEND = "django-db" + +# TODO: CSP settings + +# Authentication + +LOGIN_URL = reverse_lazy("caffeinateddomains.users:login") +LOGIN_REDIRECT_URL = reverse_lazy("caffeinateddomains.users:categories") +LOGOUT_REDIRECT_URL = reverse_lazy("caffeinateddomains.users:login") + +# Crispy forms settings + +CRISPY_ALLOWED_TEMPLATE_PACKS = {"bootstrap5"} +CRISPY_TEMPLATE_PACK = "bootstrap5" + +# Email settings + +EMAIL_BACKEND = ( + "django.core.mail.backends.smtp.EmailBackend" + if "SMTP" in ASK.config + else "django.core.mail.backends.console.EmailBackend" +) +EMAIL_HOST = ASK.config.get("Email", "Host") +EMAIL_USE_TLS = ASK.config.getboolean("Email", "TLS", fallback=True) +EMAIL_PORT = ASK.config.getint("Email", "Port", fallback=587 if EMAIL_USE_TLS else 25) +EMAIL_HOST_USER = ASK.config.get("Email", "Username") +EMAIL_HOST_PASSWORD = ASK.config.get("Email", "Password") +DEFAULT_FROM_EMAIL = ASK.config.get("Email", "From", fallback=EMAIL_HOST_USER) diff --git a/caffeinateddomains/urls.py b/caffeinateddomains/urls.py new file mode 100644 index 0000000..351988e --- /dev/null +++ b/caffeinateddomains/urls.py @@ -0,0 +1,23 @@ +""" +URL configuration for caffeinateddomains project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.0/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('accounts/', include("caffeinateddomains.users.urls")) +] diff --git a/caffeinateddomains/users/__init__.py b/caffeinateddomains/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/caffeinateddomains/users/admin.py b/caffeinateddomains/users/admin.py new file mode 100644 index 0000000..1dc0361 --- /dev/null +++ b/caffeinateddomains/users/admin.py @@ -0,0 +1,7 @@ +from django.contrib import admin +from django.contrib.auth.models import Group + +from .models import User + +admin.site.register(User) +admin.site.unregister(Group) \ No newline at end of file diff --git a/caffeinateddomains/users/apps.py b/caffeinateddomains/users/apps.py new file mode 100644 index 0000000..9c2cb1e --- /dev/null +++ b/caffeinateddomains/users/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'caffeinateddomains.users' diff --git a/caffeinateddomains/users/migrations/0001_initial.py b/caffeinateddomains/users/migrations/0001_initial.py new file mode 100644 index 0000000..00eeea9 --- /dev/null +++ b/caffeinateddomains/users/migrations/0001_initial.py @@ -0,0 +1,79 @@ +# Generated by Django 5.0.7 on 2024-08-02 14:58 + +import django.utils.timezone +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.BigAutoField( + 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" + ), + ), + ( + "is_superuser", + models.BooleanField( + default=False, + help_text="Designates that this user has all permissions without explicitly assigning them.", + verbose_name="superuser status", + ), + ), + ("email", models.EmailField(max_length=254, unique=True)), + ("full_name", models.CharField(blank=True, max_length=255, null=True)), + ("contact_details", models.TextField(blank=True, null=True)), + ("is_active", models.BooleanField(default=True)), + ("is_staff", models.BooleanField(default=False)), + ( + "date_joined", + models.DateTimeField(default=django.utils.timezone.now), + ), + ( + "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={ + "abstract": False, + }, + ), + ] diff --git a/caffeinateddomains/users/migrations/__init__.py b/caffeinateddomains/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/caffeinateddomains/users/models.py b/caffeinateddomains/users/models.py new file mode 100644 index 0000000..2520312 --- /dev/null +++ b/caffeinateddomains/users/models.py @@ -0,0 +1,46 @@ +from django.contrib.auth.models import ( + AbstractBaseUser, + BaseUserManager, + PermissionsMixin, +) +from django.db import models +from django.utils import timezone + + +class CustomUserManager(BaseUserManager): + def create_user(self, email, password=None, **extra_fields): + if not email: + raise ValueError("The Email field 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_superuser(self, email, password=None, **extra_fields): + extra_fields.setdefault("is_staff", True) + extra_fields.setdefault("is_superuser", True) + + if extra_fields.get("is_staff") is not True: + raise ValueError("Superuser must have is_staff=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) + + +class User(AbstractBaseUser, PermissionsMixin): + email = models.EmailField(unique=True) + full_name = models.CharField(max_length=255, blank=True, null=True) + contact_details = models.TextField(blank=True, null=True) + is_active = models.BooleanField(default=True) + is_staff = models.BooleanField(default=False) + date_joined = models.DateTimeField(default=timezone.now) + + objects = CustomUserManager() + + USERNAME_FIELD = "email" + REQUIRED_FIELDS = [] + + def __str__(self): + return self.email diff --git a/caffeinateddomains/users/serializers.py b/caffeinateddomains/users/serializers.py new file mode 100644 index 0000000..162c2e9 --- /dev/null +++ b/caffeinateddomains/users/serializers.py @@ -0,0 +1,34 @@ +from rest_framework import serializers +from .models import User +from .utils import send_login_email + + +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ("email", "full_name", "password") + extra_kwargs = {"password": {"write_only": True}} + + def create(self, validated_data): + user = User.objects.create_user( + email=validated_data["email"], + password=validated_data["password"], + full_name=validated_data.get("full_name", ""), + ) + return user + + +class RequestLoginLinkSerializer(serializers.Serializer): + email = serializers.EmailField() + + def validate_email(self, value): + try: + User.objects.get(email=value) + except User.DoesNotExist: + raise serializers.ValidationError("User with this email does not exist.") + return value + + def create(self, validated_data): + user = User.objects.get(email=validated_data["email"]) + send_login_email(user) + return user diff --git a/caffeinateddomains/users/tests.py b/caffeinateddomains/users/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/caffeinateddomains/users/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/caffeinateddomains/users/urls.py b/caffeinateddomains/users/urls.py new file mode 100644 index 0000000..6902ad5 --- /dev/null +++ b/caffeinateddomains/users/urls.py @@ -0,0 +1,10 @@ +from django.urls import path +from .views import UserCreateView, LoginWithTokenView, RequestLoginLinkView + +urlpatterns = [ + path("register/", UserCreateView.as_view(), name="register"), + path("login/", LoginWithTokenView.as_view(), name="login"), + path( + "request-login-link/", RequestLoginLinkView.as_view(), name="request_login_link" + ), +] diff --git a/caffeinateddomains/users/utils.py b/caffeinateddomains/users/utils.py new file mode 100644 index 0000000..0b13408 --- /dev/null +++ b/caffeinateddomains/users/utils.py @@ -0,0 +1,17 @@ +from rest_framework_simplejwt.tokens import AccessToken +from django.core.mail import send_mail +from django.conf import settings +from django.urls import reverse + + +def send_login_email(user): + token = AccessToken.for_user(user) + local_part = reverse("login") + f"?token={str(token)}" + login_url = f"{settings.FRONTEND_URL}{local_part}" + send_mail( + "Your Login Link", + f"Click the link to log in: {login_url}", + settings.DEFAULT_FROM_EMAIL, + [user.email], + fail_silently=False, + ) diff --git a/caffeinateddomains/users/views.py b/caffeinateddomains/users/views.py new file mode 100644 index 0000000..b1250f4 --- /dev/null +++ b/caffeinateddomains/users/views.py @@ -0,0 +1,45 @@ +from rest_framework import generics +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework import status +from rest_framework_simplejwt.tokens import UntypedToken +from rest_framework_simplejwt.exceptions import InvalidToken, TokenError +from django.contrib.auth import get_user_model, login + +from .serializers import UserSerializer, RequestLoginLinkSerializer + +User = get_user_model() + + +class LoginWithTokenView(APIView): + def get(self, request): + token = request.query_params.get("token") + if not token: + return Response( + {"detail": "Token is required."}, status=status.HTTP_400_BAD_REQUEST + ) + + try: + user_id = UntypedToken(token).payload.get( + "user_id" + ) # This implicitly checks the token's validity + user = User.objects.get(id=user_id) + except (InvalidToken, TokenError, User.DoesNotExist): + return Response( + {"detail": "Invalid or expired token."}, + status=status.HTTP_400_BAD_REQUEST, + ) + + login(request, user) + return Response( + {"detail": "Logged in successfully."}, status=status.HTTP_200_OK + ) + + +class UserCreateView(generics.CreateAPIView): + queryset = User.objects.all() + serializer_class = UserSerializer + + +class RequestLoginLinkView(generics.CreateAPIView): + serializer_class = RequestLoginLinkSerializer diff --git a/caffeinateddomains/wsgi.py b/caffeinateddomains/wsgi.py new file mode 100644 index 0000000..337a024 --- /dev/null +++ b/caffeinateddomains/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for caffeinateddomains 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/5.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'caffeinateddomains.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..b85be6e --- /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', 'caffeinateddomains.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/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6f4805c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,52 @@ +[tool.poetry] +name = "caffeinateddomains" +version = "0.1.0" +description = "" +authors = ["Kumi "] +license = "MIT" +readme = "README.md" +repository = "https://git.private.coffee/kumi/caffeinateddomains" + +[tool.poetry.dependencies] +python = "^3.10" +django = "^5.0" +djangorestframework = "*" +django-storages = "*" +django-polymorphic = "*" +setuptools = "*" +pillow = "*" +pygments = "*" +markdown = "*" +coreapi = "*" +pyyaml = "*" +django-autosecretkey = "*" +celery = "*" +redis = "*" +django-celery-results = "*" +django-celery-beat = "*" +drf-spectacular = {extras = ["sidecar"], version = "*"} +boto3 = "*" +argon2-cffi = "*" +django-csp = "*" +django-rest-polymorphic = "*" +django-crispy-forms = "*" +crispy-bootstrap5 = "*" +djangorestframework-simplejwt = "*" + +[tool.poetry.group.mysql.dependencies] +mysqlclient = "*" + +[tool.poetry.group.postgres.dependencies] +psycopg2 = "*" + +[tool.poetry.dev-dependencies] +pytest = "^5.2" +ruff = "*" +black = "*" + +[tool.poetry.scripts] +quackscape-manage = "quackscape.manage:main" + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api"