Implement user authentication system with custom user model, views, and templates

- Created custom User model extending Django's AbstractUser.
- Added user registration, login, and profile views with corresponding templates.
- Implemented user authentication functionality and integrated Bootstrap for styling.
- Updated project settings to use the new accounts app and user model.
- Added tests for user model and admin functionality.
This commit is contained in:
Joakim Hellsén 2025-07-21 02:57:44 +02:00
commit faddc4c9b0
22 changed files with 556 additions and 24 deletions

0
accounts/__init__.py Normal file
View file

8
accounts/admin.py Normal file
View file

@ -0,0 +1,8 @@
from __future__ import annotations
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from accounts.models import User
admin.site.register(User, UserAdmin)

11
accounts/apps.py Normal file
View file

@ -0,0 +1,11 @@
from __future__ import annotations
from django.apps import AppConfig
class AccountsConfig(AppConfig):
"""Configuration for the accounts app."""
default_auto_field = "django.db.models.BigAutoField"
name = "accounts"
verbose_name = "Accounts"

36
accounts/forms.py Normal file
View file

@ -0,0 +1,36 @@
from __future__ import annotations
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from accounts.models import User
class CustomUserCreationForm(UserCreationForm):
"""Custom user creation form for the custom User model."""
class Meta:
model = User
fields = ("username",)
def __init__(self, *args, **kwargs) -> None:
"""Initialize form with Bootstrap classes."""
super().__init__(*args, **kwargs)
# Add Bootstrap classes to form fields
for field in self.fields.values():
field.widget.attrs.update({"class": "form-control"})
def clean_username(self) -> str:
"""Validate the username using the correct User model.
Returns:
str: The cleaned username.
Raises:
ValidationError: If the username already exists.
"""
username = self.cleaned_data.get("username")
if username and User.objects.filter(username=username).exists():
msg = "A user with that username already exists."
raise ValidationError(msg)
return username or ""

View file

@ -0,0 +1,44 @@
# Generated by Django 5.2.4 on 2025-07-21 00:54
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')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('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')),
('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': 'auth_user',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View file

21
accounts/models.py Normal file
View file

@ -0,0 +1,21 @@
from __future__ import annotations
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""Custom User model extending Django's AbstractUser.
This allows for future customization of the User model
while maintaining all the default Django User functionality.
"""
# Add any custom fields here in the future
# For example:
# bio = models.TextField(max_length=500, blank=True)
# avatar = models.ImageField(upload_to='avatars/', blank=True, null=True)
class Meta:
db_table = "auth_user" # Keep the same table name as Django's default User
verbose_name = "User"
verbose_name_plural = "Users"

66
accounts/tests.py Normal file
View file

@ -0,0 +1,66 @@
from __future__ import annotations
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
User = get_user_model()
class AuthenticationTestCase(TestCase):
"""Test authentication functionality."""
def setUp(self) -> None:
"""Set up test data."""
self.username = "testuser"
self.password = "testpass123"
self.user = User.objects.create_user(username=self.username, password=self.password)
def test_login_view_get(self) -> None:
"""Test login view GET request."""
response = self.client.get(reverse("accounts:login"))
assert response.status_code == 200
self.assertContains(response, "Login")
def test_signup_view_get(self) -> None:
"""Test signup view GET request."""
response = self.client.get(reverse("accounts:signup"))
assert response.status_code == 200
self.assertContains(response, "Sign Up")
def test_login_valid_user(self) -> None:
"""Test login with valid credentials."""
response = self.client.post(reverse("accounts:login"), {"username": self.username, "password": self.password})
assert response.status_code == 302 # Redirect after login
def test_login_invalid_user(self) -> None:
"""Test login with invalid credentials."""
response = self.client.post(reverse("accounts:login"), {"username": self.username, "password": "wrongpassword"})
assert response.status_code == 200 # Stay on login page
self.assertContains(response, "Please enter a correct username and password")
def test_profile_view_authenticated(self) -> None:
"""Test profile view for authenticated user."""
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse("accounts:profile"))
assert response.status_code == 200
self.assertContains(response, self.username)
def test_profile_view_unauthenticated(self) -> None:
"""Test profile view redirects unauthenticated user."""
response = self.client.get(reverse("accounts:profile"))
assert response.status_code == 302 # Redirect to login
def test_user_signup(self) -> None:
"""Test user signup functionality."""
response = self.client.post(
reverse("accounts:signup"), {"username": "newuser", "password1": "complexpass123", "password2": "complexpass123"}
)
assert response.status_code == 302 # Redirect after signup
assert User.objects.filter(username="newuser").exists()
def test_logout(self) -> None:
"""Test user logout functionality."""
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse("accounts:logout"))
assert response.status_code == 302 # Redirect after logout

View file

View file

@ -0,0 +1,86 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pytest
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import AbstractUser
from django.db.models.base import Model
from django.test import RequestFactory
if TYPE_CHECKING:
from django.contrib.admin import ModelAdmin
from django.contrib.auth.models import AbstractUser
from django.db.models.base import Model
User: type[AbstractUser] = get_user_model()
@pytest.mark.django_db
class TestUserAdmin:
"""Test cases for User admin configuration."""
def setup_method(self) -> None:
"""Set up test data for each test method."""
self.factory = RequestFactory()
self.superuser: AbstractUser = User.objects.create_superuser(
username="admin",
email="admin@example.com",
password="test_admin_password_123",
)
def test_user_model_registered_in_admin(self) -> None:
"""Test that User model is registered in Django admin."""
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
assert User in registry
def test_user_admin_class(self) -> None:
"""Test that User is registered with UserAdmin."""
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
admin_class: admin.ModelAdmin[Any] = registry[User]
assert isinstance(admin_class, UserAdmin)
def test_user_admin_can_create_user(self) -> None:
"""Test that admin can create users through the interface."""
# Test that the admin form can handle user creation
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
user_admin: admin.ModelAdmin[Any] = registry[User]
# Check that the admin has the expected methods
assert hasattr(user_admin, "get_form")
assert hasattr(user_admin, "save_model")
def test_user_admin_list_display(self) -> None:
"""Test admin list display configuration."""
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
user_admin: admin.ModelAdmin[Any] = registry[User]
# UserAdmin should have default list_display
expected_fields: tuple[str, ...] = (
"username",
"email",
"first_name",
"last_name",
"is_staff",
)
assert user_admin.list_display == expected_fields
def test_user_admin_search_fields(self) -> None:
"""Test admin search fields configuration."""
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
user_admin: admin.ModelAdmin[Any] = registry[User]
# UserAdmin should have default search fields
expected_search_fields: tuple[str, ...] = ("username", "first_name", "last_name", "email")
assert user_admin.search_fields == expected_search_fields
def test_user_admin_fieldsets(self) -> None:
"""Test admin fieldsets configuration."""
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
user_admin: admin.ModelAdmin[Any] = registry[User]
# UserAdmin should have fieldsets defined
assert hasattr(user_admin, "fieldsets")
assert user_admin.fieldsets is not None

View file

@ -0,0 +1,178 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.db import IntegrityError
if TYPE_CHECKING:
from django.contrib.auth.models import AbstractUser
User: type[AbstractUser] = get_user_model()
@pytest.mark.django_db
class TestUserModel:
"""Test cases for the custom User model."""
def test_create_user(self) -> None:
"""Test creating a regular user."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
assert user.username == "testuser"
assert user.email == "test@example.com"
assert user.check_password("testpass123")
assert not user.is_staff
assert not user.is_superuser
assert user.is_active
def test_create_superuser(self) -> None:
"""Test creating a superuser."""
superuser: AbstractUser = User.objects.create_superuser(username="admin", email="admin@example.com", password="adminpass123")
assert superuser.username == "admin"
assert superuser.email == "admin@example.com"
assert superuser.check_password("adminpass123")
assert superuser.is_staff
assert superuser.is_superuser
assert superuser.is_active
def test_user_str_representation(self) -> None:
"""Test the string representation of the user."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com")
assert str(user) == "testuser"
def test_user_email_field(self) -> None:
"""Test that email field works correctly."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
assert user.email == "test@example.com"
# Test email update
user.email = "newemail@example.com"
user.save()
user.refresh_from_db()
assert user.email == "newemail@example.com"
def test_user_unique_username(self) -> None:
"""Test that username must be unique."""
User.objects.create_user(username="testuser", email="test1@example.com", password="testpass123")
# Attempting to create another user with the same username should raise an error
with pytest.raises(IntegrityError):
User.objects.create_user(username="testuser", email="test2@example.com", password="testpass123")
def test_user_password_hashing(self) -> None:
"""Test that passwords are properly hashed."""
password = "testpass123"
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password=password)
# Password should be hashed, not stored in plain text
assert user.password != password
assert user.check_password(password)
assert not user.check_password("wrongpassword")
def test_user_without_email(self) -> None:
"""Test creating a user without email."""
user: AbstractUser = User.objects.create_user(username="testuser", password="testpass123")
assert user.username == "testuser"
assert not user.email
assert user.check_password("testpass123")
def test_user_model_meta_options(self) -> None:
"""Test the model meta options."""
assert User._meta.db_table == "auth_user" # noqa: SLF001
assert User._meta.verbose_name == "User" # noqa: SLF001
assert User._meta.verbose_name_plural == "Users" # noqa: SLF001
def test_user_manager_methods(self) -> None:
"""Test User manager methods."""
# Test create_user method
user: AbstractUser = User.objects.create_user(username="regularuser", email="regular@example.com", password="pass123")
assert not user.is_staff
assert not user.is_superuser
# Test create_superuser method
superuser: AbstractUser = User.objects.create_superuser(username="superuser", email="super@example.com", password="superpass123")
assert superuser.is_staff
assert superuser.is_superuser
def test_user_permissions(self) -> None:
"""Test user permissions and groups."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
# Initially user should have no permissions
assert not user.user_permissions.exists()
assert not user.groups.exists()
# Test has_perm method (should be False for regular user)
assert not user.has_perm("auth.add_user")
def test_user_active_status(self) -> None:
"""Test user active status functionality."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
# User should be active by default
assert user.is_active
# Test deactivating user
user.is_active = False
user.save()
user.refresh_from_db()
assert not user.is_active
def test_user_date_joined(self) -> None:
"""Test that date_joined is automatically set."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
assert user.date_joined is not None
def test_user_last_login_initially_none(self) -> None:
"""Test that last_login is initially None."""
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
assert user.last_login is None
@pytest.mark.django_db
class TestUserModelEdgeCases:
"""Test edge cases and error conditions for the User model."""
def test_create_user_without_username(self) -> None:
"""Test that creating a user without username raises an error."""
with pytest.raises(ValueError, match="The given username must be set"):
User.objects.create_user(username="", email="test@example.com", password="testpass123")
def test_create_superuser_without_is_staff(self) -> None:
"""Test that create_superuser enforces is_staff=True."""
with pytest.raises(ValueError, match=r"Superuser must have is_staff=True."):
User.objects.create_superuser(username="admin", email="admin@example.com", password="adminpass123", is_staff=False)
def test_create_superuser_without_is_superuser(self) -> None:
"""Test that create_superuser enforces is_superuser=True."""
with pytest.raises(ValueError, match=r"Superuser must have is_superuser=True."):
User.objects.create_superuser(username="admin", email="admin@example.com", password="adminpass123", is_superuser=False)
def test_user_with_very_long_username(self) -> None:
"""Test username length validation."""
# Django's default max_length for username is 150
long_username: str = "a" * 151
user = User(username=long_username, email="test@example.com")
with pytest.raises(ValidationError):
user.full_clean()
def test_user_with_invalid_email_format(self) -> None:
"""Test email format validation."""
user = User(username="testuser", email="invalid-email-format")
with pytest.raises(ValidationError):
user.full_clean()

14
accounts/urls.py Normal file
View file

@ -0,0 +1,14 @@
from __future__ import annotations
from django.urls import path
from accounts import views
app_name = "accounts"
urlpatterns = [
path("login/", views.CustomLoginView.as_view(), name="login"),
path("logout/", views.CustomLogoutView.as_view(), name="logout"),
path("signup/", views.SignUpView.as_view(), name="signup"),
path("profile/", views.profile_view, name="profile"),
]

73
accounts/views.py Normal file
View file

@ -0,0 +1,73 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import LoginView, LogoutView
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from accounts.forms import CustomUserCreationForm
from accounts.models import User
if TYPE_CHECKING:
from django.forms import BaseModelForm
from django.http import HttpRequest, HttpResponse
class CustomLoginView(LoginView):
"""Custom login view with better styling."""
template_name = "accounts/login.html"
redirect_authenticated_user = True
def get_success_url(self) -> str:
"""Redirect to the dashboard after successful login.
Returns:
str: URL to redirect to after successful login.
"""
return reverse_lazy("twitch:dashboard")
class CustomLogoutView(LogoutView):
"""Custom logout view."""
next_page = reverse_lazy("twitch:dashboard")
class SignUpView(CreateView):
"""User registration view."""
model = User
form_class = CustomUserCreationForm
template_name = "accounts/signup.html"
success_url = reverse_lazy("twitch:dashboard")
def form_valid(self, form: BaseModelForm) -> HttpResponse:
"""Login the user after successful registration.
Args:
form: The validated user creation form.
Returns:
HttpResponse: Response after successful form processing.
"""
response = super().form_valid(form)
login(self.request, self.object) # type: ignore[attr-defined]
return response
@login_required
def profile_view(request: HttpRequest) -> HttpResponse:
"""User profile view.
Args:
request: The HTTP request object.
Returns:
HttpResponse: Rendered profile template.
"""
return render(request, "accounts/profile.html", {"user": request.user})