import logging from django.conf import settings from django.core.cache import cache from django.http import HttpResponse, HttpResponseForbidden, JsonResponse from django.utils import timezone from .demo_policy import is_demo_user logger = logging.getLogger(__name__) class DemoAccountPolicyMiddleware: """Deny privileged and external actions even if a link is hidden in the UI.""" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path_info == '/o/token/' and request.method == 'POST': from oauth2_provider.models import get_grant_model, get_refresh_token_model grant_type = request.POST.get('grant_type') credential = request.POST.get('refresh_token' if grant_type == 'refresh_token' else 'code') model = (get_refresh_token_model() if grant_type == 'refresh_token' else get_grant_model() if grant_type == 'authorization_code' else None) field = 'token' if grant_type == 'refresh_token' else 'code' if model and credential and model.objects.filter( **{field: credential, 'user__planner_settings__is_demo': True}).exists(): logger.warning('Denied demo OAuth token exchange') return JsonResponse({'error': 'access_denied'}, status=403) if is_demo_user(request.user): path = request.path_info if request.method not in {'GET', 'HEAD', 'OPTIONS'}: if request.META.get('CONTENT_LENGTH', '').isdigit() and int(request.META['CONTENT_LENGTH']) > 1024 * 1024: return HttpResponse('Demo requests are limited to 1 MB.', status=413) limits = ( (f'demo:writes:minute:{request.user.pk}', 60, getattr(settings, 'DEMO_MUTATIONS_PER_MINUTE', 60)), (f'demo:writes:day:{request.user.pk}:{timezone.localdate().isoformat()}', 86400, getattr(settings, 'DEMO_MUTATIONS_PER_DAY', 500)), ) over_limit = False for key, lifetime, maximum in limits: cache.add(key, 0, lifetime) try: count = cache.incr(key) except ValueError: cache.set(key, 1, lifetime) count = 1 over_limit |= count > maximum if over_limit: logger.warning('Demo account write limit reached: user_id=%s', request.user.pk) response = HttpResponse('Demo request limit reached. Try again in a minute.', status=429) response['Retry-After'] = '60' return response forbidden = (path.startswith(('/o/', '/admin/', '/food/settings/tokens/')) or path == '/settings/notifications/ntfy/test/' or (request.method == 'POST' and path in { '/food/search/openfoodfacts/', '/food/import/openfoodfacts/', '/food/inventory/search/openfoodfacts/', '/food/inventory/lookup/', }) or (request.method == 'POST' and path.startswith('/recipes/') and not (path == '/recipes/match/reset/' or (path.startswith('/recipes/match/') and path.endswith('/select/')) or path.startswith('/recipes/cook-later/'))) or (path == '/settings/' and request.method == 'POST' and request.POST.get('section') in {'ntfy', 'location'})) if forbidden: logger.warning('Denied demo account action: user_id=%s path=%s', request.user.pk, path) return HttpResponseForbidden('This action is unavailable in the demo account.') return self.get_response(request)