Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,9 @@ ui-debug.log*

# Turbopack
.turbo

#backend
.venv
__pycache__/
*.pyc
.env
113 changes: 113 additions & 0 deletions Backend/API_DOCS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Authentication API Documentation

Base URL: `http://localhost:8000` (dev) | `https://your-backend.vercel.app` (prod)

## Endpoints

### 1. Register
```http
POST /auth/register/
Content-Type: application/json
```

**Request:**
```json
{
"username": "string",
"email": "string",
"password": "string",
"re_password": "string",
"first_name": "string",
"last_name": "string"
}
```

**Response (201):**
```json
{
"user": {
"id": 1,
"username": "string",
"email": "string",
"first_name": "string",
"last_name": "string"
},
"refresh": "jwt_token",
"access": "jwt_token",
"message": "Registration successful"
}
```

---

### 2. Login
```http
POST /auth/login/
Content-Type: application/json
```

**Request:**
```json
{
"email": "string",
"password": "string"
}
```

**Response (200):**
```json
{
"refresh": "jwt_token",
"access": "jwt_token"
}
```

---

### 3. Refresh Token
```http
POST /auth/token/refresh/
Content-Type: application/json
```

**Request:**
```json
{
"refresh": "jwt_token"
}
```

**Response (200):**
```json
{
"access": "jwt_token",
"refresh": "jwt_token"
}
```

---

## Authentication

For protected endpoints, include the access token in the Authorization header:

```http
Authorization: Bearer <access_token>
```

## Token Lifecycle

- **Access Token:** 60 minutes
- **Refresh Token:** 7 days
- Refresh tokens rotate on use (new refresh token returned)

## Error Responses

```json
{
"field_name": ["error message"],
"detail": "error description"
}
```

Common status codes: `400` (validation error), `401` (unauthorized), `404` (not found)
Empty file.
10 changes: 10 additions & 0 deletions Backend/apps/authentication/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User

@admin.register(User)
class UserAdmin(BaseUserAdmin):
list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff', 'created_at')
list_filter = ('is_staff', 'is_superuser', 'created_at')
search_fields = ('email', 'username', 'first_name', 'last_name')
ordering = ('-created_at',)
6 changes: 6 additions & 0 deletions Backend/apps/authentication/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class AuthenticationConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.authentication'
44 changes: 44 additions & 0 deletions Backend/apps/authentication/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Generated by Django 5.1.3 on 2025-12-04 10:27

import django.contrib.auth.models
import django.contrib.auth.validators
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')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('email', models.EmailField(max_length=254, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('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={
'db_table': 'auth_user',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
Empty file.
18 changes: 18 additions & 0 deletions Backend/apps/authentication/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.

class User(AbstractUser):
email = models.EmailField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

def __str__(self):
return self.email

class Meta:
db_table = 'auth_user'
38 changes: 38 additions & 0 deletions Backend/apps/authentication/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
write_only=True,
required=True,
validators=[validate_password]
)
re_password = serializers.CharField(write_only=True, required=True)

class Meta:
model = User
fields = ('id', 'username', 'email', 'password', 're_password', 'first_name', 'last_name')
extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True},
}

def validate(self, attrs):
if attrs['password'] != attrs['re_password']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return attrs

def create(self, validated_data):
validated_data.pop('re_password')
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
3 changes: 3 additions & 0 deletions Backend/apps/authentication/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/apps/authentication/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .views import RegisterView

urlpatterns = [
path('register/', RegisterView.as_view(), name='register'),
path('login/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
27 changes: 27 additions & 0 deletions Backend/apps/authentication/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from rest_framework import status, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import UserSerializer
from django.contrib.auth import get_user_model

User = get_user_model()

class RegisterView(generics.CreateAPIView):
queryset = User.objects.all()
permission_classes = (AllowAny,)
serializer_class = UserSerializer

def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
refresh = RefreshToken.for_user(user)
res_data = {
"user": serializer.data,
"refresh": str(refresh),
"access": str(refresh.access_token),
"message": "Registration successful"
}
return Response(res_data, status=status.HTTP_201_CREATED)
Empty file added Backend/config/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions Backend/config/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for config 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.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

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

application = get_asgi_application()
Loading