diff --git a/.gitignore b/.gitignore index 4684555..94d6be2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ venv/ env/ ENV/ tasksnest-host/ +tasksnest/ # Environment / secrets .env @@ -24,6 +25,7 @@ local_settings.py # User-uploaded media media/ +main/private_media/ # Collected static files staticfiles/ @@ -62,4 +64,4 @@ Thumbs.db *.sqlite3 playwright/.auth/ -#AGENTS.md \ No newline at end of file +#AGENTS.md diff --git a/AGENTS.md b/AGENTS.md index 49d7f01..08c74ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,113 +1,21 @@ -Please update the project's `AGENTS.md` to document our browser-based UI testing workflow. - -Playwright MCP is now available to you and should be used when working on frontend, UI, UX, responsive-layout, JavaScript, HTMX, accessibility, or other browser-visible changes. - -Add an appropriate section to `AGENTS.md` covering the following requirements. -If needed you can install the required modules for it. +# Project working instructions ## Browser and visual testing -Playwright MCP is available for interacting with and inspecting the actual rendered application. +Use Playwright MCP for frontend, UI, UX, responsive layout, JavaScript, HTMX, accessibility, and other browser-visible changes. Open the running Django application and inspect the rendered result; source inspection alone does not verify appearance or behavior. After a significant change, reload the affected page, inspect it, exercise relevant controls and HTMX interactions, and check the browser console after JavaScript or HTMX changes. Use screenshots for appearance, spacing, typography, sizing, alignment, colour, hierarchy, overflow, and responsive behavior. Use the accessibility/DOM representation for structure, names, labels, state, and interactions. Test desktop and mobile viewports for responsive interfaces, plus intermediate widths where useful. A visual task is incomplete until the rendered result has been inspected. -When working on browser-visible changes: - -- Use Playwright to open the running Django application and inspect the actual rendered result. -- Do not judge whether a visual change is correct solely by reading Django templates, HTML, SCSS/CSS, or JavaScript. -- After significant UI changes, reload the relevant page and inspect the result in the browser. -- Use screenshots when evaluating visual appearance, spacing, typography, sizing, alignment, colour, hierarchy, overflow, or responsive behaviour. -- Use the accessibility/DOM representation where it is more appropriate for understanding page structure, controls, labels, state, and interactions. -- Test relevant interactions rather than assuming they work from reading the implementation. -- Check browser console errors after changes involving JavaScript or HTMX. -- Verify important HTMX interactions in the browser. -- Test both desktop and mobile-sized viewports when the affected interface is responsive. -- When appropriate, test intermediate viewport widths as well rather than only the two extremes. -- Do not consider a visual task complete until the rendered result has actually been inspected. - -When reporting findings from browser inspection, distinguish between: -1. problems actually observed in the rendered application; -2. accessibility or functional problems discovered through browser inspection; -3. optional design suggestions. - -Do not present subjective redesign suggestions as bugs. - -Do not redesign unrelated parts of the application simply because browser inspection reveals opportunities for improvement. Keep changes within the requested scope unless explicitly asked otherwise. +In findings, distinguish observed visual problems, accessibility or functional problems found in the browser, and optional design suggestions. Do not present subjective redesign suggestions as bugs or redesign unrelated areas. ## Authentication and demo account -The application has a dedicated demo/test account intended for development and browser testing. +Playwright may use the dedicated demo account to navigate authenticated pages and create, edit, or delete its own test data. Never modify another user's data. Reuse an authenticated Playwright session when available. Credentials may be supplied interactively; never commit passwords, cookies, session or CSRF tokens, or other credentials. Never put demo credentials in this file or source/configuration files. If browser authentication state is exported, store it in `playwright/.auth/` and keep that directory in `.gitignore`. -Playwright may use this account when authentication is required. +## Browser testing behavior -The demo account may be used to: -- navigate authenticated parts of the application; -- create test data; -- edit test data belonging to the demo user; -- delete test data belonging to the demo user; -- exercise forms and interactive features; -- test authenticated HTMX/browser behaviour. +Browser access is for verification and debugging, not permission for arbitrary changes. For an inspection-only request, reproduce and inspect the relevant state, take screenshots when useful, report findings, and leave project files untouched. For an implementation request, inspect the current rendered state when useful, make the requested change, reload and inspect the page, test relevant interactions, check browser errors, inspect relevant viewport sizes, and fix introduced problems. Prefer rendered observations over assumptions from templates or styles. -Never modify data belonging to other users. - -Prefer reusing an existing authenticated Playwright browser session when one is available rather than repeatedly logging in. - -The demo account credentials should not be written into `AGENTS.md`, source code, committed configuration, or other repository files. They can be supplied interactively when authentication is required. - -Do not copy authentication cookies, session tokens, CSRF tokens, passwords, or other credentials into committed files. - -If Playwright authentication state is ever exported to a file, store it in a dedicated location such as: - -`playwright/.auth/` - -and ensure that directory is excluded by `.gitignore`. - -## Browser testing behaviour - -Browser access is a verification and debugging tool, not permission to make arbitrary changes. - -When asked to inspect something without modifying it: -- browse the application; -- reproduce the relevant state; -- inspect it; -- take screenshots if useful; -- report findings; -- do not change project files. - -When asked to implement a browser-visible change: -1. inspect the current rendered state when useful; -2. implement the requested change; -3. reload/open the affected page; -4. inspect the rendered result; -5. exercise the relevant interaction if applicable; -6. check for browser/console errors; -7. inspect responsive behaviour where relevant; -8. fix problems introduced by the change before considering the task complete. - -For visual verification, prefer observations from the actual rendered application over assumptions derived from source code. - -If the Django development server is not running, determine the project's normal development command from the repository rather than inventing a new development setup. Starting the existing development server for browser testing is allowed when appropriate. - -Do not alter production configuration merely to make browser testing easier. +If the Django server is stopped, find and use the repository's normal development command. Do not change production configuration to ease testing. ## Accessibility -Use browser testing to help catch accessibility regressions when working on UI. - -Where relevant, verify: -- semantic controls and headings; -- accessible names and labels; -- keyboard-operable interactive elements; -- visible focus behaviour; -- sensible form validation/error presentation; -- appropriate ARIA state where custom controls require it; -- obvious colour/contrast or readability problems; -- behaviour at narrow/mobile viewport sizes. - -Do not treat the accessibility tree alone as proof that the visual interface is correct. Likewise, do not treat a screenshot alone as proof that the interface is accessible. Use the appropriate browser information for each. - -Please integrate these rules cleanly into the existing `AGENTS.md` rather than blindly appending duplicate or conflicting instructions. - -Preserve any existing useful project-specific instructions. - -Before editing, read the current `AGENTS.md` if one exists and adapt the new section to its existing structure and terminology. - -Afterwards, show me the resulting section or summarise exactly what you added. Do not make unrelated project changes. \ No newline at end of file +For UI changes, check relevant semantic headings and controls, accessible names and labels, keyboard operation and visible focus, form errors, ARIA state for custom controls, obvious contrast/readability problems, and narrow viewport behavior. Use both visual inspection and the accessibility/DOM representation where each is appropriate; neither alone proves the other. diff --git a/main/API.md b/main/API.md new file mode 100644 index 0000000..966a6d3 --- /dev/null +++ b/main/API.md @@ -0,0 +1,47 @@ +# TaskNest Food and Kitchen API v1 + +The API is intended for a future thin MCP adapter. It is available under `/api/v1/`; machine-readable OpenAPI 3.1 is at `/api/v1/schema/`. No MCP server or interactive production API UI is included. + +## Authentication and permissions + +Create a personal token in Settings → API access. The full `tn_...` token is shown once. Send it as `Authorization: Bearer `. A token identifies its owner; API requests do not accept a user identifier. Tokens can have `food:read`, `food:write`, `inventory:read`, and `inventory:write`. A missing, invalid, revoked, or expired token returns HTTP 401. A missing scope returns HTTP 403. The token management screen supports optional expiry and revocation. HTTPS is required in deployment to protect bearer tokens in transit. + +Each resource lookup filters by the token owner. An unknown UUID and another user's UUID both return 404. The API does not use session authentication, and its bearer-token views are CSRF exempt. Default Django CORS policy does not grant cross-origin browser access. Do not log `Authorization` headers. + +## Endpoints + +| Method | Route | Scope | Purpose | +| --- | --- | --- | --- | +| GET | `/food/today/` | `food:read` | User-local date, entries grouped by meal, seven daily totals, and existing goals | +| GET | `/food/products/?search=&limit=30&offset=0` | `food:read` | Own products, nutrition per 100, and portions; no `raw_data` | +| POST | `/food/log/` | `food:write` | Create from an owned `product_id` or manual snapshot | +| GET/PATCH/DELETE | `/food/log/{id}/` | read/write | Own log entry | +| POST | `/food/log/{id}/attachments/` | `food:write` | Multipart image upload to an owned entry | +| GET | `/food/attachments/{id}/file/` | `food:read` | Authenticated image retrieval | +| DELETE | `/food/attachments/{id}/` | `food:write` | Delete an owned image | +| GET/POST | `/kitchen/items/` | read/write | Search/list or create inventory item | +| GET/PATCH/DELETE | `/kitchen/items/{id}/` | read/write | Own inventory item | + +Collection responses use `count`, `limit`, `offset`, and `results`. The default limit is 30 and maximum is 100; `offset` is capped at 10,000. Product and inventory search checks name, brand, and barcode; inventory search also checks location and category. `GET /food/today/` is naturally bounded by one day. + +JSON decimal values are strings to preserve precision. For food creation, send `meal`, positive decimal `amount`, and `unit` (`g` or `ml`). With `product_id`, nutrition and name snapshots are calculated from that owned product using the same service as the web UI, and the unit must match its basis. Without a product, send `product_name` and optional `brand`, `barcode`, `portion_label`, and nutrition totals (`calories_kcal`, `carbohydrates_g`, `protein_g`, `fat_g`, `fibre_g`, `sugars_g`, `salt_g`). Manual entries are snapshot-only, so repeat estimates do not create duplicate products. `date` defaults to the user's saved local time zone date; an explicit ISO date and optional time can be supplied. API entries have `created_via: api`, separate from their nutrition `source`. + +Inventory creation requires an owned product UUID, positive integer `quantity`, and a location name. Optional fields are `category`, `notes`, `opened`, and `best_before`. Location and category names reuse the application's owned lookup records. There is no invented inventory unit: the existing model counts whole items. DELETE removes the item, matching the API operation; the web inventory still has its separate archive behavior. + +For attachment upload, send multipart `image` and optional `caption`. JPEG, PNG, and WebP are accepted after decoding and format/MIME checks. The file limit is 5 MiB and the pixel limit is 25 million. Images are stored under `main/private_media/`, which has no public media URL; download requires `food:read` and ownership of the parent entry. Filenames on disk are random. The original filename is metadata only. + +POST creation routes accept an optional `Idempotency-Key` header. Repeating the same token, route, key, and body returns the stored result and creates no second record. Reusing a key with a different body or route returns 409. Keys are per token. JSON errors use `{"error":{"code":"...","message":"..."}}`; validation may include `details`. Common codes include `invalid_token`, `expired_token`, `insufficient_scope`, `entry_not_found`, `product_not_found`, `inventory_item_not_found`, `image_too_large`, and `unsupported_image_type`. + +## Example requests + +```sh +TOKEN='' +curl -H "Authorization: Bearer $TOKEN" https://example.com/api/v1/food/today/ +curl -H "Authorization: Bearer $TOKEN" 'https://example.com/api/v1/food/products/?search=pasta' +curl -X POST https://example.com/api/v1/food/log/ \ + -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -H 'Idempotency-Key: dinner-2026-10-07-1' \ + -d '{"meal":"dinner","product_name":"Homemade satay","amount":"1","unit":"g","calories_kcal":"850"}' +curl -X POST https://example.com/api/v1/food/log/ENTRY_UUID/attachments/ \ + -H "Authorization: Bearer $TOKEN" -F 'image=@meal.jpg;type=image/jpeg' -F 'caption=Dinner' +``` diff --git a/main/food/api.py b/main/food/api.py new file mode 100644 index 0000000..1dc8ecd --- /dev/null +++ b/main/food/api.py @@ -0,0 +1,484 @@ +"""Token-authenticated, owner-scoped HTTP API for future MCP adapters.""" +import hashlib +import hmac +import json +import secrets +from decimal import Decimal +from functools import wraps +from uuid import UUID + +from PIL import Image, UnidentifiedImageError +from django.core.exceptions import ValidationError +from django.db import transaction +from django.db.models import Q +from django.http import FileResponse, JsonResponse +from django.utils import timezone +from django.utils.dateparse import parse_date, parse_time +from django.views.decorators.csrf import csrf_exempt + +from planner.models import UserSettings +from planner.timezones import localdate_for_user +from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct, + InventoryCategory, InventoryLocation, KitchenInventoryItem, + MealType, PersonalAccessToken, Unit) +from .services.logging import apply_product_snapshot + +SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'} +NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') +MANUAL_FIELDS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') +MAX_IMAGE_BYTES = 5 * 1024 * 1024 + + +def error(code, message, status=400, details=None): + payload = {'error': {'code': code, 'message': message}} + if details: + payload['error']['details'] = details + return JsonResponse(payload, status=status) + + +def token_value(): + prefix = secrets.token_hex(8) + secret = secrets.token_urlsafe(32) + return prefix, f'tn_{prefix}_{secret}' + + +def create_token(user, name, scopes, expires_at=None): + prefix, value = token_value() + token = PersonalAccessToken.objects.create(user=user, name=name, prefix=prefix, + token_hash=hashlib.sha256(value.encode()).hexdigest(), scopes=sorted(set(scopes)), expires_at=expires_at) + return token, value + + +def _authenticate(request): + header = request.headers.get('Authorization', '') + if not header.startswith('Bearer '): + return None, error('authentication_required', 'Provide a Bearer API token.', 401) + raw = header[7:] + if len(raw) > 512: + return None, error('invalid_token', 'Invalid API token.', 401) + parts = raw.split('_', 2) + prefix = parts[1] if len(parts) == 3 and parts[0] == 'tn' else '' + token = PersonalAccessToken.objects.select_related('user').filter(prefix=prefix).first() if prefix else None + if token is None or not hmac.compare_digest(token.token_hash, hashlib.sha256(raw.encode()).hexdigest()): + return None, error('invalid_token', 'Invalid API token.', 401) + if token.revoked_at: + return None, error('revoked_token', 'API token has been revoked.', 401) + if token.expires_at and token.expires_at <= timezone.now(): + return None, error('expired_token', 'API token has expired.', 401) + PersonalAccessToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now()) + return token, None + + +def api_view(scope, methods): + def decorator(view): + @csrf_exempt + @wraps(view) + def wrapped(request, *args, **kwargs): + if request.method not in methods: + return error('method_not_allowed', 'Method not allowed.', 405) + token, failure = _authenticate(request) + if failure: + return failure + required_scope = scope.get(request.method) if isinstance(scope, dict) else scope + if required_scope not in token.scopes: + return error('insufficient_scope', f'Missing {required_scope} scope.', 403) + request.api_token = token + request.api_user = token.user + try: + return view(request, *args, **kwargs) + except (ValueError, ValidationError) as exc: + return error('invalid_request', 'Invalid request data.', 400, str(exc)) + return wrapped + return decorator + + +def _json(request): + if request.content_type != 'application/json': + raise ValueError('Use application/json.') + try: + payload = json.loads(request.body) + except (UnicodeDecodeError, json.JSONDecodeError): + raise ValueError('Malformed JSON.') from None + if not isinstance(payload, dict): + raise ValueError('Expected a JSON object.') + return payload + + +def _decimal(value, name, positive=False): + try: + result = Decimal(str(value)) + except Exception: + raise ValueError(f'Invalid {name}.') from None + if not result.is_finite() or result < 0 or (positive and result == 0): + raise ValueError(f'Invalid {name}.') + return result + + +def _uuid(value): + try: + return UUID(str(value)) + except (TypeError, ValueError, AttributeError): + raise ValueError('Invalid API identifier.') from None + + +def _date(value, user): + if value is None: + return localdate_for_user(user) + result = parse_date(str(value)) + if result is None or result.isoformat() != value: + raise ValueError('Enter date as YYYY-MM-DD.') + return result + + +def _time(value): + if value is None or value == '': + return None + result = parse_time(str(value)) + if result is None: + raise ValueError('Invalid time.') + return result + + +def _page(request, queryset): + try: + limit = int(request.GET.get('limit', 30)) + offset = int(request.GET.get('offset', 0)) + except ValueError: + raise ValueError('Invalid pagination.') from None + if not 1 <= limit <= 100 or not 0 <= offset <= 10000: + raise ValueError('Pagination out of range.') + return {'count': queryset.count(), 'limit': limit, 'offset': offset, + 'results': queryset[offset:offset + limit]} + + +def _attachment_data(item): + return {'id': str(item.api_id), 'original_filename': item.original_filename, + 'content_type': item.content_type, 'file_size': item.file_size, + 'caption': item.caption, 'created_at': item.created_at.isoformat(), + 'download_url': f'/api/v1/food/attachments/{item.api_id}/file/'} + + +def _entry_data(entry): + data = {name: getattr(entry, name) for name in ( + 'meal', 'product_name_snapshot', 'brand_snapshot', 'barcode_snapshot', + 'portion_label_snapshot', 'amount', 'unit', *NUTRIENTS, 'source', 'created_via')} + data.update(id=str(entry.api_id), date=entry.date.isoformat(), + time=entry.time.isoformat() if entry.time else None, + product_id=str(entry.product.api_id) if entry.product_id else None, + attachments=[_attachment_data(item) for item in entry.attachments.all()], + created_at=entry.created_at.isoformat(), updated_at=entry.updated_at.isoformat()) + for name in ('amount', *NUTRIENTS): + data[name] = str(data[name]) if data[name] is not None else None + return data + + +def _product_data(product): + fields = ('product_name', 'brand', 'barcode', 'image_url', 'package_quantity', + 'serving_size_text', 'serving_amount', 'serving_unit', 'base_unit', + 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', + 'fibre_100', 'sugars_100', 'salt_100', 'source') + data = {name: getattr(product, name) for name in fields} + for name in fields: + if isinstance(data[name], Decimal): + data[name] = str(data[name]) + data['id'] = str(product.api_id) + data['portions'] = [{'label': p.label, 'amount': str(p.amount), 'unit': p.unit, + 'is_default': p.is_default} for p in product.portions.all()] + return data + + +def _inventory_data(item): + return {'id': str(item.api_id), 'product_id': str(item.product.api_id), + 'product_name': item.product.product_name, 'brand': item.product.brand, + 'barcode': item.product.barcode, 'quantity': item.quantity, + 'location': item.location.name, 'category': item.category.name if item.category else None, + 'notes': item.notes, 'opened': item.opened, + 'best_before': item.best_before.isoformat() if item.best_before else None, + 'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()} + + +def _idempotent(request, payload, action): + key = request.headers.get('Idempotency-Key') + if not key: + return action() + if len(key) > 128 or not key.isascii() or any(ord(ch) < 33 or ord(ch) > 126 for ch in key): + return error('invalid_idempotency_key', 'Invalid Idempotency-Key.') + digest = hashlib.sha256(request.path.encode() + b'\0' + request.body).hexdigest() + with transaction.atomic(): + # Lock the token row so concurrent retries serialize on databases with row locking. + PersonalAccessToken.objects.select_for_update().get(pk=request.api_token.pk) + record = ApiIdempotencyRecord.objects.filter(token=request.api_token, key=key).first() + if record: + if not hmac.compare_digest(record.request_hash, digest): + return error('idempotency_conflict', 'This key was used with another request.', 409) + return JsonResponse(record.response, status=200) + response = action() + if response.status_code < 400: + ApiIdempotencyRecord.objects.create(token=request.api_token, key=key, + request_hash=digest, response=json.loads(response.content)) + return response + + +@api_view('food:read', ('GET',)) +def today(request): + day = localdate_for_user(request.api_user) + 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} + totals = {name: str(sum((getattr(e, name) or Decimal('0') for e in entries), Decimal('0'))) + for name in NUTRIENTS} + goals = UserSettings.objects.filter(user=request.api_user).first() + goal_data = {name: str(getattr(goals, name)) if goals and getattr(goals, name) is not None else None + for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g')} + return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, 'goals': goal_data}) + + +@api_view('food:read', ('GET',)) +def products(request): + query = request.GET.get('search', '').strip()[:100] + qs = FoodProduct.objects.filter(owner=request.api_user).prefetch_related('portions').order_by('product_name', 'pk') + if query: + qs = qs.filter(Q(product_name__icontains=query) | Q(brand__icontains=query) | Q(barcode__icontains=query)) + page = _page(request, qs) + page['results'] = [_product_data(p) for p in page['results']] + return JsonResponse(page) + + +def _save_entry(request, data, entry=None): + creating = entry is None + if creating: + entry = FoodLogEntry(user=request.api_user, created_via='api') + allowed = {'date', 'time', 'meal', 'product_id', 'product_name', 'brand', 'barcode', + 'portion_label', 'amount', 'unit', *MANUAL_FIELDS} + unknown = set(data) - allowed + if unknown: + raise ValueError(f'Unknown fields: {", ".join(sorted(unknown))}.') + if 'date' in data or creating: + entry.date = _date(data.get('date'), request.api_user) + if 'time' in data: + entry.time = _time(data['time']) + if 'meal' in data: + if data['meal'] not in MealType.values: + raise ValueError('Invalid meal.') + entry.meal = data['meal'] + if 'amount' in data: + entry.amount = _decimal(data['amount'], 'amount', positive=True) + if 'unit' in data: + if data['unit'] not in Unit.values: + raise ValueError('Invalid unit.') + entry.unit = data['unit'] + if 'portion_label' in data: + entry.portion_label_snapshot = str(data['portion_label']) + if not entry.meal or entry.amount is None or not entry.unit: + raise ValueError('meal, amount, and unit are required.') + if 'product_id' in data: + product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(data['product_id'])).first() + if product is None: + return None, error('product_not_found', 'Food product not found.', 404) + entry.product = product + if entry.product_id: + if entry.unit != entry.product.base_unit: + raise ValueError('Unit must match the product nutrition basis.') + if any(field in data for field in ('product_name', 'brand', 'barcode', *MANUAL_FIELDS)): + raise ValueError('Product entries calculate nutrition from the product.') + apply_product_snapshot(entry, entry.product) + else: + if 'product_name' in data: + entry.product_name_snapshot = str(data['product_name']).strip() + if 'brand' in data: + entry.brand_snapshot = str(data['brand']) + if 'barcode' in data: + entry.barcode_snapshot = str(data['barcode']) + if not entry.product_name_snapshot: + raise ValueError('product_name is required for manual food.') + entry.source = FoodProduct.Source.MANUAL + for name in MANUAL_FIELDS: + if name in data: + setattr(entry, name, _decimal(data[name], name) if data[name] is not None else None) + entry.full_clean() + entry.save() + return entry, None + + +@api_view('food:write', ('POST',)) +def log_create(request): + data = _json(request) + def create(): + entry, failure = _save_entry(request, data) + return failure or JsonResponse(_entry_data(entry), status=201) + return _idempotent(request, data, create) + + +@api_view('food:read', ('GET',)) +def log_detail(request, identifier): + entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).select_related('product').prefetch_related('attachments').first() + return JsonResponse(_entry_data(entry)) if entry else error('entry_not_found', 'Food log entry not found.', 404) + + +@api_view('food:write', ('PATCH', 'DELETE')) +def log_change(request, identifier): + entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).select_related('product').first() + if entry is None: + return error('entry_not_found', 'Food log entry not found.', 404) + if request.method == 'DELETE': + entry.delete() + return JsonResponse({'deleted': True}) + entry, failure = _save_entry(request, _json(request), entry) + return failure or JsonResponse(_entry_data(entry)) + + +@api_view('inventory:read', ('GET',)) +def inventory_list(request): + qs = KitchenInventoryItem.objects.filter(user=request.api_user, archived_at__isnull=True) + query = request.GET.get('search', '').strip()[:100] + if query: + qs = qs.filter(Q(product__product_name__icontains=query) | Q(product__brand__icontains=query) | + Q(product__barcode__icontains=query) | Q(location__name__icontains=query) | + Q(category__name__icontains=query)) + qs = qs.select_related('product', 'location', 'category').order_by('-added_at', '-pk') + page = _page(request, qs) + page['results'] = [_inventory_data(item) for item in page['results']] + return JsonResponse(page) + + +def _save_inventory(request, data, item=None): + if item is None: + item = KitchenInventoryItem(user=request.api_user) + allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before'} + if set(data) - allowed: + raise ValueError('Unknown inventory fields.') + if 'product_id' in data: + product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(data['product_id'])).first() + if product is None: + return None, error('product_not_found', 'Food product not found.', 404) + item.product = product + if 'quantity' in data: + if isinstance(data['quantity'], bool) or not isinstance(data['quantity'], int) or data['quantity'] < 1: + raise ValueError('Quantity must be a positive integer.') + item.quantity = data['quantity'] + if 'location' in data: + name = ' '.join(str(data['location']).split()) + if not name or len(name) > 100: + raise ValueError('Invalid location.') + item.location, _ = InventoryLocation.objects.get_or_create(user=request.api_user, name__iexact=name, defaults={'name': name}) + if 'category' in data: + name = ' '.join(str(data['category'] or '').split()) + if len(name) > 100: + raise ValueError('Invalid category.') + item.category = (InventoryCategory.objects.get_or_create(user=request.api_user, name__iexact=name, + defaults={'name': name})[0] if name else None) + if 'notes' in data: + item.notes = str(data['notes']) + if 'opened' in data: + if not isinstance(data['opened'], bool): + raise ValueError('opened must be a boolean.') + item.opened = data['opened'] + if 'best_before' in data: + item.best_before = _date(data['best_before'], request.api_user) if data['best_before'] else None + if not item.product_id or not item.location_id: + raise ValueError('product_id and location are required.') + item.full_clean() + item.save() + return item, None + + +@api_view('inventory:write', ('POST',)) +def inventory_create(request): + data = _json(request) + def create(): + item, failure = _save_inventory(request, data) + return failure or JsonResponse(_inventory_data(item), status=201) + return _idempotent(request, data, create) + + +@api_view('inventory:read', ('GET',)) +def inventory_detail(request, identifier): + item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first() + return JsonResponse(_inventory_data(item)) if item else error('inventory_item_not_found', 'Inventory item not found.', 404) + + +@api_view('inventory:write', ('PATCH', 'DELETE')) +def inventory_change(request, identifier): + item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first() + if item is None: + return error('inventory_item_not_found', 'Inventory item not found.', 404) + if request.method == 'DELETE': + item.delete() + return JsonResponse({'deleted': True}) + item, failure = _save_inventory(request, _json(request), item) + return failure or JsonResponse(_inventory_data(item)) + + +@api_view('food:write', ('POST',)) +def attachment_create(request, identifier): + entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).first() + if entry is None: + return error('entry_not_found', 'Food log entry not found.', 404) + if int(request.META.get('CONTENT_LENGTH') or 0) > MAX_IMAGE_BYTES + 65536: + return error('image_too_large', 'Image exceeds 5 MB.', 413) + upload = request.FILES.get('image') + if upload is None: + return error('image_required', 'Upload an image field.') + if upload.size > MAX_IMAGE_BYTES: + return error('image_too_large', 'Image exceeds 5 MB.', 413) + try: + image = Image.open(upload) + if image.width * image.height > 25_000_000: + return error('image_too_large', 'Image dimensions are too large.', 413) + image.verify() + image_format = image.format + except (UnidentifiedImageError, OSError, ValueError): + return error('unsupported_image_type', 'Use a valid JPEG, PNG, or WebP image.') + content_types = {'JPEG': 'image/jpeg', 'PNG': 'image/png', 'WEBP': 'image/webp'} + if image_format not in content_types or upload.content_type != content_types[image_format]: + return error('unsupported_image_type', 'Use a valid JPEG, PNG, or WebP image.') + upload.seek(0) + extension = {'JPEG': 'jpg', 'PNG': 'png', 'WEBP': 'webp'}[image_format] + attachment = FoodLogAttachment(log_entry=entry, image=upload, + original_filename=upload.name.rsplit('/', 1)[-1].rsplit('\\', 1)[-1][:255], + content_type=content_types[image_format], file_size=upload.size, + caption=request.POST.get('caption', '')[:255]) + attachment.image.name = f'{secrets.token_hex(16)}.{extension}' + attachment.save() + return JsonResponse(_attachment_data(attachment), status=201) + + +@api_view('food:read', ('GET',)) +def attachment_file(request, identifier): + item = FoodLogAttachment.objects.filter(api_id=identifier, log_entry__user=request.api_user).first() + if item is None: + return error('attachment_not_found', 'Attachment not found.', 404) + response = FileResponse(item.image.open('rb'), content_type=item.content_type) + response['Content-Disposition'] = 'inline' + response['X-Content-Type-Options'] = 'nosniff' + return response + + +@api_view('food:write', ('DELETE',)) +def attachment_delete(request, identifier): + item = FoodLogAttachment.objects.filter(api_id=identifier, log_entry__user=request.api_user).first() + if item is None: + return error('attachment_not_found', 'Attachment not found.', 404) + item.delete() + return JsonResponse({'deleted': True}) + + +@api_view({'GET': 'food:read', 'PATCH': 'food:write', 'DELETE': 'food:write'}, ('GET', 'PATCH', 'DELETE')) +def log_item(request, identifier): + if request.method == 'GET': + return log_detail.__wrapped__(request, identifier) + return log_change.__wrapped__(request, identifier) + + +@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST')) +def inventory_collection(request): + if request.method == 'GET': + return inventory_list.__wrapped__(request) + return inventory_create.__wrapped__(request) + + +@api_view({'GET': 'inventory:read', 'PATCH': 'inventory:write', 'DELETE': 'inventory:write'}, ('GET', 'PATCH', 'DELETE')) +def inventory_item(request, identifier): + if request.method == 'GET': + return inventory_detail.__wrapped__(request, identifier) + return inventory_change.__wrapped__(request, identifier) diff --git a/main/food/api_middleware.py b/main/food/api_middleware.py new file mode 100644 index 0000000..7118c0a --- /dev/null +++ b/main/food/api_middleware.py @@ -0,0 +1,16 @@ +from django.http import JsonResponse + + +class ApiErrorMiddleware: + """Ensure fallback Django errors on API paths remain machine-readable.""" + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + response = self.get_response(request) + if request.path.startswith('/api/v1/') and response.status_code >= 400 and not response.get('Content-Type', '').startswith('application/json'): + code = 'not_found' if response.status_code == 404 else 'server_error' if response.status_code >= 500 else 'request_error' + message = 'Resource not found.' if response.status_code == 404 else 'Request failed.' + return JsonResponse({'error': {'code': code, 'message': message}}, status=response.status_code) + return response diff --git a/main/food/api_schema.py b/main/food/api_schema.py new file mode 100644 index 0000000..18bb4db --- /dev/null +++ b/main/food/api_schema.py @@ -0,0 +1,85 @@ +"""Small public OpenAPI document; no interactive production documentation UI.""" +from django.http import JsonResponse +from django.views.decorators.http import require_GET + + +def operation(summary, scope, request=None, response=None, multipart=False): + result = { + 'summary': summary, + 'security': [{'bearerToken': []}], + 'x-required-scope': scope, + 'responses': { + '200': {'description': 'Success', 'content': {'application/json': {'schema': response or {'type': 'object'}}}}, + '400': {'description': 'Invalid request'}, '401': {'description': 'Invalid, revoked, or expired token'}, + '403': {'description': 'Missing scope'}, '404': {'description': 'Not found'}, + }, + } + if request: + result['requestBody'] = {'required': True, 'content': { + 'multipart/form-data' if multipart else 'application/json': {'schema': request}}} + return result + + +ENTRY = {'type': 'object', 'properties': { + 'meal': {'type': 'string', 'enum': ['breakfast', 'lunch', 'dinner', 'snacks']}, + 'product_id': {'type': 'string', 'format': 'uuid'}, + 'product_name': {'type': 'string'}, 'brand': {'type': 'string'}, 'barcode': {'type': 'string'}, + 'amount': {'type': 'string', 'description': 'Positive decimal'}, + 'unit': {'type': 'string', 'enum': ['g', 'ml']}, + 'date': {'type': 'string', 'format': 'date', 'description': 'Defaults to the user local date'}, + 'time': {'type': 'string', 'format': 'time'}, + 'portion_label': {'type': 'string'}, + **{field: {'type': ['string', 'null'], 'description': 'Decimal nutrition amount'} for field in + ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')}, +}} +INVENTORY = {'type': 'object', 'properties': { + 'product_id': {'type': 'string', 'format': 'uuid'}, 'quantity': {'type': 'integer', 'minimum': 1}, + 'location': {'type': 'string'}, 'category': {'type': 'string'}, 'notes': {'type': 'string'}, + 'opened': {'type': 'boolean'}, 'best_before': {'type': ['string', 'null'], 'format': 'date'}, +}} +UPLOAD = {'type': 'object', 'required': ['image'], 'properties': { + 'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'}, +}} + + +@require_GET +def schema(request): + document = { + 'openapi': '3.1.0', 'info': {'title': 'TaskNest Food and Kitchen API', 'version': '1.0.0'}, + '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/products/': {'get': operation('Search own food products', 'food:read')}, + '/food/log/': {'post': operation('Create food log entry', 'food:write', ENTRY)}, + '/food/log/{id}/': { + 'get': operation('Read own entry', 'food:read'), + 'patch': operation('Update own entry', 'food:write', ENTRY), + 'delete': operation('Delete own entry', 'food:write'), + }, + '/food/log/{id}/attachments/': {'post': operation('Upload image for own entry', 'food:write', UPLOAD, multipart=True)}, + '/food/attachments/{id}/file/': {'get': operation('Download own attachment', 'food:read')}, + '/food/attachments/{id}/': {'delete': operation('Delete own attachment', 'food:write')}, + '/kitchen/items/': { + 'get': operation('Search own inventory', 'inventory:read'), + 'post': operation('Create inventory item', 'inventory:write', INVENTORY), + }, + '/kitchen/items/{id}/': { + 'get': operation('Read own inventory item', 'inventory:read'), + 'patch': operation('Update own inventory item', 'inventory:write', INVENTORY), + 'delete': operation('Delete own inventory item', 'inventory:write'), + }, + }, + } + for path, methods in document['paths'].items(): + if '{id}' in path: + methods['parameters'] = [{'name': 'id', 'in': 'path', 'required': True, + 'schema': {'type': 'string', 'format': 'uuid'}}] + if 'post' in methods: + methods['post']['responses']['201'] = methods['post']['responses'].pop('200') + document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = { + 'description': 'Owned image bytes', + 'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}} + for mime in ('image/jpeg', 'image/png', 'image/webp')}, + } + return JsonResponse(document) diff --git a/main/food/api_urls.py b/main/food/api_urls.py new file mode 100644 index 0000000..9f6a921 --- /dev/null +++ b/main/food/api_urls.py @@ -0,0 +1,15 @@ +from django.urls import path +from . import api, api_schema + +urlpatterns = [ + path('schema/', api_schema.schema), + path('food/today/', api.today), + path('food/products/', api.products), + path('food/log/', api.log_create), + path('food/log//', api.log_item), + path('food/log//attachments/', api.attachment_create), + path('food/attachments//file/', api.attachment_file), + path('food/attachments//', api.attachment_delete), + path('kitchen/items/', api.inventory_collection), + path('kitchen/items//', api.inventory_item), +] diff --git a/main/food/apps.py b/main/food/apps.py index ad58500..a582f7f 100644 --- a/main/food/apps.py +++ b/main/food/apps.py @@ -4,3 +4,6 @@ from django.apps import AppConfig class FoodConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'food' + + def ready(self): + from . import signals # noqa: F401 diff --git a/main/food/migrations/0004_foodlogentry_api_id_foodlogentry_created_via_and_more.py b/main/food/migrations/0004_foodlogentry_api_id_foodlogentry_created_via_and_more.py new file mode 100644 index 0000000..45a2272 --- /dev/null +++ b/main/food/migrations/0004_foodlogentry_api_id_foodlogentry_created_via_and_more.py @@ -0,0 +1,91 @@ +# Generated by Django 6.1.1 on 2026-10-07 12:36 + +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +def backfill_api_ids(apps, schema_editor): + for model_name in ('FoodLogEntry', 'FoodProduct', 'KitchenInventoryItem'): + model = apps.get_model('food', model_name) + for pk in model.objects.filter(api_id__isnull=True).values_list('pk', flat=True).iterator(): + model.objects.filter(pk=pk).update(api_id=uuid.uuid4()) + + +class Migration(migrations.Migration): + + dependencies = [ + ('food', '0003_inventorycategory_inventorylocation_and_more'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='foodlogentry', + name='api_id', + field=models.UUIDField(null=True, editable=False), + ), + migrations.AddField( + model_name='foodlogentry', + name='created_via', + field=models.CharField(default='web', max_length=16), + ), + migrations.AddField( + model_name='foodproduct', + name='api_id', + field=models.UUIDField(null=True, editable=False), + ), + migrations.AddField( + model_name='kitcheninventoryitem', + name='api_id', + field=models.UUIDField(null=True, editable=False), + ), + migrations.RunPython(backfill_api_ids, migrations.RunPython.noop), + migrations.AlterField(model_name='foodlogentry', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + migrations.AlterField(model_name='foodproduct', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + migrations.AlterField(model_name='kitcheninventoryitem', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + migrations.CreateModel( + name='FoodLogAttachment', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('api_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + ('image', models.ImageField(upload_to='food-attachments/%Y/%m/')), + ('original_filename', models.CharField(max_length=255)), + ('content_type', models.CharField(max_length=50)), + ('file_size', models.PositiveIntegerField()), + ('caption', models.CharField(blank=True, max_length=255)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('log_entry', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='food.foodlogentry')), + ], + ), + migrations.CreateModel( + name='PersonalAccessToken', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=100)), + ('prefix', models.CharField(max_length=20, unique=True)), + ('token_hash', models.CharField(max_length=64)), + ('scopes', models.JSONField(default=list)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('last_used_at', models.DateTimeField(blank=True, null=True)), + ('expires_at', models.DateTimeField(blank=True, null=True)), + ('revoked_at', models.DateTimeField(blank=True, null=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='personal_access_tokens', to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='ApiIdempotencyRecord', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('key', models.CharField(max_length=128)), + ('request_hash', models.CharField(max_length=64)), + ('response', models.JSONField()), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('token', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='food.personalaccesstoken')), + ], + options={ + 'constraints': [models.UniqueConstraint(fields=('token', 'key'), name='food_unique_api_idempotency_key')], + }, + ), + ] diff --git a/main/food/models.py b/main/food/models.py index 2abcbc2..9613839 100644 --- a/main/food/models.py +++ b/main/food/models.py @@ -1,3 +1,5 @@ +import uuid + from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator @@ -22,6 +24,7 @@ class MealType(models.TextChoices): class FoodProduct(models.Model): + api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) class Source(models.TextChoices): OPEN_FOOD_FACTS = 'openfoodfacts', 'Open Food Facts' MANUAL = 'manual', 'Manual' @@ -58,6 +61,7 @@ class FoodProduct(models.Model): class FoodLogEntry(models.Model): + api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_log_entries') date = models.DateField(db_index=True) time = models.TimeField(null=True, blank=True) @@ -77,6 +81,7 @@ class FoodLogEntry(models.Model): sugars_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) salt_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) source = models.CharField(max_length=16, choices=FoodProduct.Source.choices, default=FoodProduct.Source.MANUAL) + created_via = models.CharField(max_length=16, default='web') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @@ -156,6 +161,7 @@ class InventoryCategory(models.Model): class KitchenInventoryItem(models.Model): + api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='kitchen_inventory') product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT, related_name='inventory_items') quantity = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)]) @@ -176,3 +182,37 @@ class KitchenInventoryItem(models.Model): raise ValidationError({'location': 'Choose one of your own locations.'}) if self.user_id and self.category_id and self.category.user_id != self.user_id: raise ValidationError({'category': 'Choose one of your own categories.'}) + + +class PersonalAccessToken(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='personal_access_tokens') + name = models.CharField(max_length=100) + prefix = models.CharField(max_length=20, unique=True) + token_hash = models.CharField(max_length=64) + scopes = models.JSONField(default=list) + created_at = models.DateTimeField(auto_now_add=True) + last_used_at = models.DateTimeField(null=True, blank=True) + expires_at = models.DateTimeField(null=True, blank=True) + revoked_at = models.DateTimeField(null=True, blank=True) + + +class FoodLogAttachment(models.Model): + api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) + log_entry = models.ForeignKey(FoodLogEntry, on_delete=models.CASCADE, related_name='attachments') + image = models.ImageField(upload_to='food-attachments/%Y/%m/') + original_filename = models.CharField(max_length=255) + content_type = models.CharField(max_length=50) + file_size = models.PositiveIntegerField() + caption = models.CharField(max_length=255, blank=True) + created_at = models.DateTimeField(auto_now_add=True) + + +class ApiIdempotencyRecord(models.Model): + token = models.ForeignKey(PersonalAccessToken, on_delete=models.CASCADE) + key = models.CharField(max_length=128) + request_hash = models.CharField(max_length=64) + response = models.JSONField() + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + constraints = [models.UniqueConstraint(fields=('token', 'key'), name='food_unique_api_idempotency_key')] diff --git a/main/food/services/logging.py b/main/food/services/logging.py new file mode 100644 index 0000000..6064475 --- /dev/null +++ b/main/food/services/logging.py @@ -0,0 +1,25 @@ +from decimal import Decimal + + +NUTRIENTS = ( + ('energy_kcal_100', 'calories_kcal'), + ('carbohydrates_100', 'carbohydrates_g'), + ('protein_100', 'protein_g'), + ('fat_100', 'fat_g'), + ('fibre_100', 'fibre_g'), + ('sugars_100', 'sugars_g'), + ('salt_100', 'salt_g'), +) + + +def apply_product_snapshot(entry, product): + """Apply the same product snapshot and nutrition calculation for web and API logs.""" + entry.product = product + entry.product_name_snapshot = product.product_name + entry.brand_snapshot = product.brand + entry.barcode_snapshot = product.barcode + entry.source = product.source + factor = entry.amount / Decimal('100') + for source, target in NUTRIENTS: + value = getattr(product, source) + setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None) diff --git a/main/food/signals.py b/main/food/signals.py new file mode 100644 index 0000000..07f2eae --- /dev/null +++ b/main/food/signals.py @@ -0,0 +1,12 @@ +from django.db import transaction +from django.db.models.signals import post_delete +from django.dispatch import receiver + +from .models import FoodLogAttachment + + +@receiver(post_delete, sender=FoodLogAttachment) +def delete_attachment_file(sender, instance, **kwargs): + if instance.image: + storage, name = instance.image.storage, instance.image.name + transaction.on_commit(lambda: storage.delete(name)) diff --git a/main/food/templates/food/tokens.html b/main/food/templates/food/tokens.html new file mode 100644 index 0000000..39e6b2f --- /dev/null +++ b/main/food/templates/food/tokens.html @@ -0,0 +1,34 @@ +{% extends 'planner/base.html' %} +{% block title %}API tokens · Tasknest{% endblock %} +{% block content %} +
+

Personal preferences

+

API tokens

+

Give an app access to your food log and kitchen inventory. Keep tokens private.

+ {% if new_token %} +
+

New token

+

Copy this token now. For security reasons it cannot be shown again.

+
+
+ {% endif %} +
+

Create token

+
{% csrf_token %} + {% for field in form %}{% if field.name == 'scopes' %}
Permissions{{ field }}{{ field.errors }}
{% else %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endif %}{% endfor %} + +
+
+
+

Your tokens

+ {% for token in tokens %} +
+

{{ token.name }}

+

Permissions: {{ token.scopes|join:", " }} · Created: {{ token.created_at|date:"SHORT_DATETIME_FORMAT" }} · Last used: {{ token.last_used_at|date:"SHORT_DATETIME_FORMAT"|default:"Never" }}

+

Status: {% if token.revoked_at %}Revoked{% elif token.expires_at and token.expires_at <= now %}Expired{% else %}Active{% endif %}{% if token.expires_at %} · Expires: {{ token.expires_at|date:"SHORT_DATETIME_FORMAT" }}{% endif %}

+ {% if not token.revoked_at %}
{% csrf_token %}
{% endif %} +
+ {% empty %}

No API tokens yet.

{% endfor %} +
+
+{% endblock %} diff --git a/main/food/test_api.py b/main/food/test_api.py new file mode 100644 index 0000000..426236d --- /dev/null +++ b/main/food/test_api.py @@ -0,0 +1,157 @@ +import hashlib +import io +import json +from datetime import datetime, timedelta, timezone as py_timezone +from decimal import Decimal +from unittest.mock import patch + +from PIL import Image +from django.contrib.auth import get_user_model +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import TestCase, override_settings +from django.utils import timezone + +from planner.models import UserSettings +from .api import create_token +from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken + + +class FoodApiTests(TestCase): + def setUp(self): + self.a = get_user_model().objects.create_user('api-a', password='test') + self.b = get_user_model().objects.create_user('api-b', password='test') + self.product_a = FoodProduct.objects.create(owner=self.a, product_name='Pasta', energy_kcal_100=Decimal('350')) + self.product_b = FoodProduct.objects.create(owner=self.b, product_name='Private food') + self.entry_b = FoodLogEntry.objects.create(user=self.b, date=timezone.localdate(), meal='lunch', + product=self.product_b, product_name_snapshot='Private food', amount=Decimal('100'), unit='g') + self.location_b = InventoryLocation.objects.create(user=self.b, name='Cupboard') + self.item_b = KitchenInventoryItem.objects.create(user=self.b, product=self.product_b, location=self.location_b) + self.token, self.secret = create_token(self.a, 'Test', + ['food:read', 'food:write', 'inventory:read', 'inventory:write']) + + def call(self, method, path, data=None, token=None, **headers): + args = {'HTTP_AUTHORIZATION': f'Bearer {token or self.secret}', **headers} + if data is not None: + args['content_type'] = 'application/json' + data = json.dumps(data) + return getattr(self.client, method)(path, data=data, **args) + + def test_authentication_scopes_and_token_storage(self): + self.assertNotIn(self.secret, self.token.token_hash) + self.assertEqual(self.token.token_hash, hashlib.sha256(self.secret.encode()).hexdigest()) + self.assertEqual(self.call('get', '/api/v1/food/today/').status_code, 200) + self.token.refresh_from_db() + self.assertIsNotNone(self.token.last_used_at) + self.assertEqual(self.call('get', '/api/v1/food/today/', token='bad').status_code, 401) + read_token, read_secret = create_token(self.a, 'Read', ['food:read']) + self.assertEqual(self.call('get', '/api/v1/food/today/', token=read_secret).status_code, 200) + self.assertEqual(self.call('post', '/api/v1/food/log/', {'meal': 'lunch'}, token=read_secret).status_code, 403) + self.assertEqual(self.call('get', '/api/v1/kitchen/items/', token=read_secret).status_code, 403) + read_token.revoked_at = timezone.now() + read_token.save() + self.assertEqual(self.call('get', '/api/v1/food/today/', token=read_secret).status_code, 401) + expired, expired_secret = create_token(self.a, 'Expired', ['food:read'], timezone.now() - timedelta(seconds=1)) + self.assertEqual(self.call('get', '/api/v1/food/today/', token=expired_secret).json()['error']['code'], 'expired_token') + + def test_owner_isolation_and_products(self): + self.assertEqual(self.call('get', '/api/v1/food/today/').json()['meals']['lunch'], []) + result = self.call('get', '/api/v1/food/products/?search=Private') + self.assertEqual(result.json()['results'], []) + self.assertEqual(self.call('get', f'/api/v1/food/log/{self.entry_b.api_id}/').status_code, 404) + self.assertEqual(self.call('patch', f'/api/v1/food/log/{self.entry_b.api_id}/', {'meal': 'dinner'}).status_code, 404) + self.assertEqual(self.call('delete', f'/api/v1/food/log/{self.entry_b.api_id}/').status_code, 404) + self.assertEqual(self.call('post', f'/api/v1/food/log/{self.entry_b.api_id}/attachments/').status_code, 404) + self.assertEqual(self.call('get', f'/api/v1/kitchen/items/{self.item_b.api_id}/').status_code, 404) + self.assertEqual(self.call('delete', f'/api/v1/kitchen/items/{self.item_b.api_id}/').status_code, 404) + self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{self.item_b.api_id}/', {'quantity': 2}).status_code, 404) + result = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '100', 'unit': 'g', + 'product_id': str(self.product_b.api_id)}) + self.assertEqual(result.status_code, 404) + + def test_food_crud_and_idempotency(self): + payload = {'meal': 'dinner', 'amount': '50', 'unit': 'g', 'product_id': str(self.product_a.api_id)} + first = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='meal-1') + self.assertEqual(first.status_code, 201, first.content) + self.assertEqual(first.json()['calories_kcal'], '175.000') + second = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='meal-1') + self.assertEqual(second.status_code, 200) + self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 1) + self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '60'}, + HTTP_IDEMPOTENCY_KEY='meal-1').status_code, 409) + identifier = first.json()['id'] + self.assertEqual(self.call('patch', f'/api/v1/food/log/{identifier}/', {'amount': '100'}).json()['calories_kcal'], '350.000') + self.assertEqual(self.call('get', f'/api/v1/food/log/{identifier}/').status_code, 200) + self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200) + self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '0'}).status_code, 400) + + def test_manual_and_inventory_crud(self): + manual = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g', + 'product_name': 'Homemade satay', 'calories_kcal': '850'}) + self.assertEqual(manual.status_code, 201, manual.content) + self.assertIsNone(manual.json()['product_id']) + self.assertEqual(manual.json()['created_via'], 'api') + self.assertEqual(self.call('get', '/api/v1/food/today/').json()['totals']['calories_kcal'], '850.000') + payload = {'product_id': str(self.product_a.api_id), 'quantity': 2, 'location': 'Cupboard'} + created = self.call('post', '/api/v1/kitchen/items/', payload, HTTP_IDEMPOTENCY_KEY='item-1') + self.assertEqual(created.status_code, 201, created.content) + self.assertEqual(self.call('post', '/api/v1/kitchen/items/', payload, HTTP_IDEMPOTENCY_KEY='item-1').status_code, 200) + identifier = created.json()['id'] + self.assertEqual(self.call('get', '/api/v1/kitchen/items/?search=Pasta').json()['count'], 1) + self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{identifier}/', {'quantity': 3}).json()['quantity'], 3) + self.assertEqual(self.call('delete', f'/api/v1/kitchen/items/{identifier}/').status_code, 200) + + def test_today_uses_user_timezone(self): + UserSettings.objects.create(user=self.a, time_zone='America/Los_Angeles') + 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') + + @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', + 'product_name': 'Soup'}).json() + path = f"/api/v1/food/log/{entry['id']}/attachments/" + bad = SimpleUploadedFile('bad.jpg', b'', content_type='image/jpeg') + response = self.client.post(path, {'image': bad}, HTTP_AUTHORIZATION=f'Bearer {self.secret}') + self.assertEqual(response.status_code, 400) + image = Image.new('RGB', (2, 2), color='red') + stream = io.BytesIO() + image.save(stream, format='PNG') + mismatch = SimpleUploadedFile('wrong.jpg', stream.getvalue(), content_type='image/jpeg') + self.assertEqual(self.client.post(path, {'image': mismatch}, HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 400) + good = SimpleUploadedFile('photo.png', stream.getvalue(), content_type='image/png') + response = self.client.post(path, {'image': good}, HTTP_AUTHORIZATION=f'Bearer {self.secret}') + self.assertEqual(response.status_code, 201, response.content) + for image_format, content_type, filename in [('JPEG', 'image/jpeg', 'photo.jpg'), + ('WEBP', 'image/webp', 'photo.webp')]: + stream = io.BytesIO() + image.save(stream, format=image_format) + upload = SimpleUploadedFile(filename, stream.getvalue(), content_type=content_type) + self.assertEqual(self.client.post(path, {'image': upload}, + HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 201) + huge = SimpleUploadedFile('large.png', b'X' * (5 * 1024 * 1024 + 1), content_type='image/png') + self.assertEqual(self.client.post(path, {'image': huge}, + HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 413) + identifier = response.json()['id'] + _, other_secret = create_token(self.b, 'Other', ['food:read', 'food:write']) + self.assertEqual(self.call('get', f'/api/v1/food/attachments/{identifier}/file/', token=other_secret).status_code, 404) + self.assertEqual(self.call('delete', f'/api/v1/food/attachments/{identifier}/', token=other_secret).status_code, 404) + self.assertEqual(self.call('get', f'/api/v1/food/attachments/{identifier}/file/').status_code, 200) + + def test_token_management_screen_shows_secret_once(self): + self.client.force_login(self.a) + self.assertEqual(self.client.get('/food/settings/tokens/').status_code, 200) + response = self.client.post('/food/settings/tokens/', { + 'name': 'Phone', 'scopes': ['food:read', 'inventory:read']}) + self.assertEqual(response.status_code, 200, response.content[:300]) + self.assertContains(response, 'Copy this token now') + created = PersonalAccessToken.objects.get(user=self.a, name='Phone') + self.assertNotIn(created.token_hash, response.content.decode()) + self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Copy this token now') + self.assertEqual(self.client.post(f'/food/settings/tokens/{created.pk}/revoke/').status_code, 302) + created.refresh_from_db() + self.assertIsNotNone(created.revoked_at) + + def test_api_fallback_errors_are_json(self): + response = self.call('get', '/api/v1/does-not-exist/') + self.assertEqual(response.status_code, 404) + self.assertEqual(response['Content-Type'], 'application/json') diff --git a/main/food/token_views.py b/main/food/token_views.py new file mode 100644 index 0000000..4cf99d5 --- /dev/null +++ b/main/food/token_views.py @@ -0,0 +1,58 @@ +from datetime import datetime, time, timedelta + +from django import forms +from django.contrib.auth.decorators import login_required +from django.shortcuts import get_object_or_404, redirect, render +from django.utils import timezone +from django.views.decorators.http import require_http_methods, require_POST +from django.views.decorators.cache import never_cache + +from planner.timezones import timezone_for_user +from .api import SCOPES, create_token +from .models import PersonalAccessToken + + +class TokenForm(forms.Form): + name = forms.CharField(max_length=100, label='Name') + scopes = forms.MultipleChoiceField(choices=[(scope, scope) for scope in sorted(SCOPES)], + widget=forms.CheckboxSelectMultiple, label='Permissions') + expires_on = forms.DateField(required=False, widget=forms.DateInput(attrs={'type': 'date'}), + label='Expiry date (optional)') + + def __init__(self, *args, user=None, **kwargs): + super().__init__(*args, **kwargs) + self.user = user + + def clean_expires_on(self): + value = self.cleaned_data['expires_on'] + if value and value <= timezone.localdate(timezone=timezone_for_user(self.user)): + raise forms.ValidationError('Choose a future date.') + return value + + +@login_required +@never_cache +@require_http_methods(['GET', 'POST']) +def tokens(request): + form = TokenForm(request.POST or None, user=request.user) + new_token = None + if request.method == 'POST' and form.is_valid(): + expiry = form.cleaned_data['expires_on'] + expires_at = timezone.make_aware(datetime.combine(expiry + timedelta(days=1), time.min), timezone_for_user(request.user)) if expiry else None + _, new_token = create_token(request.user, form.cleaned_data['name'], form.cleaned_data['scopes'], expires_at) + form = TokenForm(user=request.user) + return render(request, 'food/tokens.html', { + 'form': form, 'new_token': new_token, + 'tokens': PersonalAccessToken.objects.filter(user=request.user).order_by('-created_at'), + 'now': timezone.now(), + }) + + +@login_required +@require_POST +def revoke_token(request, pk): + token = get_object_or_404(PersonalAccessToken, user=request.user, pk=pk) + if token.revoked_at is None: + token.revoked_at = timezone.now() + token.save(update_fields=['revoked_at']) + return redirect('food:tokens') diff --git a/main/food/urls.py b/main/food/urls.py index 5abb825..576ab75 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -1,10 +1,12 @@ from django.urls import path -from . import views, inventory +from . import views, inventory, token_views app_name = 'food' urlpatterns = [ + path('settings/tokens/', token_views.tokens, name='tokens'), + path('settings/tokens//revoke/', token_views.revoke_token, name='token-revoke'), path('inventory/', inventory.overview, name='inventory'), path('inventory/add/', inventory.add, name='inventory-add'), path('inventory/lookup/', inventory.lookup, name='inventory-lookup'), diff --git a/main/food/views.py b/main/food/views.py index bda6920..6098cdd 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -21,6 +21,7 @@ from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealT from .services.diary import diary_context, selected_date from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search from .services.products import local_products +from .services.logging import apply_product_snapshot from planner.timezones import localdate_for_user @@ -120,19 +121,7 @@ def _save_entry(form, user, day, product): entry = form.save(commit=False) entry.user = user entry.date = day - entry.product = product - entry.product_name_snapshot = product.product_name - entry.brand_snapshot = product.brand - entry.barcode_snapshot = product.barcode - entry.source = product.source - factor = entry.amount / Decimal('100') - for source, target in ( - ('energy_kcal_100', 'calories_kcal'), ('carbohydrates_100', 'carbohydrates_g'), - ('protein_100', 'protein_g'), ('fat_100', 'fat_g'), ('fibre_100', 'fibre_g'), - ('sugars_100', 'sugars_g'), ('salt_100', 'salt_g'), - ): - value = getattr(product, source) - setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None) + apply_product_snapshot(entry, product) entry.full_clean() entry.save() _save_custom_portion(form, user, product, entry) diff --git a/main/frontend/src/styles/main.scss b/main/frontend/src/styles/main.scss index 885cc31..9a7aa9a 100644 --- a/main/frontend/src/styles/main.scss +++ b/main/frontend/src/styles/main.scss @@ -583,3 +583,8 @@ body[data-theme="dark"] .gitea-activity__summary strong { color: #9bd5ae; } body[data-theme="dark"] .gitea-activity__cell--0 { background: #303a33; } body[data-theme="dark"] .gitea-activity__cell--future { background: transparent; } @media (max-width: 560px) { .gitea-activity { padding: 22px; }.gitea-activity__header { align-items: start; }.gitea-activity__header h2 { font-size: 1.45rem; } } +.token-scope-field { border: 0; padding: 0; margin: 0 0 16px; } +.token-scope-field legend { margin-bottom: 8px; font-size: .82rem; font-weight: 700; } +.token-scope-field > div { display: grid; gap: 6px; } +.token-scope-field label { display: flex; align-items: center; gap: 10px; font-size: .88rem; font-weight: 600; cursor: pointer; } +.token-scope-field input[type='checkbox'] { width: 16px; height: 16px; margin: 0; flex: none; } diff --git a/main/planner/templates/planner/user_settings.html b/main/planner/templates/planner/user_settings.html index 44cc6b4..4290b50 100644 --- a/main/planner/templates/planner/user_settings.html +++ b/main/planner/templates/planner/user_settings.html @@ -9,6 +9,7 @@

Sick Day Mode

Temporarily defer routine work while you recover.

{% csrf_token %}{% for field in sick_form %}{% if field.name == 'enabled' %}
{{ field.errors }}
{% else %}
{{ field.label_tag }}{{ field }}{% if field.help_text %}{{ field.help_text }}{% endif %}{{ field.errors }}
{% endif %}{% endfor %}

Hydration

Set your daily water goal.

{% csrf_token %}{% for field in hydration_goal_form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}

Food

Set optional daily nutrition goals. Exercise calories do not change these goals.

{% csrf_token %}{% for field in food_goal_form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
+

API access

Create scoped tokens for apps that need access to your food log or kitchen inventory.

Manage API tokens

Notifications / ntfy

Enter your private topic URL, test it, then enable notifications.

diff --git a/main/requirements.txt b/main/requirements.txt index 23d6153..b04646a 100644 --- a/main/requirements.txt +++ b/main/requirements.txt @@ -1,5 +1,6 @@ asarPy==1.0.1 asgiref==3.12.1 Django==6.1.1 +Pillow==12.3.0 h3==4.5.0 sqlparse==0.6.0 diff --git a/main/tasksnest/settings.py b/main/tasksnest/settings.py index 3163cf2..895586a 100644 --- a/main/tasksnest/settings.py +++ b/main/tasksnest/settings.py @@ -46,6 +46,7 @@ INSTALLED_APPS = [ ] MIDDLEWARE = [ + 'food.api_middleware.ApiErrorMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', @@ -123,6 +124,7 @@ USE_TZ = True # https://docs.djangoproject.com/en/6.1/howto/static-files/ STATIC_URL = 'static/' +MEDIA_ROOT = BASE_DIR / 'private_media' # Vite writes production assets and its manifest here. In development templates # load modules from the Vite server configured by VITE_DEV_SERVER. diff --git a/main/tasksnest/urls.py b/main/tasksnest/urls.py index 3c54b19..84f4d76 100644 --- a/main/tasksnest/urls.py +++ b/main/tasksnest/urls.py @@ -18,6 +18,7 @@ from django.contrib import admin from django.urls import include, path urlpatterns = [ + path('api/v1/', include('food.api_urls')), path('admin/', admin.site.urls), path('food/', include('food.urls', namespace='food')), path('', include('planner.urls')),