implement auth (register, login, logout)

This commit is contained in:
Matteo Rosati
2026-02-10 20:24:02 +01:00
parent b10cd41cb3
commit 266a1249d7
9 changed files with 293 additions and 4 deletions

75
api/serializers.py Normal file
View File

@@ -0,0 +1,75 @@
from django.contrib.auth import authenticate, get_user_model
from django.core.validators import validate_email
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
User = get_user_model()
class RegistrationSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField(min_length=8, write_only=True)
def validate_email(self, value):
validate_email(value)
if User.objects.filter(email__iexact=value).exists():
raise serializers.ValidationError(_("Email is already registered."))
return value
def create(self, validated_data):
email = validated_data["email"].lower()
password = validated_data["password"]
user = User.objects.create_user(
username=email,
email=email,
password=password,
)
return user
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField(write_only=True)
def validate(self, attrs):
email = attrs.get("email", "").lower()
password = attrs.get("password")
if not email or not password:
raise serializers.ValidationError(_("Email and password are required."))
user = authenticate(
request=self.context.get("request"),
username=email,
password=password,
)
if user is None:
raise serializers.ValidationError(_("Invalid email or password."))
if not user.is_active:
raise serializers.ValidationError(_("User account is disabled."))
attrs["user"] = user
return attrs
def create(self, validated_data):
user = validated_data["user"]
refresh = RefreshToken.for_user(user)
return {
"refresh": str(refresh),
"access": str(refresh.access_token),
}
class LogoutSerializer(serializers.Serializer):
refresh = serializers.CharField()
def validate(self, attrs):
refresh = attrs.get("refresh")
if not refresh:
raise serializers.ValidationError(_("Refresh token is required."))
return attrs
def create(self, validated_data):
refresh = RefreshToken(validated_data["refresh"])
refresh.blacklist()
return {}

9
api/urls.py Normal file
View File

@@ -0,0 +1,9 @@
from django.urls import path
from .views import LoginView, LogoutView, RegisterView
urlpatterns = [
path("auth/register", RegisterView.as_view(), name="auth-register"),
path("auth/login", LoginView.as_view(), name="auth-login"),
path("auth/logout", LogoutView.as_view(), name="auth-logout"),
]

View File

@@ -1,3 +1,67 @@
from django.shortcuts import render from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here. from .serializers import LoginSerializer, LogoutSerializer, RegistrationSerializer
class RegisterView(APIView):
permission_classes = [permissions.AllowAny]
throttle_scope = "auth"
def post(self, request):
serializer = RegistrationSerializer(data=request.data)
if not serializer.is_valid():
return Response(
{"errors": serializer.errors},
status=status.HTTP_400_BAD_REQUEST,
)
user = serializer.save()
login_serializer = LoginSerializer(
data={
"email": user.email,
"password": request.data.get("password"),
},
context={"request": request},
)
login_serializer.is_valid(raise_exception=True)
tokens = login_serializer.save()
return Response(
{
"user": {
"id": user.id,
"email": user.email,
},
"tokens": tokens,
},
status=status.HTTP_201_CREATED,
)
class LoginView(APIView):
permission_classes = [permissions.AllowAny]
throttle_scope = "auth"
def post(self, request):
serializer = LoginSerializer(data=request.data, context={"request": request})
if not serializer.is_valid():
return Response(
{"errors": serializer.errors},
status=status.HTTP_400_BAD_REQUEST,
)
tokens = serializer.save()
return Response({"tokens": tokens}, status=status.HTTP_200_OK)
class LogoutView(APIView):
permission_classes = [permissions.IsAuthenticated]
def post(self, request):
serializer = LogoutSerializer(data=request.data)
if not serializer.is_valid():
return Response(
{"errors": serializer.errors},
status=status.HTTP_400_BAD_REQUEST,
)
serializer.save()
return Response({"detail": "Logged out."}, status=status.HTTP_200_OK)

Binary file not shown.

View File

@@ -10,6 +10,7 @@ For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/ https://docs.djangoproject.com/en/6.0/ref/settings/
""" """
from datetime import timedelta
from pathlib import Path from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
@@ -32,6 +33,9 @@ ALLOWED_HOSTS = []
INSTALLED_APPS = [ INSTALLED_APPS = [
"api", "api",
"rest_framework",
"rest_framework_simplejwt",
"rest_framework_simplejwt.token_blacklist",
"django.contrib.admin", "django.contrib.admin",
"django.contrib.auth", "django.contrib.auth",
"django.contrib.contenttypes", "django.contrib.contenttypes",
@@ -116,3 +120,29 @@ USE_TZ = True
# https://docs.djangoproject.com/en/6.0/howto/static-files/ # https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = "static/" STATIC_URL = "static/"
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
"DEFAULT_PARSER_CLASSES": ("rest_framework.parsers.JSONParser",),
"DEFAULT_RENDERER_CLASSES": ("rest_framework.renderers.JSONRenderer",),
"DEFAULT_THROTTLE_CLASSES": (
"rest_framework.throttling.AnonRateThrottle",
"rest_framework.throttling.UserRateThrottle",
"rest_framework.throttling.ScopedRateThrottle",
),
"DEFAULT_THROTTLE_RATES": {
"anon": "20/min",
"user": "60/min",
"auth": "5/min",
},
}
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
"REFRESH_TOKEN_LIFETIME": timedelta(days=7),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
"AUTH_HEADER_TYPES": ("Bearer",),
}

View File

@@ -14,9 +14,11 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path 1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
""" """
from django.contrib import admin from django.contrib import admin
from django.urls import path from django.urls import include, path
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path("admin/", admin.site.urls),
path("api/", include("api.urls")),
] ]

View File

@@ -6,5 +6,7 @@ readme = "README.md"
requires-python = ">=3.13" requires-python = ">=3.13"
dependencies = [ dependencies = [
"django>=6.0.2", "django>=6.0.2",
"djangorestframework>=3.16.1",
"djangorestframework-simplejwt>=5.5.0",
"pydantic>=2.12.5", "pydantic>=2.12.5",
] ]

68
specs/authentication.md Normal file
View File

@@ -0,0 +1,68 @@
# Authentication
- Write a fully functional API based authentication system for this application.
- There must be two available endpoints, one for the registration, one for the login. Both only speak JSON and both are POST only.
- The authentication must be token based. When a user authenticates, the response returns a token that uniquely identifies the user, and can be used for the next API calls.
- The implementation must be secure, solid, and be production ready.
- If necessary, add python / django packages to simplify the implementation.
You must interview the user on this specs to gather as many information as you think it's necessary to make this implementation solid as rock, then update this file with an accurate implementation plan.
## Registration
The registration accepts two fields in the payload:
- email: mandatory, valid email.
- password: mandatory, 8 characters minimum.
The endpoint must validate the data and return meaningful JSON error messages. When it runs without errors, it creates a new user.
## Login
The login endpoint accepts two fields in the payload:
- email: mandatory, valid email.
- password: mandatory
If the user is found in the database, the API returns a token for that user.
## Logout
Provide also a logout mechanism that invalidates or deletes the current user token.
## Implementation Plan
Assumptions (defaulted since only routes were confirmed):
- Use Django REST Framework + SimpleJWT.
- Access token lifetime: 15 minutes; refresh token lifetime: 7 days.
- Enable token blacklist app to invalidate refresh tokens on logout.
- Keep default Django `User` model; store email as the unique identifier, set `username = email` on registration.
- Add throttling for login/registration to reduce abuse.
- Routes: `/api/auth/register`, `/api/auth/login`, `/api/auth/logout` (JSON-only, POST).
Steps:
1) Add packages
- Add `djangorestframework`, `djangorestframework-simplejwt`, and `djangorestframework-simplejwt[token_blacklist]` to dependencies.
2) Configure settings
- Add `rest_framework`, `rest_framework_simplejwt`, and `rest_framework_simplejwt.token_blacklist` to `INSTALLED_APPS`.
- Configure `REST_FRAMEWORK` defaults for JSON-only responses, authentication classes (JWT), and throttling classes/rates.
- Configure `SIMPLE_JWT` lifetimes and blacklist settings.
3) Add API routes
- Create `api/urls.py` and include under `dronewars/urls.py` at `path("api/", include(...))`.
- Add routes:
- POST `/api/auth/register`
- POST `/api/auth/login`
- POST `/api/auth/logout`
4) Implement serializers
- `RegistrationSerializer`: validate email format, enforce minimum password length (>= 8), ensure email uniqueness, create user with `set_password`, set `username=email`.
- `LoginSerializer`: validate credentials using `authenticate`, return SimpleJWT token pair.
5) Implement views
- `RegisterView`: create user; return token pair on success.
- `LoginView`: return token pair for valid credentials; return JSON errors on failure.
- `LogoutView`: accept refresh token, blacklist it, return success JSON.
6) Error handling
- Return consistent JSON errors with field-level messages for validation failures and authentication errors.
7) Tests (if present or required)
- Add basic tests for registration, login, and logout success/failure paths.
If any assumption should change (token lifetimes, user model, blacklist behavior, throttling), update this plan before implementation.

39
uv.lock generated
View File

@@ -34,18 +34,48 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/96/ba/a6e2992bc5b8c688249c00ea48cb1b7a9bc09839328c81dc603671460928/django-6.0.2-py3-none-any.whl", hash = "sha256:610dd3b13d15ec3f1e1d257caedd751db8033c5ad8ea0e2d1219a8acf446ecc6", size = 8339381, upload-time = "2026-02-03T13:50:15.501Z" }, { url = "https://files.pythonhosted.org/packages/96/ba/a6e2992bc5b8c688249c00ea48cb1b7a9bc09839328c81dc603671460928/django-6.0.2-py3-none-any.whl", hash = "sha256:610dd3b13d15ec3f1e1d257caedd751db8033c5ad8ea0e2d1219a8acf446ecc6", size = 8339381, upload-time = "2026-02-03T13:50:15.501Z" },
] ]
[[package]]
name = "djangorestframework"
version = "3.16.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "django" },
]
sdist = { url = "https://files.pythonhosted.org/packages/8a/95/5376fe618646fde6899b3cdc85fd959716bb67542e273a76a80d9f326f27/djangorestframework-3.16.1.tar.gz", hash = "sha256:166809528b1aced0a17dc66c24492af18049f2c9420dbd0be29422029cfc3ff7", size = 1089735, upload-time = "2025-08-06T17:50:53.251Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b0/ce/bf8b9d3f415be4ac5588545b5fcdbbb841977db1c1d923f7568eeabe1689/djangorestframework-3.16.1-py3-none-any.whl", hash = "sha256:33a59f47fb9c85ede792cbf88bde71893bcda0667bc573f784649521f1102cec", size = 1080442, upload-time = "2025-08-06T17:50:50.667Z" },
]
[[package]]
name = "djangorestframework-simplejwt"
version = "5.5.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "django" },
{ name = "djangorestframework" },
{ name = "pyjwt" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a8/27/2874a325c11112066139769f7794afae238a07ce6adf96259f08fd37a9d7/djangorestframework_simplejwt-5.5.1.tar.gz", hash = "sha256:e72c5572f51d7803021288e2057afcbd03f17fe11d484096f40a460abc76e87f", size = 101265, upload-time = "2025-07-21T16:52:25.026Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/60/94/fdfb7b2f0b16cd3ed4d4171c55c1c07a2d1e3b106c5978c8ad0c15b4a48b/djangorestframework_simplejwt-5.5.1-py3-none-any.whl", hash = "sha256:2c30f3707053d384e9f315d11c2daccfcb548d4faa453111ca19a542b732e469", size = 107674, upload-time = "2025-07-21T16:52:07.493Z" },
]
[[package]] [[package]]
name = "dronewars" name = "dronewars"
version = "0.1.0" version = "0.1.0"
source = { virtual = "." } source = { virtual = "." }
dependencies = [ dependencies = [
{ name = "django" }, { name = "django" },
{ name = "djangorestframework" },
{ name = "djangorestframework-simplejwt" },
{ name = "pydantic" }, { name = "pydantic" },
] ]
[package.metadata] [package.metadata]
requires-dist = [ requires-dist = [
{ name = "django", specifier = ">=6.0.2" }, { name = "django", specifier = ">=6.0.2" },
{ name = "djangorestframework", specifier = ">=3.16.1" },
{ name = "djangorestframework-simplejwt", specifier = ">=5.5.0" },
{ name = "pydantic", specifier = ">=2.12.5" }, { name = "pydantic", specifier = ">=2.12.5" },
] ]
@@ -117,6 +147,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9f/ed/068e41660b832bb0b1aa5b58011dea2a3fe0ba7861ff38c4d4904c1c1a99/pydantic_core-2.41.5-cp314-cp314t-win_arm64.whl", hash = "sha256:35b44f37a3199f771c3eaa53051bc8a70cd7b54f333531c59e29fd4db5d15008", size = 1974769, upload-time = "2025-11-04T13:42:01.186Z" }, { url = "https://files.pythonhosted.org/packages/9f/ed/068e41660b832bb0b1aa5b58011dea2a3fe0ba7861ff38c4d4904c1c1a99/pydantic_core-2.41.5-cp314-cp314t-win_arm64.whl", hash = "sha256:35b44f37a3199f771c3eaa53051bc8a70cd7b54f333531c59e29fd4db5d15008", size = 1974769, upload-time = "2025-11-04T13:42:01.186Z" },
] ]
[[package]]
name = "pyjwt"
version = "2.11.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5c/5a/b46fa56bf322901eee5b0454a34343cdbdae202cd421775a8ee4e42fd519/pyjwt-2.11.0.tar.gz", hash = "sha256:35f95c1f0fbe5d5ba6e43f00271c275f7a1a4db1dab27bf708073b75318ea623", size = 98019, upload-time = "2026-01-30T19:59:55.694Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/6f/01/c26ce75ba460d5cd503da9e13b21a33804d38c2165dec7b716d06b13010c/pyjwt-2.11.0-py3-none-any.whl", hash = "sha256:94a6bde30eb5c8e04fee991062b534071fd1439ef58d2adc9ccb823e7bcd0469", size = 28224, upload-time = "2026-01-30T19:59:54.539Z" },
]
[[package]] [[package]]
name = "sqlparse" name = "sqlparse"
version = "0.5.5" version = "0.5.5"