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

View file

@ -13,6 +13,7 @@
"Hellsén",
"isort",
"Joakim",
"kwargs",
"lovinator",
"Mailgun",
"makemigrations",

View file

@ -3,7 +3,6 @@ from __future__ import annotations
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from core.models import User
from accounts.models import User
# Register your custom User model with the admin
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

@ -1,4 +1,4 @@
# Generated by Django 5.2.4 on 2025-07-08 15:01
# Generated by Django 5.2.4 on 2025-07-21 00:54
import django.contrib.auth.models
import django.contrib.auth.validators

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

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})

View file

@ -41,7 +41,7 @@ def get_data_dir() -> Path:
DATA_DIR: Path = get_data_dir()
ADMINS: list[tuple[str, str]] = [("Joakim Hellsén", "tlovinator@gmail.com")]
AUTH_USER_MODEL = "core.User"
AUTH_USER_MODEL = "accounts.User"
BASE_DIR: Path = Path(__file__).resolve().parent.parent
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
ROOT_URLCONF = "config.urls"
@ -63,13 +63,17 @@ EMAIL_USE_SSL: bool = os.getenv(key="EMAIL_USE_SSL", default="False").lower() ==
SERVER_EMAIL: str | None = os.getenv(key="EMAIL_HOST_USER", default=None)
LOGIN_REDIRECT_URL = "/"
LOGIN_URL = "/accounts/login/"
LOGOUT_REDIRECT_URL = "/"
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_AUTHENTICATION_METHOD = "username"
ACCOUNT_EMAIL_REQUIRED = False
MEDIA_ROOT: Path = DATA_DIR / "media"
MEDIA_ROOT.mkdir(exist_ok=True)
MEDIA_URL = "/media/"
STATIC_ROOT: Path = BASE_DIR / "staticfiles"
STATIC_ROOT.mkdir(exist_ok=True)
STATIC_URL = "static/"
@ -114,7 +118,7 @@ INSTALLED_APPS: list[str] = [
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"core.apps.CoreConfig",
"accounts.apps.AccountsConfig",
"twitch.apps.TwitchConfig",
]

View file

@ -12,6 +12,7 @@ if TYPE_CHECKING:
urlpatterns: list[URLResolver] = [
path(route="admin/", view=admin.site.urls),
path(route="accounts/", view=include("accounts.urls", namespace="accounts")),
path(route="", view=include("twitch.urls", namespace="twitch")),
]

View file

@ -1,17 +0,0 @@
from __future__ import annotations
from django.apps import AppConfig
class CoreConfig(AppConfig):
"""Configuration class for the 'core' Django application.
Attributes:
default_auto_field (str): Specifies the type of auto-created primary key field to use for models in this app.
name (str): The full Python path to the application.
verbose_name (str): A human-readable name for the application.
"""
default_auto_field: str = "django.db.models.BigAutoField"
name = "core"
verbose_name: str = "Core Application"

View file

@ -39,6 +39,8 @@ lint.ignore = [
"ERA001", # Checks for commented-out Python code.
"FIX002", # Checks for "TODO" comments.
"PLR6301", # Checks for the presence of unused self parameter in methods definitions.
"ANN002", # Checks that function *args arguments have type annotations.
"ANN003", # Checks that function **kwargs arguments have type annotations.
# Conflicting lint rules when using Ruff's formatter
# https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules

View file

@ -0,0 +1,73 @@
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header bg-primary text-white">
<h4 class="mb-0"><i class="fas fa-sign-in-alt"></i> Login</h4>
</div>
<div class="card-body">
{% if form.errors %}
<div class="alert alert-danger">
<ul class="mb-0">
{% for field, errors in form.errors.items %}
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
<form method="post">
{% csrf_token %}
<div class="mb-3">
<label for="{{ form.username.id_for_label }}" class="form-label">Username</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-user"></i></span>
<input type="text" class="form-control" name="username"
id="{{ form.username.id_for_label }}" value="{{ form.username.value|default:'' }}"
required>
</div>
</div>
<div class="mb-3">
<label for="{{ form.password.id_for_label }}" class="form-label">Password</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
<input type="password" class="form-control" name="password"
id="{{ form.password.id_for_label }}" required>
</div>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary btn-lg">
<i class="fas fa-sign-in-alt"></i> Login
</button>
</div>
</form>
</div>
<div class="card-footer text-center">
<p class="mb-0">Don't have an account? <a href="{% url 'accounts:signup' %}"
class="text-decoration-none">Sign up here</a></p>
</div>
</div>
</div>
</div>
</div>
<style>
.form-control {
border-left: none;
}
.input-group-text {
background-color: #f8f9fa;
border-right: none;
}
</style>
{% endblock %}

View file

@ -0,0 +1,141 @@
{% extends 'base.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card shadow">
<div class="card-header bg-info text-white">
<h4 class="mb-0"><i class="fas fa-user-circle"></i> User Profile</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4 text-center">
<div class="avatar-placeholder bg-light rounded-circle d-inline-flex align-items-center justify-content-center"
style="width: 120px; height: 120px;">
<i class="fas fa-user fa-3x text-muted"></i>
</div>
<h5 class="mt-3">{{ user.username }}</h5>
<p class="text-muted">Member since {{ user.date_joined|date:"F Y" }}</p>
</div>
<div class="col-md-8">
<h5>Account Information</h5>
<table class="table table-borderless">
<tr>
<td><strong>Username:</strong></td>
<td>{{ user.username }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ user.email|default:"Not provided" }}</td>
</tr>
<tr>
<td><strong>First Name:</strong></td>
<td>{{ user.first_name|default:"Not provided" }}</td>
</tr>
<tr>
<td><strong>Last Name:</strong></td>
<td>{{ user.last_name|default:"Not provided" }}</td>
</tr>
<tr>
<td><strong>Date Joined:</strong></td>
<td>{{ user.date_joined|date:"F d, Y" }}</td>
</tr>
<tr>
<td><strong>Last Login:</strong></td>
<td>{{ user.last_login|date:"F d, Y H:i"|default:"Never" }}</td>
</tr>
<tr>
<td><strong>Account Status:</strong></td>
<td>
{% if user.is_active %}
<span class="badge bg-success">Active</span>
{% else %}
<span class="badge bg-danger">Inactive</span>
{% endif %}
{% if user.is_staff %}
<span class="badge bg-warning">Staff</span>
{% endif %}
{% if user.is_superuser %}
<span class="badge bg-danger">Superuser</span>
{% endif %}
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="card-footer">
<div class="d-flex justify-content-between">
<a href="{% url 'twitch:dashboard' %}" class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Back to Dashboard
</a>
<div>
<button class="btn btn-outline-primary me-2"
onclick="alert('Profile editing feature coming soon!')">
<i class="fas fa-edit"></i> Edit Profile
</button>
<a href="{% url 'accounts:logout' %}" class="btn btn-danger">
<i class="fas fa-sign-out-alt"></i> Logout
</a>
</div>
</div>
</div>
</div>
<!-- Quick Stats Card -->
<div class="card shadow mt-4">
<div class="card-header bg-secondary text-white">
<h5 class="mb-0"><i class="fas fa-chart-bar"></i> Quick Stats</h5>
</div>
<div class="card-body">
<div class="row text-center">
<div class="col-md-4">
<div class="stat-card">
<h3 class="text-primary">-</h3>
<p class="text-muted">Campaigns Tracked</p>
</div>
</div>
<div class="col-md-4">
<div class="stat-card">
<h3 class="text-success">-</h3>
<p class="text-muted">Drops Collected</p>
</div>
</div>
<div class="col-md-4">
<div class="stat-card">
<h3 class="text-info">-</h3>
<p class="text-muted">Games Followed</p>
</div>
</div>
</div>
<p class="text-center text-muted mt-3">
<i class="fas fa-info-circle"></i> Detailed statistics coming soon!
</p>
</div>
</div>
</div>
</div>
</div>
<style>
.stat-card {
padding: 1rem;
border-radius: 0.375rem;
background-color: #f8f9fa;
margin-bottom: 1rem;
}
.stat-card h3 {
font-size: 2rem;
font-weight: bold;
margin-bottom: 0.5rem;
}
.avatar-placeholder {
border: 3px solid #dee2e6;
}
</style>
{% endblock %}

View file

@ -0,0 +1,96 @@
{% extends 'base.html' %}
{% block title %}Sign Up{% endblock %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header bg-success text-white">
<h4 class="mb-0"><i class="fas fa-user-plus"></i> Sign Up</h4>
</div>
<div class="card-body">
{% if form.errors %}
<div class="alert alert-danger">
<ul class="mb-0">
{% for field, errors in form.errors.items %}
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
<form method="post">
{% csrf_token %}
<div class="mb-3">
<label for="{{ form.username.id_for_label }}" class="form-label">Username</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-user"></i></span>
<input type="text" class="form-control" name="username"
id="{{ form.username.id_for_label }}" value="{{ form.username.value|default:'' }}"
required>
</div>
{% if form.username.help_text %}
<div class="form-text">{{ form.username.help_text }}</div>
{% endif %}
</div>
<div class="mb-3">
<label for="{{ form.password1.id_for_label }}" class="form-label">Password</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
<input type="password" class="form-control" name="password1"
id="{{ form.password1.id_for_label }}" required>
</div>
{% if form.password1.help_text %}
<div class="form-text">{{ form.password1.help_text }}</div>
{% endif %}
</div>
<div class="mb-3">
<label for="{{ form.password2.id_for_label }}" class="form-label">Confirm Password</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
<input type="password" class="form-control" name="password2"
id="{{ form.password2.id_for_label }}" required>
</div>
{% if form.password2.help_text %}
<div class="form-text">{{ form.password2.help_text }}</div>
{% endif %}
</div>
<div class="d-grid">
<button type="submit" class="btn btn-success btn-lg">
<i class="fas fa-user-plus"></i> Sign Up
</button>
</div>
</form>
</div>
<div class="card-footer text-center">
<p class="mb-0">Already have an account? <a href="{% url 'accounts:login' %}"
class="text-decoration-none">Login here</a></p>
</div>
</div>
</div>
</div>
</div>
<style>
.form-control {
border-left: none;
}
.input-group-text {
background-color: #f8f9fa;
border-right: none;
}
.form-text {
font-size: 0.875em;
color: #6c757d;
}
</style>
{% endblock %}

View file

@ -4,7 +4,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Twitch Drops Tracker{% endblock %}</title>
<title>{% block title %}ttvdrops{% endblock %}</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome -->
@ -81,11 +81,43 @@
<i class="fas fa-gamepad me-1"></i> Games
</a>
</li>
{% if user.is_authenticated %}
{% if user.is_staff %}
<li class="nav-item">
<a class="nav-link" href="{% url 'admin:index' %}">
<i class="fas fa-cog me-1"></i> Admin
</a>
</li>
{% endif %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-user me-1"></i> {{ user.username }}
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="{% url 'accounts:profile' %}">
<i class="fas fa-user-circle me-2"></i> Profile
</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="{% url 'accounts:logout' %}">
<i class="fas fa-sign-out-alt me-2"></i> Logout
</a></li>
</ul>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'accounts:login' %}">
<i class="fas fa-sign-in-alt me-1"></i> Login
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'accounts:signup' %}">
<i class="fas fa-user-plus me-1"></i> Sign Up
</a>
</li>
{% endif %}
</ul>
</div>
</div>