commit e591d0f4092e2d37b2aa892fed302619b8907856 Author: zwnk Date: Thu Jan 16 10:20:20 2025 -0300 second diff --git a/.env b/.env new file mode 100644 index 0000000..f23dff0 --- /dev/null +++ b/.env @@ -0,0 +1,6 @@ +DB_NAME=todo_db +DB_USER=postgres +DB_PASSWORD=postgres +DB_HOST=db +DB_PORT=5432 +DEBUG=1 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9e859df --- /dev/null +++ b/Dockerfile @@ -0,0 +1,30 @@ +# backend/Dockerfile +FROM python:3.9-slim + +# Set environment variables +ENV PYTHONDONTWRITEBYTECODE 1 +ENV PYTHONUNBUFFERED 1 + +# Set work directory +WORKDIR /app + +# Install system dependencies +RUN apt-get update && apt-get install -y \ + gcc \ + postgresql-client \ + netcat-openbsd \ + && rm -rf /var/lib/apt/lists/* + +# Install Python dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy project +COPY . . + +# Copy entrypoint script and set permissions +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh \ + && sed -i 's/\r$//g' /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000..4b381ff Binary files /dev/null and b/db.sqlite3 differ diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..60bffb8 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,17 @@ +#!/bin/sh + +# Wait for postgres to be ready +while ! nc -z db 5432; do + echo "Waiting for postgres..." + sleep 1 +done + +echo "PostgreSQL started" + +# Apply database migrations +echo "Applying database migrations..." +python manage.py migrate + +# Start server +echo "Starting server..." +python manage.py runserver 0.0.0.0:8000 diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..1d0193a --- /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', 'todo_project.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..0598d25 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +Django==4.2.0 +djangorestframework==3.14.0 +django-cors-headers==4.1.0 +djangorestframework-simplejwt==5.2.2 +python-dotenv==1.0.0 +psycopg2-binary==2.9.9 + diff --git a/todo_project/__init__.py b/todo_project/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/todo_project/__pycache__/__init__.cpython-312.pyc b/todo_project/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..447f091 Binary files /dev/null and b/todo_project/__pycache__/__init__.cpython-312.pyc differ diff --git a/todo_project/__pycache__/settings.cpython-312.pyc b/todo_project/__pycache__/settings.cpython-312.pyc new file mode 100644 index 0000000..fcd5e7a Binary files /dev/null and b/todo_project/__pycache__/settings.cpython-312.pyc differ diff --git a/todo_project/__pycache__/urls.cpython-312.pyc b/todo_project/__pycache__/urls.cpython-312.pyc new file mode 100644 index 0000000..91f736a Binary files /dev/null and b/todo_project/__pycache__/urls.cpython-312.pyc differ diff --git a/todo_project/__pycache__/wsgi.cpython-312.pyc b/todo_project/__pycache__/wsgi.cpython-312.pyc new file mode 100644 index 0000000..87498e3 Binary files /dev/null and b/todo_project/__pycache__/wsgi.cpython-312.pyc differ diff --git a/todo_project/asgi.py b/todo_project/asgi.py new file mode 100644 index 0000000..a304b33 --- /dev/null +++ b/todo_project/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for todo_project 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/4.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_project.settings') + +application = get_asgi_application() diff --git a/todo_project/settings.py b/todo_project/settings.py new file mode 100644 index 0000000..a384da0 --- /dev/null +++ b/todo_project/settings.py @@ -0,0 +1,151 @@ +""" +Django settings for todo_project project. + +Generated by 'django-admin startproject' using Django 4.2. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +from pathlib import Path +import os +from dotenv import load_dotenv + +# Load environment variables +load_dotenv() + +# 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/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-lfui+*aw(!!kq8qbalr@mp$--uc7gb2#8o#ps3p5s2)pzw@s3i' + +# 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', + 'rest_framework', + 'corsheaders', + 'todos', +] + +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', +] + +CORS_ALLOWED_ORIGINS = [ + "http://localhost:5173", # Vue.js development server +] + +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework_simplejwt.authentication.JWTAuthentication', + ], +} + +ROOT_URLCONF = 'todo_project.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 = 'todo_project.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +#DATABASES = { +# 'default': { +# 'ENGINE': 'django.db.backends.sqlite3', +# 'NAME': BASE_DIR / 'db.sqlite3', +# } +#} +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': os.getenv('DB_NAME', 'todo_db'), + 'USER': os.getenv('DB_USER', 'postgres'), + 'PASSWORD': os.getenv('DB_PASSWORD', 'postgres'), + 'HOST': os.getenv('DB_HOST', 'localhost'), + 'PORT': os.getenv('DB_PORT', '5432'), + } +} + +# Password validation +# https://docs.djangoproject.com/en/4.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/4.2/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/4.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/todo_project/urls.py b/todo_project/urls.py new file mode 100644 index 0000000..7cc5ab3 --- /dev/null +++ b/todo_project/urls.py @@ -0,0 +1,24 @@ +""" +URL configuration for todo_project project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/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('api/', include('todos.urls')), +] diff --git a/todo_project/wsgi.py b/todo_project/wsgi.py new file mode 100644 index 0000000..2d00322 --- /dev/null +++ b/todo_project/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for todo_project 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/4.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_project.settings') + +application = get_wsgi_application() diff --git a/todos/__init__.py b/todos/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/todos/__pycache__/__init__.cpython-312.pyc b/todos/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..9c535c0 Binary files /dev/null and b/todos/__pycache__/__init__.cpython-312.pyc differ diff --git a/todos/__pycache__/admin.cpython-312.pyc b/todos/__pycache__/admin.cpython-312.pyc new file mode 100644 index 0000000..79fe7b3 Binary files /dev/null and b/todos/__pycache__/admin.cpython-312.pyc differ diff --git a/todos/__pycache__/apps.cpython-312.pyc b/todos/__pycache__/apps.cpython-312.pyc new file mode 100644 index 0000000..a632f60 Binary files /dev/null and b/todos/__pycache__/apps.cpython-312.pyc differ diff --git a/todos/__pycache__/models.cpython-312.pyc b/todos/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000..02a1164 Binary files /dev/null and b/todos/__pycache__/models.cpython-312.pyc differ diff --git a/todos/__pycache__/serializers.cpython-312.pyc b/todos/__pycache__/serializers.cpython-312.pyc new file mode 100644 index 0000000..feeabdb Binary files /dev/null and b/todos/__pycache__/serializers.cpython-312.pyc differ diff --git a/todos/__pycache__/urls.cpython-312.pyc b/todos/__pycache__/urls.cpython-312.pyc new file mode 100644 index 0000000..42eb593 Binary files /dev/null and b/todos/__pycache__/urls.cpython-312.pyc differ diff --git a/todos/__pycache__/views.cpython-312.pyc b/todos/__pycache__/views.cpython-312.pyc new file mode 100644 index 0000000..7610385 Binary files /dev/null and b/todos/__pycache__/views.cpython-312.pyc differ diff --git a/todos/admin.py b/todos/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/todos/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/todos/apps.py b/todos/apps.py new file mode 100644 index 0000000..a8b463e --- /dev/null +++ b/todos/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class TodosConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'todos' diff --git a/todos/migrations/0001_initial.py b/todos/migrations/0001_initial.py new file mode 100644 index 0000000..520eb09 --- /dev/null +++ b/todos/migrations/0001_initial.py @@ -0,0 +1,27 @@ +# Generated by Django 4.2 on 2025-01-15 13:36 + +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='Todo', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=200)), + ('completed', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/todos/migrations/__init__.py b/todos/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/todos/migrations/__pycache__/0001_initial.cpython-312.pyc b/todos/migrations/__pycache__/0001_initial.cpython-312.pyc new file mode 100644 index 0000000..ece69a4 Binary files /dev/null and b/todos/migrations/__pycache__/0001_initial.cpython-312.pyc differ diff --git a/todos/migrations/__pycache__/__init__.cpython-312.pyc b/todos/migrations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..fc708bc Binary files /dev/null and b/todos/migrations/__pycache__/__init__.cpython-312.pyc differ diff --git a/todos/models.py b/todos/models.py new file mode 100644 index 0000000..3b99884 --- /dev/null +++ b/todos/models.py @@ -0,0 +1,12 @@ +from django.db import models +from django.contrib.auth.models import User + +class Todo(models.Model): + user = models.ForeignKey(User, on_delete=models.CASCADE) + title = models.CharField(max_length=200) + completed = models.BooleanField(default=False) + created_at = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return self.title + diff --git a/todos/serializers.py b/todos/serializers.py new file mode 100644 index 0000000..39546a0 --- /dev/null +++ b/todos/serializers.py @@ -0,0 +1,21 @@ +from rest_framework import serializers +from django.contrib.auth.models import User +from .models import Todo + +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ('id', 'username') + extra_kwargs = {'password': {'write_only': True}} + + def create(self, validated_data): + user = User.objects.create_user( + username=validated_data['username'], + password=validated_data['password'] + ) + return user + +class TodoSerializer(serializers.ModelSerializer): + class Meta: + model = Todo + fields = ('id', 'title', 'completed', 'created_at') diff --git a/todos/tests.py b/todos/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/todos/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/todos/urls.py b/todos/urls.py new file mode 100644 index 0000000..eba661e --- /dev/null +++ b/todos/urls.py @@ -0,0 +1,12 @@ +from django.urls import path, include +from rest_framework.routers import DefaultRouter +from .views import TodoViewSet, register_user, login_user + +router = DefaultRouter() +router.register(r'todos', TodoViewSet, basename='todo') + +urlpatterns = [ + path('', include(router.urls)), + path('register/', register_user, name='register'), + path('login/', login_user, name='login'), +] diff --git a/todos/views.py b/todos/views.py new file mode 100644 index 0000000..880c1a8 --- /dev/null +++ b/todos/views.py @@ -0,0 +1,51 @@ +from rest_framework import viewsets, permissions, status +from rest_framework.response import Response +from rest_framework.decorators import api_view, permission_classes +from django.contrib.auth import authenticate +from rest_framework_simplejwt.tokens import RefreshToken +from .models import Todo +from .serializers import TodoSerializer, UserSerializer +import logging + +logger = logging.getLogger(__name__) + +@api_view(['POST']) +@permission_classes([permissions.AllowAny]) +def register_user(request): + serializer = UserSerializer(data=request.data) + if serializer.is_valid(): + user = serializer.save() + refresh = RefreshToken.for_user(user) + return Response({ + 'token': str(refresh.access_token), + }) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +@api_view(['POST']) +@permission_classes([permissions.AllowAny]) +def login_user(request): + username = request.data.get('username') + password = request.data.get('password') + user = authenticate(username=username, password=password) + if user: + refresh = RefreshToken.for_user(user) + return Response({ + 'token': str(refresh.access_token), + }) + return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) + +class TodoViewSet(viewsets.ModelViewSet): + serializer_class = TodoSerializer + permission_classes = [permissions.IsAuthenticated] + + def get_queryset(self): + print(f"user query: {self.request.user.username}") + logger.info(f"query by user: {self.request.user.username}") + return Todo.objects.filter(user=self.request.user) + + def perform_create(self, serializer): + todo = serializer.save(user=self.request.user) + serializer.save(user=self.request.user) + print(f"New todo added - Title: '{todo.title}' by user: {self.request.user.username}") + logger.info(f"New todo added - Title: '{todo.title}' by user: {self.request.user.username}") +