This commit is contained in:
Joren de Graaf
2026-10-09 14:43:46 +02:00
parent c825cd474e
commit 559c51e9bb
20 changed files with 322 additions and 27 deletions
+7 -1
View File
@@ -222,7 +222,13 @@ def _idempotent(request, payload, action, digest_override=None):
@api_view('food:read', ('GET',))
def today(request):
day = localdate_for_user(request.api_user)
requested_date = request.GET.get('date')
if requested_date is None:
day = localdate_for_user(request.api_user)
else:
day = parse_date(requested_date)
if day is None or day.isoformat() != requested_date:
return error('invalid_date', 'Use a date in YYYY-MM-DD format.')
entries = list(FoodLogEntry.objects.filter(user=request.api_user, date=day)
.select_related('product').prefetch_related('attachments'))
meals = {meal: [_entry_data(e) for e in entries if e.meal == meal] for meal in MealType.values}
+6 -1
View File
@@ -49,7 +49,7 @@ def schema(request):
'servers': [{'url': '/api/v1'}],
'components': {'securitySchemes': {'bearerToken': {'type': 'http', 'scheme': 'bearer'}}},
'paths': {
'/food/today/': {'get': operation('Current local day food log, meal groups, totals, and goals', 'food:read')},
'/food/today/': {'get': operation('Food log for an optional local calendar date, defaulting to today', 'food:read')},
'/food/products/': {'get': operation('Search own food products', 'food:read')},
'/food/log/': {'post': operation('Create food log entry', 'food:write', ENTRY)},
'/food/log/{id}/': {
@@ -77,6 +77,11 @@ def schema(request):
'schema': {'type': 'string', 'format': 'uuid'}}]
if 'post' in methods:
methods['post']['responses']['201'] = methods['post']['responses'].pop('200')
document['paths']['/food/today/']['get']['parameters'] = [{
'name': 'date', 'in': 'query', 'required': False,
'description': 'Local calendar date; defaults to today in the user time zone.',
'schema': {'type': 'string', 'format': 'date'},
}]
document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = {
'description': 'Owned image bytes',
'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}}
+21
View File
@@ -0,0 +1,21 @@
"""Adapt CIMD method negotiation for DOT's public-client-only implementation."""
from oauth2_provider.cimd import SafeMetadataFetcher
from oauth2_provider.settings import oauth2_settings
class CompatibleCIMDFetcher(SafeMetadataFetcher):
def fetch(self, client_id):
metadata, max_age = super().fetch(client_id)
methods = metadata.get('token_endpoint_auth_methods_supported')
if (
metadata.get('token_endpoint_auth_method') != 'none'
and isinstance(methods, list)
and 'none' in methods
and 'none' in oauth2_settings.OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED
):
# DOT 3.4 accepts only public CIMD clients. The plural metadata
# field explicitly allows this method even when the legacy singular
# field prefers private_key_jwt, which this server does not offer.
metadata = {**metadata, 'token_endpoint_auth_method': 'none'}
return metadata, max_age
+2 -1
View File
@@ -24,7 +24,8 @@ def selected_date(request):
def diary_context(user, day):
goals, _ = UserSettings.objects.get_or_create(user=user)
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product').defer('product__raw_data'))
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product')
.prefetch_related('attachments').defer('product__raw_data'))
totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')}
meals = []
+3
View File
@@ -15,6 +15,9 @@ body[data-theme="dark"]{--food-surface:#202923;--food-border:#3b473f;--food-ink:
.food-progress span{background:var(--food-green)}
.food-entry-main span,.food-entry-main small,.food-card>p:not(.food-remaining),.food-attribution{color:var(--food-muted);opacity:1}
.food-entry-main strong,.food-card h2,.food-card h3,.food-remaining{color:var(--food-ink)}
.food-entry-images{display:flex;gap:.35rem;flex:none;max-width:min(40vw,220px);overflow-x:auto;padding:.15rem}
.food-entry-images a{display:block;flex:none;border-radius:.6rem}
.food-entry-images a:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.inventory-page .inventory-group{margin:1.5rem 0 .5rem}.inventory-filters{display:flex;flex-wrap:wrap;gap:.75rem;align-items:end}.inventory-filters label{display:grid;gap:.25rem;min-width:130px;flex:1}.inventory-filters .inventory-check{display:flex;align-items:center;min-width:auto}.inventory-row{display:flex;align-items:center;gap:1rem}.inventory-row>img,.inventory-product>img{width:68px;height:68px;object-fit:contain;background:#fff;border-radius:.6rem}.inventory-row-main{flex:1;min-width:0}.inventory-row-main p{margin:.2rem 0}.inventory-row-actions{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}.inventory-row-actions form{display:flex;gap:.4rem}.inventory-row-actions button,.inventory-row-actions a{min-height:44px;padding:.5rem .75rem}.inventory-tag{display:inline-block;padding:.2rem .45rem;margin:.2rem .2rem 0 0;border-radius:.5rem;background:#eef1ed;color:#263828}.inventory-soon{background:#fff0c2;color:#533c00}.inventory-expired{background:#f9d9d9;color:#6b1717}.inventory-product{display:flex;gap:1rem;align-items:center}.inventory-existing{display:flex;justify-content:space-between;align-items:center;gap:.7rem;margin:.7rem 0}.inventory-form{display:grid;gap:.8rem}.inventory-form .form-field{display:grid;gap:.25rem}.inventory-form input:not([type=checkbox]),.inventory-form textarea{width:100%}@media(max-width:650px){.inventory-row{align-items:flex-start;flex-wrap:wrap}.inventory-row-actions{width:100%}.inventory-existing{align-items:flex-start;flex-direction:column}}
.inventory-quantity{display:flex;align-items:center;gap:.5rem}.inventory-quantity input{text-align:center;max-width:6rem}.inventory-quantity button{min-width:44px;min-height:44px;border:1px solid currentColor;border-radius:.5rem;background:transparent;color:inherit;font-size:1.3rem}
.food-tabs a[aria-current=page]{background:var(--food-green);border-color:var(--food-green);color:#fff}
@@ -5,7 +5,18 @@
{% for meal in meals %}
<section class="food-meal" id="meal-{{ meal.key }}" aria-labelledby="meal-title-{{ meal.key }}">
<div class="food-meal-heading"><div><h2 id="meal-title-{{ meal.key }}">{{ meal.label }}</h2><p>{{ meal.calories|floatformat:0 }} kcal</p></div><a class="food-add-meal" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal.key }}" aria-label="Add food to {{ meal.label }}">+</a></div>
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}<li class="food-entry"><div class="food-entry-main">{% if entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div></div><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a></li>{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}
<li class="food-entry">
<div class="food-entry-main">
{% with images=entry.attachments.all %}
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
{% endwith %}
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div>
</div>
<a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>
</li>
{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
</section>
{% endfor %}
<a class="button" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}">Add food</a>
+1 -1
View File
@@ -35,7 +35,7 @@
<p>Compatible assistants can use your Food and Kitchen data through MCP. Access is limited to the permissions you grant.</p>
<div class="form-field">
<label for="mcp-server-url">MCP server URL</label>
<input id="mcp-server-url" type="url" value="{{ mcp_url }}" readonly data-mcp-url>
<input id="mcp-server-url" type="url" readonly data-mcp-url>
<button class="button button--secondary" type="button" data-mcp-copy-url>Copy URL</button>
</div>
<div class="form-field">
+12
View File
@@ -105,6 +105,18 @@ class FoodApiTests(TestCase):
with patch('planner.timezones.timezone.now', return_value=datetime(2026, 1, 1, 1, tzinfo=py_timezone.utc)):
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['date'], '2025-12-31')
def test_food_diary_accepts_specific_date(self):
entry = FoodLogEntry.objects.create(user=self.a, date=datetime(2026, 1, 2).date(), meal='breakfast',
product_name_snapshot='Oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
response = self.call('get', '/api/v1/food/today/?date=2026-01-02')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['date'], '2026-01-02')
self.assertEqual(response.json()['meals']['breakfast'][0]['id'], str(entry.api_id))
self.assertEqual(response.json()['totals']['calories_kcal'], '120')
self.assertEqual(self.call('get', '/api/v1/food/today/?date=2026-01-03').json()['meals']['breakfast'], [])
for invalid in ('', 'yesterday', '2026-02-30', '2026-1-2'):
self.assertEqual(self.call('get', f'/api/v1/food/today/?date={invalid}').status_code, 400)
@override_settings(MEDIA_ROOT='/tmp/tasknest-api-test-media')
def test_attachment_validation_and_isolation(self):
entry = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
+35
View File
@@ -1,15 +1,50 @@
import base64
import hashlib
from unittest.mock import patch
from urllib.parse import parse_qs, urlparse
from django.contrib.auth import get_user_model
from django.test import TestCase
from oauth2_provider.models import Application, AccessToken
from .cimd import CompatibleCIMDFetcher
from .models import PersonalAccessToken
class McpOAuthTests(TestCase):
def test_cimd_requires_explicit_public_client_support(self):
metadata = {'token_endpoint_auth_method': 'private_key_jwt',
'token_endpoint_auth_methods_supported': ['private_key_jwt']}
with patch('oauth2_provider.cimd.SafeMetadataFetcher.fetch', return_value=(metadata, 300)):
selected, _ = CompatibleCIMDFetcher().fetch('https://example.com/client.json')
self.assertEqual(selected['token_endpoint_auth_method'], 'private_key_jwt')
def test_chatgpt_cimd_can_select_public_client_method(self):
client_id = 'https://chatgpt.com/oauth/client.json'
redirect_uri = 'https://chatgpt.com/connector_platform_oauth_redirect'
metadata = {
'client_id': client_id,
'redirect_uris': [redirect_uri],
'grant_types': ['authorization_code', 'refresh_token'],
'token_endpoint_auth_method': 'private_key_jwt',
'token_endpoint_auth_methods_supported': ['none', 'private_key_jwt'],
'client_name': 'ChatGPT',
}
user = get_user_model().objects.create_user('chatgpt-cimd-test', password='test')
self.client.force_login(user)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
with patch('oauth2_provider.cimd.SafeMetadataFetcher.fetch', return_value=(metadata, 300)):
response = self.client.get('/o/authorize/', {
'response_type': 'code', 'client_id': client_id, 'redirect_uri': redirect_uri,
'scope': 'food:read', 'state': 'cimd-test', 'code_challenge': challenge,
'code_challenge_method': 'S256', 'resource': 'https://tasksnest.jorendegraaf.eu',
}, HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
self.assertEqual(response.status_code, 200, response.content[:300])
self.assertContains(response, 'Authorize')
application = Application.objects.get(client_id=client_id)
self.assertEqual(application.client_type, Application.CLIENT_PUBLIC)
def test_authorization_code_issues_hashed_pat_and_revoke_synchronizes(self):
user = get_user_model().objects.create_user('oauth-test', password='test')
application = Application.objects.create(user=user, name='Test MCP client', client_type=Application.CLIENT_PUBLIC,
+25 -1
View File
@@ -1,8 +1,10 @@
from datetime import date
from decimal import Decimal
from tempfile import TemporaryDirectory
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import IntegrityError, transaction
from django.test import TestCase
from django.urls import reverse
@@ -10,7 +12,7 @@ from planner.models import UserSettings
from .services.diary import diary_context
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
class FoodFoundationTests(TestCase):
@@ -61,6 +63,28 @@ class FoodFoundationTests(TestCase):
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:diary')).status_code, 200)
def test_diary_shows_private_attachment_to_owner(self):
entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.DINNER,
product_name_snapshot='Dinner', amount=Decimal('250'), unit=Unit.GRAM)
image_bytes = b'example-image-bytes'
with TemporaryDirectory() as media_root, self.settings(MEDIA_ROOT=media_root):
attachment = FoodLogAttachment.objects.create(log_entry=entry,
image=SimpleUploadedFile('dinner.png', image_bytes, content_type='image/png'),
original_filename='dinner.png', content_type='image/png', file_size=len(image_bytes))
image_url = reverse('food:attachment-file', args=[attachment.api_id])
self.client.force_login(self.user)
diary = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertContains(diary, image_url, count=2)
image = self.client.get(image_url)
self.assertEqual(image.status_code, 200)
self.assertEqual(image['Content-Type'], 'image/png')
self.assertEqual(b''.join(image.streaming_content), image_bytes)
image.close()
self.client.force_login(self.other)
self.assertEqual(self.client.get(image_url).status_code, 404)
self.client.logout()
self.assertEqual(self.client.get(image_url).status_code, 302)
def test_food_goals_reject_negative_values(self):
from planner.forms import FoodGoalForm
-2
View File
@@ -1,7 +1,6 @@
from datetime import datetime, time, timedelta
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
@@ -47,7 +46,6 @@ def tokens(request):
'form': form, 'new_token': new_token,
'tokens': PersonalAccessToken.objects.filter(user=request.user).order_by('-created_at'),
'now': timezone.now(),
'mcp_url': settings.TASKNEST_MCP_PUBLIC_URL,
})
+1
View File
@@ -24,6 +24,7 @@ urlpatterns = [
path('manual/', views.manual_food, name='manual'),
path('log/<int:pk>/', views.edit_entry, name='edit'),
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
path('export/<str:period>/', views.export_csv, name='export'),
]
+15 -3
View File
@@ -7,17 +7,18 @@ import re
from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
from django.contrib import messages
from django.db.models import Q
from django.db.models import Max
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from django.views.decorators.cache import never_cache
from .forms import FoodLogForm, ManualFoodForm
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType
from .services.diary import diary_context, selected_date
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
from .services.products import local_products
@@ -144,6 +145,17 @@ def diary(request):
return render(request, 'food/diary.html', diary_context(request.user, day))
@login_required
@never_cache
@require_GET
def attachment_file(request, identifier):
attachment = get_object_or_404(FoodLogAttachment, api_id=identifier, log_entry__user=request.user)
response = FileResponse(attachment.image.open('rb'), content_type=attachment.content_type)
response['Content-Disposition'] = 'inline'
response['X-Content-Type-Options'] = 'nosniff'
return response
@login_required
@require_http_methods(['GET', 'POST'])
def add_food(request):