latest changes

This commit is contained in:
Joren de Graaf
2026-10-22 10:32:41 +02:00
parent 5799b542c8
commit 5b986134be
63 changed files with 2412 additions and 77 deletions
+34 -5
View File
@@ -1,14 +1,43 @@
"""Template context shared by Tasknest pages."""
from .models import UserSettings
from django.urls import reverse
def appearance(request):
"""Expose the signed-in user’s saved colour preference without creating settings."""
user = getattr(request, "user", None)
if user is not None and user.is_authenticated:
saved_appearance = (
UserSettings.objects.filter(user=user).values_list("appearance", flat=True).first()
)
return {"user_appearance": saved_appearance or UserSettings.Appearance.LIGHT}
return {"user_appearance": UserSettings.Appearance.LIGHT}
profile = UserSettings.objects.filter(user=user).values('appearance', 'is_demo').first()
return {"user_appearance": profile['appearance'] if profile else UserSettings.Appearance.LIGHT,
"is_demo_account": bool(profile and profile['is_demo'])}
return {"user_appearance": UserSettings.Appearance.LIGHT, "is_demo_account": False}
def navigation(request):
"""A single site navigation tree for desktop and mobile."""
user = getattr(request, 'user', None)
if not user or not user.is_authenticated:
return {'nav_groups': ()}
current = request.path
definitions = (
('tasks', 'My tasks', 'planner:task-list', (('Daily planner', 'planner:daily-planner'),)),
('health', 'Health', 'planner:health', (('Stress', 'stress:journal'), ('Dreams', 'dreams:journal'))),
('food', 'Food', 'food:diary', (('Recipes', 'recipes:list'),
('Kitchen Inventory', 'food:inventory'),
('Groceries', 'groceries:index'))),
)
groups = []
for key, label, route, children in definitions:
url = reverse(route)
items = [{'label': child_label, 'url': reverse(child_route),
'active': current.startswith(reverse(child_route))}
for child_label, child_route in children]
# Food's root URL is a prefix of its children; exact match keeps its parent state clear.
parent_active = current == url or (key == 'food' and
getattr(request.resolver_match, 'namespace', '') == 'food' and
not any(item['active'] for item in items))
groups.append({'key': key, 'label': label, 'url': url, 'items': items,
'parent_active': parent_active,
'active': parent_active or any(item['active'] for item in items)})
return {'nav_groups': groups}
+7
View File
@@ -0,0 +1,7 @@
"""A recoverable page for expired forms and CSRF cookie changes."""
from django.shortcuts import render
def csrf_failure(request, reason=''):
return render(request, 'planner/csrf_failure.html', status=403)
+8
View File
@@ -0,0 +1,8 @@
"""Server-side restrictions for the public demonstration account."""
from .models import UserSettings
def is_demo_user(user):
return bool(getattr(user, 'is_authenticated', False) and
UserSettings.objects.filter(user_id=user.pk, is_demo=True).exists())
+58 -5
View File
@@ -3,11 +3,19 @@ from datetime import datetime, time, timedelta
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone
from food.models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
from food.models import (FoodLogAttachment, InventoryCategory, InventoryConsumption,
InventoryLocation, KitchenInventoryItem, PersonalAccessToken)
from recipes.models import Recipe, RecipeSelection, CookLater, RecipeUse, RecipeCookingRun
from stress.models import StressEntry
from dreams.models import DreamEntry
from oauth2_provider.models import get_access_token_model, get_grant_model, get_refresh_token_model
from planner.models import (
BowelHealthCheckIn,
@@ -95,19 +103,29 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--username', default='demo', help='Demo username (default: demo).')
parser.add_argument('--password', default='demo', help='Demo password (default: demo).')
parser.add_argument('--password', help='Initial or replacement demo password; prefer TASKNEST_DEMO_PASSWORD.')
@transaction.atomic
def handle(self, *args, **options):
username = options['username']
password = options['password']
password = options['password'] or settings.TASKNEST_DEMO_PASSWORD
user_model = get_user_model()
user, created = user_model.objects.get_or_create(username=username)
user.set_password(password)
user = user_model.objects.filter(username=username).first()
created = user is None
if created and not password:
raise CommandError('Set TASKNEST_DEMO_PASSWORD before creating a demo account.')
if created:
user = user_model(username=username)
if not created and (user.is_staff or user.is_superuser or
UserSettings.objects.filter(user=user).exclude(is_demo=True).exists()):
raise CommandError('Refusing to reset an account that is not marked as a demo account.')
if password:
user.set_password(password)
user.is_active = True
user.save()
profile, _ = UserSettings.objects.get_or_create(user=user)
profile.is_demo = True
profile.time_zone = DEFAULT_TIME_ZONE
profile.appearance = UserSettings.Appearance.LIGHT
profile.latitude = '52.367600'
@@ -115,6 +133,11 @@ class Command(BaseCommand):
profile.onboarding_enabled = False
profile.onboarding_step = 0
profile.daily_water_goal_ml = 2000
profile.auto_count_food_drinks = True
profile.include_liquid_foods = False
profile.show_hydration_breakdown = True
profile.allow_manual_hydration_adjustments = True
profile.hydration_beverage_rules = {}
profile.daily_calorie_goal = 2000
profile.carbohydrate_goal_g = Decimal('250.0')
profile.protein_goal_g = Decimal('100.0')
@@ -136,13 +159,43 @@ class Command(BaseCommand):
WaterIntakeEntry.objects.filter(user=user).delete()
ToothBrushing.objects.filter(user=user).delete()
BowelHealthCheckIn.objects.filter(user=user).delete()
for attachment in FoodLogAttachment.objects.filter(log_entry__user=user):
storage, name = attachment.image.storage, attachment.image.name
transaction.on_commit(lambda storage=storage, name=name: storage.delete(name))
FoodLogEntry.objects.filter(user=user).delete()
StressEntry.objects.filter(user=user).delete()
DreamEntry.objects.filter(user=user).delete()
RecipeSelection.objects.filter(user=user).delete()
CookLater.objects.filter(user=user).delete()
RecipeUse.objects.filter(user=user).delete()
RecipeCookingRun.objects.filter(user=user).delete()
demo_drafts = Recipe.objects.filter(owner=user, status=Recipe.Status.DRAFT)
for recipe in demo_drafts.exclude(photo=''):
storage, name = recipe.photo.storage, recipe.photo.name
transaction.on_commit(lambda storage=storage, name=name: storage.delete(name))
demo_drafts.delete()
KitchenInventoryItem.objects.filter(user=user).delete()
InventoryConsumption.objects.filter(user=user).delete()
InventoryLocation.objects.filter(user=user).delete()
InventoryCategory.objects.filter(user=user).delete()
get_refresh_token_model().objects.filter(user=user).delete()
get_grant_model().objects.filter(user=user).delete()
get_access_token_model().objects.filter(user=user).delete()
PersonalAccessToken.objects.filter(user=user).delete()
for session in Session.objects.filter(expire_date__gt=timezone.now()).iterator():
if session.get_decoded().get('_auth_user_id') == str(user.pk):
session.delete()
FoodFavourite.objects.filter(user=user).delete()
FoodPortion.objects.filter(user=user).delete()
FoodProduct.objects.filter(owner=user).delete()
now = timezone.now()
today = localdate_for_user(user, now)
StressEntry.objects.create(user=user, score=3, daily_date=today,
note='A manageable day after a short walk.')
DreamEntry.objects.create(user=user, wake_up_date=today - timedelta(days=1),
title='The quiet garden',
narrative='I walked through a calm garden and found a familiar path home.')
ToothBrushing.objects.create(user=user, date=today - timedelta(days=1), morning=True, evening=True)
ToothBrushing.objects.create(user=user, date=today, morning=True, evening=False)
+72
View File
@@ -0,0 +1,72 @@
import logging
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
from django.utils import timezone
from .demo_policy import is_demo_user
logger = logging.getLogger(__name__)
class DemoAccountPolicyMiddleware:
"""Deny privileged and external actions even if a link is hidden in the UI."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path_info == '/o/token/' and request.method == 'POST':
from oauth2_provider.models import get_grant_model, get_refresh_token_model
grant_type = request.POST.get('grant_type')
credential = request.POST.get('refresh_token' if grant_type == 'refresh_token' else 'code')
model = (get_refresh_token_model() if grant_type == 'refresh_token'
else get_grant_model() if grant_type == 'authorization_code' else None)
field = 'token' if grant_type == 'refresh_token' else 'code'
if model and credential and model.objects.filter(
**{field: credential, 'user__planner_settings__is_demo': True}).exists():
logger.warning('Denied demo OAuth token exchange')
return JsonResponse({'error': 'access_denied'}, status=403)
if is_demo_user(request.user):
path = request.path_info
if request.method not in {'GET', 'HEAD', 'OPTIONS'}:
if request.META.get('CONTENT_LENGTH', '').isdigit() and int(request.META['CONTENT_LENGTH']) > 1024 * 1024:
return HttpResponse('Demo requests are limited to 1 MB.', status=413)
limits = (
(f'demo:writes:minute:{request.user.pk}', 60,
getattr(settings, 'DEMO_MUTATIONS_PER_MINUTE', 60)),
(f'demo:writes:day:{request.user.pk}:{timezone.localdate().isoformat()}',
86400, getattr(settings, 'DEMO_MUTATIONS_PER_DAY', 500)),
)
over_limit = False
for key, lifetime, maximum in limits:
cache.add(key, 0, lifetime)
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, lifetime)
count = 1
over_limit |= count > maximum
if over_limit:
logger.warning('Demo account write limit reached: user_id=%s', request.user.pk)
response = HttpResponse('Demo request limit reached. Try again in a minute.', status=429)
response['Retry-After'] = '60'
return response
forbidden = (path.startswith(('/o/', '/admin/', '/food/settings/tokens/')) or
path == '/settings/notifications/ntfy/test/' or
(request.method == 'POST' and path in {
'/food/search/openfoodfacts/', '/food/import/openfoodfacts/',
'/food/inventory/search/openfoodfacts/', '/food/inventory/lookup/',
}) or
(request.method == 'POST' and path.startswith('/recipes/') and
not (path == '/recipes/match/reset/' or
(path.startswith('/recipes/match/') and path.endswith('/select/')) or
path.startswith('/recipes/cook-later/'))) or
(path == '/settings/' and request.method == 'POST' and
request.POST.get('section') in {'ntfy', 'location'}))
if forbidden:
logger.warning('Denied demo account action: user_id=%s path=%s',
request.user.pk, path)
return HttpResponseForbidden('This action is unavailable in the demo account.')
return self.get_response(request)
@@ -0,0 +1,27 @@
# Generated by Django 6.1.1 on 2026-10-19 14:54
from django.db import migrations, models
def mark_existing_demo(apps, schema_editor):
User = apps.get_model('auth', 'User')
UserSettings = apps.get_model('planner', 'UserSettings')
user = User.objects.filter(username='demo', is_staff=False, is_superuser=False).first()
if user:
UserSettings.objects.filter(user_id=user.pk).update(is_demo=True)
class Migration(migrations.Migration):
dependencies = [
('planner', '0021_automatic_hydration'),
]
operations = [
migrations.AddField(
model_name='usersettings',
name='is_demo',
field=models.BooleanField(default=False, editable=False),
),
migrations.RunPython(mark_existing_demo, migrations.RunPython.noop),
]
+1
View File
@@ -105,6 +105,7 @@ class UserSettings(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='planner_settings'
)
is_demo = models.BooleanField(default=False, editable=False)
latitude = models.DecimalField(
max_digits=9, decimal_places=6, blank=True, null=True,
validators=[MinValueValidator(-90), MaxValueValidator(90)],
+3
View File
@@ -15,6 +15,7 @@ from urllib.request import urlopen
from django.core.cache import cache
from planner.models import Task, UserSettings
from planner.demo_policy import is_demo_user
OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast'
FORECAST_SEARCH_HORIZON_DAYS = 16
@@ -138,6 +139,8 @@ def _forecast_cache_key(user_id: int, latitude: Decimal, longitude: Decimal) ->
def forecasts_for_user(user) -> list[DailyForecast] | None:
"""Return cached normalized forecasts, or None when location/API is unavailable."""
if is_demo_user(user):
return None
settings = UserSettings.objects.filter(user=user).first()
if settings is None or settings.latitude is None or settings.longitude is None:
return None
+28 -3
View File
@@ -1,4 +1,29 @@
/* Keep the expanded navigation inside tablet widths as sections are added. */
@media (min-width: 701px) and (max-width: 960px) {
.primary-nav { gap: 8px; font-size: .82rem; }
/* One navigation tree is rendered for both the desktop header and mobile drawer. */
.primary-nav{gap:clamp(8px,1.3vw,20px);white-space:nowrap}
.nav-group{position:relative}
.nav-group__heading{display:flex;align-items:center}
.nav-group__heading>a{padding:9px 2px;color:#4d5852;text-decoration:none}
.nav-group__heading>a:hover,.nav-group--active .nav-group__heading>a{color:#235943}
.nav-group__toggle{display:grid;place-items:center;width:34px;height:40px;padding:0;border:0;border-radius:7px;color:#4d5852;background:transparent}
.nav-group__toggle span{display:block;font-size:1.15rem;line-height:1;transition:transform .18s ease}
.nav-group--open .nav-group__toggle span{transform:rotate(180deg)}
.nav-submenu{position:absolute;top:100%;left:0;z-index:30;min-width:190px;max-width:min(280px,90vw);margin:0;padding:6px;list-style:none;border:1px solid #d9e0d9;border-radius:12px;background:#fff;box-shadow:0 18px 45px #1d2b251c;white-space:normal}
.nav-submenu[hidden]{display:none!important}
.nav-submenu a{display:block;padding:10px 12px;border-radius:7px;color:#25292e;text-decoration:none}
.nav-submenu a:hover,.nav-submenu a[aria-current=page]{color:#174333;background:#e0f0e5}
.primary-nav a:focus-visible,.primary-nav button:focus-visible{outline:3px solid #235943;outline-offset:2px}
.nav-logout button{white-space:nowrap}
body[data-theme=dark] .nav-group__heading>a,body[data-theme=dark] .nav-group__toggle{color:#bac5bd}
body[data-theme=dark] .nav-group--active .nav-group__heading>a,body[data-theme=dark] .nav-group__heading>a:hover{color:#a9ddba}
body[data-theme=dark] .nav-submenu{border-color:#46544b;background:#242d27}
body[data-theme=dark] .nav-submenu a{color:#e8eee9}
body[data-theme=dark] .nav-submenu a:hover,body[data-theme=dark] .nav-submenu a[aria-current=page]{color:#fff;background:#355a45}
@media(min-width:701px) and (max-width:960px){.primary-nav{gap:8px;font-size:.82rem}.site-header__inner{gap:12px}}
@media(max-width:700px){
.js-nav-ready .nav-group__heading>a{display:block;flex:1;padding:11px 8px}
.js-nav-ready .nav-group__toggle{width:44px;height:44px}
.js-nav-ready .nav-submenu{position:static;min-width:0;max-width:none;margin:0 0 5px 12px;padding:0 0 0 10px;border:0;border-left:2px solid #d9e0d9;border-radius:0;box-shadow:none;background:transparent}
.js-nav-ready .nav-submenu a{padding:10px 8px}
.js-nav-ready .primary-nav>a:not(.button){display:block;padding:12px 8px}
}
@media(prefers-reduced-motion:reduce){.nav-group__toggle span{transition:none}}
+43
View File
@@ -0,0 +1,43 @@
document.addEventListener('DOMContentLoaded', () => {
const nav = document.querySelector('#primary-navigation');
if (!nav) return;
const groups = Array.from(nav.querySelectorAll('[data-nav-group]'));
const mobile = window.matchMedia('(max-width: 700px)');
const setOpen = (group, open) => {
const trigger = group.querySelector('[data-nav-submenu-toggle]');
trigger.setAttribute('aria-expanded', String(open));
group.querySelector('[data-nav-submenu]').hidden = !open;
group.classList.toggle('nav-group--open', open);
};
const closeOthers = (except = null) => groups.forEach((group) => {
if (group !== except) setOpen(group, false);
});
const revealActive = () => {
closeOthers();
if (mobile.matches) {
const active = groups.find((group) => group.classList.contains('nav-group--active'));
if (active) setOpen(active, true);
}
};
groups.forEach((group) => {
group.querySelector('[data-nav-submenu-toggle]').addEventListener('click', () => {
const opening = !group.classList.contains('nav-group--open');
closeOthers(group);
setOpen(group, opening);
});
});
document.addEventListener('pointerdown', (event) => {
if (!nav.contains(event.target)) closeOthers();
});
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape') return;
const open = groups.find((group) => group.classList.contains('nav-group--open'));
if (!open) return;
event.preventDefault();
event.stopImmediatePropagation();
setOpen(open, false);
open.querySelector('[data-nav-submenu-toggle]').focus();
}, true);
mobile.addEventListener('change', revealActive);
revealActive();
});
+9 -9
View File
@@ -7,7 +7,8 @@
<meta name="description" content="A calm, focused personal task planner.">
<title>{% block title %}Tasknest{% endblock %}</title>
{% vite_asset 'src/main.js' %}
<link rel="stylesheet" href="{% static 'planner/nav_spacing.css' %}?v=1">
<link rel="stylesheet" href="{% static 'planner/nav_spacing.css' %}?v=2">
<script src="{% static 'planner/navigation.js' %}?v=1" defer></script>
</head>
<body data-theme="{{ user_appearance }}">
<div class="app-shell">
@@ -21,14 +22,12 @@
<nav class="primary-nav" id="primary-navigation" aria-label="Primary navigation">
<button class="mobile-nav-close" type="button" data-nav-close>Close menu <span aria-hidden="true">×</span></button>
{% if user.is_authenticated %}
<a href="{% url 'planner:task-list' %}">My tasks</a>
<a id="daily-planner-nav" class="{% if onboarding_tour.target == 'daily-planner' %}onboarding-highlight{% endif %}" href="{% url 'planner:daily-planner' %}">Daily planner</a>
<a id="health-nav" class="{% if onboarding_tour.target == 'wellbeing' %}onboarding-highlight{% endif %}" href="{% url 'planner:health' %}">Health</a>
<a href="{% url 'stress:journal' %}"{% if request.resolver_match.namespace == 'stress' %} aria-current="page"{% endif %}>Stress</a>
<a href="{% url 'dreams:journal' %}"{% if request.resolver_match.namespace == 'dreams' %} aria-current="page"{% endif %}>Dreams</a>
<a href="{% url 'food:diary' %}">Food</a>
<a href="{% url 'recipes:list' %}"{% if request.resolver_match.namespace == 'recipes' %} aria-current="page"{% endif %}>Recipes</a>
<a href="{% url 'food:inventory' %}">Kitchen Inventory</a>
{% for group in nav_groups %}
<div class="nav-group{% if group.active %} nav-group--active{% endif %}" data-nav-group>
<div class="nav-group__heading"><a href="{{ group.url }}"{% if group.parent_active %} aria-current="page"{% endif %}{% if group.key == 'health' %} id="health-nav" class="{% if onboarding_tour.target == 'wellbeing' %}onboarding-highlight{% endif %}"{% endif %}>{{ group.label }}</a><button type="button" class="nav-group__toggle" aria-label="Toggle {{ group.label }} submenu" aria-expanded="false" aria-controls="nav-submenu-{{ group.key }}" data-nav-submenu-toggle><span aria-hidden="true">⌄</span></button></div>
<ul class="nav-submenu" id="nav-submenu-{{ group.key }}" data-nav-submenu hidden>{% for child in group.items %}<li><a href="{{ child.url }}"{% if child.active %} aria-current="page"{% endif %}{% if group.key == 'tasks' %} id="daily-planner-nav" class="{% if onboarding_tour.target == 'daily-planner' %}onboarding-highlight{% endif %}"{% endif %}>{{ child.label }}</a></li>{% endfor %}</ul>
</div>
{% endfor %}
<a id="settings-nav" class="{% if onboarding_tour.target == 'settings' %}onboarding-highlight{% endif %}" href="{% url 'planner:user-settings' %}">Settings</a>
<form method="post" action="{% url 'planner:user-settings' %}" class="theme-toggle">{% csrf_token %}<input type="hidden" name="section" value="appearance"><input type="hidden" name="next" value="{{ request.path }}">{% if user_appearance == 'dark' %}<input type="hidden" name="appearance" value="light"><button type="submit" aria-label="Use light mode" title="Use light mode"><span aria-hidden="true">☀</span><span class="sr-only">Use light mode</span></button>{% else %}<input type="hidden" name="appearance" value="dark"><button type="submit" aria-label="Use dark mode" title="Use dark mode"><span aria-hidden="true">☾</span><span class="sr-only">Use dark mode</span></button>{% endif %}</form>
<form method="post" action="{% url 'planner:logout' %}" class="nav-logout">{% csrf_token %}<button type="submit">Log out</button></form>
@@ -41,6 +40,7 @@
</header>
<div class="mobile-nav-backdrop" data-nav-backdrop hidden></div>
<main class="page-content {% block page_class %}{% endblock %}">
{% if is_demo_account %}<p class="flash-message" role="note">Shared demo account: other visitors can see edits you make here. Please do not enter personal information. Demo changes reset at midnight Amsterdam time.</p>{% endif %}
{% if messages %}{% for message in messages %}<p class="flash-message" role="status">{{ message }}</p>{% endfor %}{% endif %}
{% block content %}{% endblock %}
</main>
@@ -0,0 +1,10 @@
{% extends 'planner/base.html' %}
{% block title %}Form expired · Tasknest{% endblock %}
{% block content %}
<section class="settings-page">
<p class="eyebrow">Please try again</p>
<h1>This form expired</h1>
<p>Your security cookie changed or this page was open for too long. Open a fresh page and submit again.</p>
<p><a class="button" href="{% url 'planner:login' %}">Go to log in</a></p>
</section>
{% endblock %}
@@ -5,11 +5,11 @@
<p class="eyebrow">Personal preferences</p><h1>Settings</h1>
<section class="settings-card"><h2>Time zone</h2><p>Dates and displayed times, including fasting, use this time zone. Europe/Amsterdam is the default.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="time-zone">{% for field in time_zone_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save time zone</button></form></section>
<section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section>
<section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
{% if not is_demo_account %}<section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
{% endif %}<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
<section class="settings-card"><h2>Hydration</h2><p>Set your daily fluid goal and how drinks are counted.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save hydration settings</button></form></section>
<section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section>
<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section>
{% if not is_demo_account %}<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section>
<section class="settings-card" aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Enter your private topic URL, test it, then enable notifications.</p>
@@ -21,6 +21,6 @@
<button class="button" type="submit">Save notification settings</button>
</form>
</section>
<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Track fasting</strong><small>Show the daily fasting and eating timer.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section>
{% endif %}<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Track fasting</strong><small>Show the daily fasting and eating timer.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section>
</section>
{% endblock %}
+32
View File
@@ -0,0 +1,32 @@
import re
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
class CsrfRecoveryTests(TestCase):
def setUp(self):
self.client = Client(enforce_csrf_checks=True)
get_user_model().objects.create_user('csrf-synthetic', password='test-password')
def test_stale_login_form_offers_retry_and_fresh_form_succeeds(self):
login_url = reverse('planner:login')
self.client.get(login_url, secure=True)
stale = self.client.post(login_url, {
'username': 'csrf-synthetic', 'password': 'test-password',
'csrfmiddlewaretoken': 'invalid',
}, secure=True, HTTP_ORIGIN='https://testserver')
self.assertEqual(stale.status_code, 403)
self.assertContains(stale, 'This form expired', status_code=403)
self.assertContains(stale, 'Go to log in', status_code=403)
fresh = self.client.get(login_url, secure=True)
token = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"',
fresh.content.decode()).group(1)
response = self.client.post(login_url, {
'username': 'csrf-synthetic', 'password': 'test-password',
'csrfmiddlewaretoken': token,
}, secure=True, HTTP_ORIGIN='https://testserver')
self.assertRedirects(response, reverse('planner:task-list'),
fetch_redirect_response=False)
+126
View File
@@ -0,0 +1,126 @@
from django.contrib.auth import get_user_model
from django.core.files.base import ContentFile
from django.core.management import call_command
from django.core.cache import cache
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from datetime import timedelta
from oauth2_provider.models import Application, get_grant_model
from dreams.models import DreamEntry
from food.api import create_token
from food.models import PersonalAccessToken
from food.models import FoodLogAttachment, FoodLogEntry
from planner.models import UserSettings
from recipes.models import Recipe
from stress.models import StressEntry
from tempfile import TemporaryDirectory
class DemoPolicyTests(TestCase):
def setUp(self):
self.demo = get_user_model().objects.create_user('synthetic-demo', password='test')
UserSettings.objects.create(user=self.demo, is_demo=True)
self.normal = get_user_model().objects.create_user('synthetic-normal', password='test')
self.client.force_login(self.demo)
def test_demo_cannot_create_tokens_or_authorize(self):
with self.assertRaises(ValueError):
create_token(self.demo, 'blocked', ['food:read'])
self.assertEqual(self.client.get(reverse('food:tokens')).status_code, 403)
self.assertEqual(self.client.get('/o/authorize/').status_code, 403)
self.assertFalse(PersonalAccessToken.objects.filter(user=self.demo).exists())
self.assertEqual(self.client.get('/settings/notifications/ntfy/test/').status_code, 403)
def test_demo_cannot_trigger_external_requests_or_upload(self):
self.assertEqual(self.client.post('/food/search/openfoodfacts/', {'q': 'oats'}).status_code, 403)
self.assertEqual(self.client.post('/recipes/new/', content_type='multipart/form-data').status_code, 403)
self.assertEqual(self.client.post('/recipes/new/', {'title': 'Injected'}).status_code, 403)
self.assertEqual(self.client.post('/settings/', {'section': 'ntfy', 'ntfy_url': 'https://example.com'}).status_code, 403)
def test_normal_user_keeps_token_access(self):
self.client.force_login(self.normal)
self.assertEqual(self.client.get(reverse('food:tokens')).status_code, 200)
token, _ = create_token(self.normal, 'allowed', ['food:read'])
self.assertEqual(token.user_id, self.normal.pk)
def test_legacy_demo_oauth_code_cannot_be_exchanged_anonymously(self):
application = Application.objects.create(user=self.demo, name='Legacy demo client',
client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='https://example.com/callback')
get_grant_model().objects.create(user=self.demo, application=application,
code='legacy-demo-code', expires=timezone.now() + timedelta(minutes=5),
redirect_uri='https://example.com/callback', scope='food:read')
self.client.logout()
response = self.client.post('/o/token/', {'grant_type': 'authorization_code',
'code': 'legacy-demo-code'})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['error'], 'access_denied')
@override_settings(DEMO_MUTATIONS_PER_MINUTE=2)
def test_demo_mutation_rate_and_body_size_limits(self):
cache.clear()
url = reverse('planner:hydration-add')
self.assertEqual(self.client.post(url).status_code, 200)
self.assertEqual(self.client.post(url).status_code, 200)
self.assertEqual(self.client.post(url).status_code, 429)
cache.clear()
response = self.client.post(url, data='x' * (1024 * 1024 + 1), content_type='text/plain')
self.assertEqual(response.status_code, 413)
class DemoResetTests(TestCase):
def test_reset_clears_new_journals_and_tokens_without_touching_other_user(self):
call_command('seed_demo', username='synthetic-seed', password='test', verbosity=0)
demo = get_user_model().objects.get(username='synthetic-seed')
other = get_user_model().objects.create_user('synthetic-other', password='test')
temporary_stress = StressEntry.objects.create(user=demo, score=3)
StressEntry.objects.create(user=other, score=3)
temporary_dream = DreamEntry.objects.create(user=demo, wake_up_date='2026-10-19',
title='Temporary dream', narrative='Demo data')
token = PersonalAccessToken.objects.create(user=demo, name='legacy', prefix='legacy123',
token_hash='0' * 64, scopes=['food:read'])
call_command('seed_demo', username='synthetic-seed', verbosity=0)
self.assertFalse(StressEntry.objects.filter(pk=temporary_stress.pk).exists())
self.assertTrue(StressEntry.objects.filter(user=other).exists())
self.assertFalse(DreamEntry.objects.filter(pk=temporary_dream.pk).exists())
self.assertEqual(StressEntry.objects.filter(user=demo).count(), 1)
self.assertEqual(DreamEntry.objects.filter(user=demo).count(), 1)
self.assertFalse(PersonalAccessToken.objects.filter(pk=token.pk).exists())
self.assertTrue(UserSettings.objects.get(user=demo).is_demo)
demo.refresh_from_db()
self.assertTrue(demo.check_password('test'))
def test_reset_refuses_unmarked_account(self):
from django.core.management.base import CommandError
user = get_user_model().objects.create_user('synthetic-real', password='test')
UserSettings.objects.create(user=user)
with self.assertRaises(CommandError):
call_command('seed_demo', username='synthetic-real', password='test', verbosity=0)
def test_reset_removes_owned_files_and_sessions(self):
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
with self.captureOnCommitCallbacks(execute=True):
call_command('seed_demo', username='synthetic-files', password='test', verbosity=0)
demo = get_user_model().objects.get(username='synthetic-files')
recipe = Recipe.objects.create(owner=demo, title='Temporary recipe')
curated = Recipe.objects.create(owner=demo, title='Curated recipe',
status=Recipe.Status.PUBLISHED)
recipe.photo.save('recipe.png', ContentFile(b'recipe image'), save=True)
entry = FoodLogEntry.objects.filter(user=demo).first()
attachment = FoodLogAttachment(log_entry=entry, original_filename='food.png',
content_type='image/png', file_size=10)
attachment.image.save('food.png', ContentFile(b'food image'), save=True)
recipe_path, attachment_path = recipe.photo.path, attachment.image.path
self.client.force_login(demo)
with self.captureOnCommitCallbacks(execute=True):
call_command('seed_demo', username='synthetic-files', password='test', verbosity=0)
from pathlib import Path
self.assertFalse(Path(recipe_path).exists())
self.assertFalse(Path(attachment_path).exists())
self.assertTrue(Recipe.objects.filter(pk=curated.pk).exists())
self.assertFalse(Recipe.objects.filter(pk=recipe.pk).exists())
self.assertRedirects(self.client.get(reverse('planner:user-settings')),
'/login/?next=/settings/', fetch_redirect_response=False)
+22
View File
@@ -0,0 +1,22 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
@override_settings(MIDDLEWARE=[item for item in settings.MIDDLEWARE if not item.startswith('whitenoise.')],
SECURE_SSL_REDIRECT=False)
class NavigationTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='nav-test', password='test')
self.client.force_login(self.user)
def test_navigation_has_one_tree_and_active_child(self):
response = self.client.get(reverse('groceries:index'))
self.assertEqual(response.status_code, 200)
html = response.content.decode()
self.assertEqual(html.count('id="nav-submenu-food"'), 1)
self.assertIn('href="/groceries/" aria-current="page"', html)
self.assertIn('nav-group--active', html)
for url in ('/daily/', '/health/', '/food/', '/recipes/', '/food/inventory/', '/groceries/'):
self.assertIn(f'href="{url}"', html)