Files
Django_TasksApp/main/food/api.py
T

498 lines
22 KiB
Python

"""Token-authenticated, owner-scoped HTTP API for future MCP adapters."""
import hashlib
import hmac
import json
import secrets
from django.conf import settings
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 and 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, digest_override=None):
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 = digest_override or 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(None, ('GET',))
def whoami(request):
subject = hashlib.sha256(f'{request.api_user.pk}:{settings.SECRET_KEY}'.encode()).hexdigest()[:24]
return JsonResponse({'subject': subject, 'scopes': request.api_token.scopes,
'expires_at': request.api_token.expires_at.isoformat() if request.api_token.expires_at else None})
@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}'
def create():
attachment.save()
return JsonResponse(_attachment_data(attachment), status=201)
digest = hashlib.sha256(str(entry.api_id).encode() + b'\0' + upload.read() +
b'\0' + attachment.caption.encode()).hexdigest()
upload.seek(0)
return _idempotent(request, None, create, digest_override=digest)
@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)