Fix OAuth page
This commit is contained in:
+1
-1
@@ -32,7 +32,7 @@ from .services.product_resolution import (create_manual, external_matches, impor
|
||||
local_matches, match_data)
|
||||
from .services.inventory_consumption import FACTORS, StockError, consume as consume_stock, preview as preview_stock, stock as stock_packages, undo as undo_stock
|
||||
|
||||
SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'}
|
||||
SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal: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
|
||||
|
||||
+41
-1
@@ -104,15 +104,55 @@ RECIPE_ANALYSIS = {'type': 'object', 'properties': {
|
||||
'include_optional': {'type': 'boolean'},
|
||||
'substitutions': {'type': 'object', 'additionalProperties': {'type': 'string'}},
|
||||
}}
|
||||
STRESS = {'type': 'object', 'required': ['score'], 'properties': {
|
||||
'score': {'type': 'integer', 'minimum': 0, 'maximum': 10},
|
||||
'recorded_at': {'type': 'string', 'format': 'date-time', 'description': 'Defaults to now; naive times use the user time zone'},
|
||||
'timing': {'type': 'string', 'enum': ['anytime', 'before_sleep', 'after_waking']},
|
||||
'note': {'type': 'string', 'maxLength': 2000},
|
||||
'tags': {'type': 'array', 'maxItems': 12, 'items': {'type': 'string', 'maxLength': 40}},
|
||||
'symptoms': {'type': 'array', 'items': {'type': 'string', 'enum': ['tension', 'headache', 'fatigue', 'restlessness']}},
|
||||
}}
|
||||
DREAM = {'type': 'object', 'required': ['wake_up_date', 'title', 'narrative'], 'properties': {
|
||||
'wake_up_date': {'type': 'string', 'format': 'date', 'description': 'Local date on waking; matches Health > Sleep'},
|
||||
'dreamed_at': {'type': ['string', 'null'], 'format': 'date-time'},
|
||||
'title': {'type': 'string', 'maxLength': 160},
|
||||
'narrative': {'type': 'string', 'maxLength': 20000},
|
||||
'interpretation': {'type': 'string', 'maxLength': 4000},
|
||||
'tags': {'type': 'array', 'maxItems': 12, 'items': {'type': 'string'}},
|
||||
'emotions': {'type': 'array', 'maxItems': 12, 'items': {'type': 'string'}},
|
||||
'vividness': {'type': ['integer', 'null'], 'minimum': 0, 'maximum': 10},
|
||||
'is_nightmare': {'type': 'boolean'},
|
||||
'after_waking_notes': {'type': 'string', 'maxLength': 4000},
|
||||
'append_narrative': {'type': 'string', 'description': 'PATCH only; requires Idempotency-Key'},
|
||||
'append_after_waking_notes': {'type': 'string', 'description': 'PATCH only; requires Idempotency-Key'},
|
||||
}}
|
||||
|
||||
|
||||
@require_GET
|
||||
def schema(request):
|
||||
document = {
|
||||
'openapi': '3.1.0', 'info': {'title': 'TaskNest Food and Kitchen API', 'version': '1.0.0'},
|
||||
'openapi': '3.1.0', 'info': {'title': 'TaskNest API', 'version': '1.0.0'},
|
||||
'servers': [{'url': '/api/v1'}],
|
||||
'components': {'securitySchemes': {'bearerToken': {'type': 'http', 'scheme': 'bearer'}}},
|
||||
'paths': {
|
||||
'/dreams/': {
|
||||
'get': operation('Search own dreams by keywords, tags, and wake-up date', 'journal:read'),
|
||||
'post': operation('Create own dream with optional Idempotency-Key', 'journal:write', DREAM),
|
||||
},
|
||||
'/dreams/{id}/': {
|
||||
'get': operation('Read own dream', 'journal:read'),
|
||||
'patch': operation('Update or append to own dream; append requires Idempotency-Key', 'journal:write', DREAM),
|
||||
'delete': operation('Delete own dream', 'journal:write'),
|
||||
},
|
||||
'/stress/': {
|
||||
'get': operation('Search own stress check-ins by text, date, and timing', 'journal:read'),
|
||||
'post': operation('Create own stress check-in with optional Idempotency-Key', 'journal:write', STRESS),
|
||||
},
|
||||
'/stress/{id}/': {
|
||||
'get': operation('Read own stress check-in', 'journal:read'),
|
||||
'patch': operation('Update own stress check-in', 'journal:write', STRESS),
|
||||
'delete': operation('Delete own stress check-in', 'journal:write'),
|
||||
},
|
||||
'/food/today/': {'get': operation('Food log for an optional local calendar date, defaulting to today', 'food:read')},
|
||||
'/food/products/': {'get': operation('Search own food products', 'food:read')},
|
||||
'/food/products/lookup/': {'get': operation('Look up local and optional Open Food Facts product candidates', 'food:read')},
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
from django.urls import path
|
||||
from . import api, api_schema
|
||||
from recipes import api as recipe_api
|
||||
from stress import api as stress_api
|
||||
from dreams import api as dream_api
|
||||
|
||||
urlpatterns = [
|
||||
path('auth/whoami/', api.whoami),
|
||||
path('stress/', stress_api.collection),
|
||||
path('stress/<uuid:identifier>/', stress_api.item),
|
||||
path('dreams/', dream_api.collection),
|
||||
path('dreams/<uuid:identifier>/', dream_api.item),
|
||||
path('schema/', api_schema.schema),
|
||||
path('food/today/', api.today),
|
||||
path('food/products/', api.products),
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Offer an explicit journal-scope upgrade for existing MCP OAuth clients."""
|
||||
|
||||
from django.conf import settings
|
||||
from django.core import signing
|
||||
from oauth2_provider.views import AuthorizationView
|
||||
|
||||
|
||||
JOURNAL_SCOPES = ('journal:read', 'journal:write')
|
||||
OFFER_SALT = 'tasknest-mcp-journal-consent'
|
||||
CHATGPT_CLIENT_ID = 'https://chatgpt.com/oauth/client.json'
|
||||
|
||||
|
||||
def is_mcp_consent(client_id, resource):
|
||||
"""ChatGPT can omit the resource parameter on a reconnect."""
|
||||
return (resource.strip() == settings.TASKNEST_MCP_PUBLIC_URL.rstrip('/')
|
||||
or client_id == CHATGPT_CLIENT_ID)
|
||||
|
||||
|
||||
class JournalAuthorizationView(AuthorizationView):
|
||||
template_name = 'oauth2_provider/authorize_tasknest.html'
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
form = context.get('form')
|
||||
if not form or not context.get('application'):
|
||||
return context
|
||||
requested = form['scope'].value() or ''
|
||||
resource = form['resource'].value() or ''
|
||||
if (is_mcp_consent(form['client_id'].value(), resource)
|
||||
and not set(JOURNAL_SCOPES).issubset(requested.split())):
|
||||
context['offer_journal_scopes'] = True
|
||||
context['journal_scope_offer'] = signing.dumps({
|
||||
'scope': requested, 'client_id': form['client_id'].value(),
|
||||
'resource': resource,
|
||||
}, salt=OFFER_SALT)
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
if form.cleaned_data.get('allow') and self.request.POST.get('grant_journal_scopes') == 'on':
|
||||
try:
|
||||
offer = signing.loads(self.request.POST.get('journal_scope_offer', ''),
|
||||
salt=OFFER_SALT, max_age=600)
|
||||
except signing.BadSignature:
|
||||
form.add_error(None, 'Journal permission offer expired. Please reconnect and try again.')
|
||||
return self.form_invalid(form)
|
||||
scope = form.cleaned_data['scope']
|
||||
if (offer != {'scope': scope, 'client_id': form.cleaned_data['client_id'],
|
||||
'resource': form.cleaned_data.get('resource', '')}
|
||||
or not is_mcp_consent(offer['client_id'], offer['resource'])):
|
||||
form.add_error(None, 'Journal permission offer changed. Please reconnect and try again.')
|
||||
return self.form_invalid(form)
|
||||
form.cleaned_data['scope'] = ' '.join(dict.fromkeys([*scope.split(), *JOURNAL_SCOPES]))
|
||||
return super().form_valid(form)
|
||||
@@ -1,5 +1,5 @@
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date
|
||||
@@ -11,6 +11,26 @@ from planner.timezones import localdate_for_user
|
||||
|
||||
|
||||
ZERO = Decimal('0')
|
||||
|
||||
|
||||
def ring_progress(amount, goal):
|
||||
"""Presentation values for a two-lap ring; totals and goals stay untouched.
|
||||
|
||||
After two laps, the inner arc shows progress in the current lap. The
|
||||
accompanying text states how many full laps have already been completed.
|
||||
"""
|
||||
progress = max(ZERO, amount * 100 / goal)
|
||||
whole_laps = int(progress // 100)
|
||||
current_lap = progress % 100
|
||||
if progress and current_lap == 0:
|
||||
current_lap = Decimal('100')
|
||||
return {
|
||||
'percent': int(progress.quantize(Decimal('1'), rounding=ROUND_HALF_UP)),
|
||||
'base_lap': format(min(progress, Decimal('100')), '.2f'),
|
||||
'extra_lap': format(current_lap if progress > 100 else ZERO, '.2f'),
|
||||
'full_laps': whole_laps,
|
||||
'current_lap': current_lap,
|
||||
}
|
||||
NUTRIENT_NAMES = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
|
||||
NUTRIENT_LABELS = {'calories_kcal': 'calories', 'carbohydrates_g': 'carbs',
|
||||
'protein_g': 'protein', 'fat_g': 'fat', 'fibre_g': 'fibre',
|
||||
@@ -72,10 +92,15 @@ def diary_context(user, day, language='en'):
|
||||
):
|
||||
eaten = totals[name]
|
||||
is_incomplete = incomplete[name]
|
||||
ring = ring_progress(eaten, goal) if goal and (known_counts[name] or not entries) else None
|
||||
macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language),
|
||||
'eaten': eaten if known_counts[name] or not entries else None, 'goal': goal,
|
||||
'remaining': goal - eaten if goal is not None and not is_incomplete else None,
|
||||
'percent': min(100, int(eaten * 100 / goal)) if goal and (known_counts[name] or not entries) else None,
|
||||
'percent': ring['percent'] if ring else None,
|
||||
'base_lap': ring['base_lap'] if ring else ZERO,
|
||||
'extra_lap': ring['extra_lap'] if ring else ZERO,
|
||||
'full_laps': ring['full_laps'] if ring else 0,
|
||||
'current_lap': ring['current_lap'] if ring else ZERO,
|
||||
'color': color, 'incomplete': is_incomplete})
|
||||
calorie_goal = goals.daily_calorie_goal
|
||||
calories = totals['calories_kcal']
|
||||
|
||||
@@ -93,3 +93,15 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
|
||||
@media(max-width:600px){.inventory-page>.food-heading{align-items:flex-start;flex-wrap:wrap}.inventory-heading-actions{justify-content:flex-start;width:100%}}
|
||||
.food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
||||
.food-quantity-controls{display:flex;align-items:center;gap:.35rem;white-space:nowrap}.food-quantity-controls .food-quantity{min-width:2.5ch;text-align:center}.food-quantity-controls .food-quantity-form{margin:0}
|
||||
|
||||
/* Shared ring geometry: the outer lap stays complete beneath excess progress. */
|
||||
.food-ring{position:relative;display:grid;place-items:center;background:none}
|
||||
.food-ring svg{display:block;width:100%;height:100%;transform:rotate(-90deg);overflow:visible}
|
||||
.food-ring circle{fill:none;stroke-width:5}
|
||||
.food-ring__track{stroke:var(--food-ring-track)}
|
||||
.food-ring__base{stroke:var(--accent)}
|
||||
.food-ring__extra{stroke:var(--accent);stroke-width:4;opacity:.8}
|
||||
.food-ring>span{position:absolute;inset:0;display:grid;place-items:center;width:auto;height:auto;background:none;border-radius:0;font-variant-numeric:tabular-nums;font-size:.7rem;letter-spacing:-.035em}
|
||||
.food-ring-laps{font-size:.7rem}
|
||||
.food-macro--pink{--accent:#d45b8b}
|
||||
.food-macro .food-ring{--accent:inherit}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{% load static %}
|
||||
{% block title %}Food · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261017-nutrition">
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261018-rings">
|
||||
{% include 'food/partials/diary_content.html' %}
|
||||
<script defer src="{% static 'food/quantity.js' %}?v=20261015"></script>
|
||||
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261015-quantity"></script>
|
||||
|
||||
@@ -25,10 +25,11 @@
|
||||
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">
|
||||
{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
|
||||
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
|
||||
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; total incomplete{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
|
||||
{% include 'food/partials/progress_ring.html' with ring=macro %}
|
||||
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3>
|
||||
<p>{% if macro.eaten is None %}Known amount unavailable{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}</p>
|
||||
{% if macro.incomplete %}<p><span class="food-warning-mark" aria-hidden="true">!</span> {% if macro.goal is not None %}Remaining unknown{% else %}Nutrition incomplete · No target{% endif %}</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}
|
||||
{% if macro.percent > 200 %}<p class="food-ring-laps">{{ macro.full_laps }} full laps{% if macro.current_lap < 100 %} + {{ macro.current_lap|floatformat:0 }}% of next{% endif %}</p>{% endif %}
|
||||
</div>
|
||||
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
|
||||
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<div class="food-ring" role="img" aria-label="{{ ring.label }}: {% if ring.percent is not None %}{{ ring.percent }}% of target; {% if ring.incomplete %}at least {% endif %}{{ ring.eaten|floatformat:1 }} g of {{ ring.goal|floatformat:1 }} g{% if ring.incomplete %}; total incomplete, remaining unknown{% elif ring.remaining < 0 %}; {{ ring.remaining|floatformat:1|cut:'-' }} g over target{% else %}; {{ ring.remaining|floatformat:1 }} g remaining{% endif %}{% if ring.percent > 200 %}; {{ ring.full_laps }} full laps{% endif %}{% else %}progress unknown{% endif %}">
|
||||
<svg viewBox="0 0 54 54" aria-hidden="true" focusable="false">
|
||||
<circle class="food-ring__track" cx="27" cy="27" r="22" pathLength="100" />
|
||||
{% if ring.percent is not None %}
|
||||
<circle class="food-ring__base" cx="27" cy="27" r="22" pathLength="100" stroke-dasharray="{{ ring.base_lap }} 100" />
|
||||
{% if ring.percent > 100 %}<circle class="food-ring__extra" cx="27" cy="27" r="15" pathLength="100" stroke-dasharray="{{ ring.extra_lap }} 100" />{% endif %}
|
||||
{% endif %}
|
||||
</svg>
|
||||
<span aria-hidden="true">{% if ring.percent is not None %}{{ ring.percent }}%{% else %}—{% endif %}</span>
|
||||
</div>
|
||||
@@ -4,7 +4,7 @@
|
||||
<section class="settings-page">
|
||||
<p class="eyebrow">Personal preferences</p>
|
||||
<h1>API tokens</h1>
|
||||
<p>Give an app access to your food log and kitchen inventory. Keep tokens private.</p>
|
||||
<p>Give an app access to your food log, kitchen inventory, or private stress and dream journals. Keep tokens private.</p>
|
||||
{% if new_token %}
|
||||
<section class="settings-card" role="status">
|
||||
<h2>New token</h2>
|
||||
@@ -32,7 +32,7 @@
|
||||
</section>
|
||||
<section class="settings-card mcp-helper" data-mcp-helper>
|
||||
<h2>Connect an AI assistant</h2>
|
||||
<p>Compatible assistants can use your Food and Kitchen data through MCP. Access is limited to the permissions you grant.</p>
|
||||
<p>Compatible assistants can use your Food, Kitchen, Stress Journal, and Dream Journal data through MCP. Access is limited to the permissions you grant.</p>
|
||||
<div class="form-field">
|
||||
<label for="mcp-server-url">MCP server URL</label>
|
||||
<input id="mcp-server-url" type="url" readonly data-mcp-url>
|
||||
@@ -49,7 +49,7 @@
|
||||
<p data-mcp-status role="status" aria-live="polite"></p>
|
||||
<p class="mcp-helper__hint">Treat this token like a password. TaskNest does not save the token you paste here. You can revoke access from your API tokens.</p>
|
||||
<div class="mcp-helper__clients">
|
||||
<section><h3>ChatGPT</h3><p>Add a custom MCP app in ChatGPT and enter the MCP server URL. Select OAuth authentication, then sign in to TaskNest and approve the requested permissions. ChatGPT does not use the pasted token field.</p></section>
|
||||
<section><h3>ChatGPT</h3><p>Add a custom MCP app in ChatGPT and enter the MCP server URL. Select OAuth authentication, then sign in to TaskNest and review the requested permissions. For dream and stress tools, select the optional private journal permission on the TaskNest consent page. If reconnecting skips consent, revoke the old ChatGPT authorization above and reconnect once. ChatGPT does not use the pasted token field.</p></section>
|
||||
<section><h3>Open WebUI</h3><p>In Admin Settings → Integrations → External Tool Servers, add an MCP (Streamable HTTP) connection. Use the URL above, choose Bearer authentication, and paste your token into its Key field.</p></section>
|
||||
<section><h3>Generic MCP client</h3><p>Use Streamable HTTP at the URL above and send <code>Authorization: Bearer <your token></code> as a separate header. Never put the token in the URL.</p></section>
|
||||
</div>
|
||||
|
||||
+3
-1
@@ -9,11 +9,13 @@
|
||||
{% else %}
|
||||
<section class="settings-card">
|
||||
<h2>Allow {{ application.name }}?</h2>
|
||||
<p>This assistant is requesting access to your TaskNest account. It can only use the permissions listed here.</p>
|
||||
<p>Allow access grants the permissions listed here{% if offer_journal_scopes %} and any optional permissions you select below{% endif %}.</p>
|
||||
<ul>{% for scope in scopes_descriptions %}<li>{{ scope }}</li>{% endfor %}</ul>
|
||||
{% if offer_journal_scopes %}<p>This connection did not request the newer private journal permissions. You can explicitly add them here for dream and stress tools.</p>{% endif %}
|
||||
<form method="post" id="authorizationForm">
|
||||
{% csrf_token %}
|
||||
{% for field in form %}{% if field.is_hidden %}{{ field }}{% endif %}{% endfor %}
|
||||
{% if offer_journal_scopes %}<input type="hidden" name="journal_scope_offer" value="{{ journal_scope_offer }}"><label class="checkbox-field"><input type="checkbox" name="grant_journal_scopes" value="on"> Also allow reading and changing my private dream and stress journals</label>{% endif %}
|
||||
{{ form.non_field_errors }}
|
||||
<button class="button" type="submit" name="allow" value="Authorize">Allow access</button>
|
||||
<button class="button button--secondary" type="submit" value="Cancel">Cancel</button>
|
||||
+137
-1
@@ -4,14 +4,150 @@ from unittest.mock import patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, override_settings
|
||||
from oauth2_provider.models import Application, AccessToken
|
||||
|
||||
from .cimd import CompatibleCIMDFetcher
|
||||
from .models import PersonalAccessToken
|
||||
from .oauth_authorize import CHATGPT_CLIENT_ID
|
||||
|
||||
|
||||
class McpOAuthTests(TestCase):
|
||||
def test_chatgpt_reconnect_without_resource_offers_journal_access(self):
|
||||
user = get_user_model().objects.create_user('chatgpt-journal-reconnect', password='test')
|
||||
Application.objects.create(user=user, name='ChatGPT', client_id=CHATGPT_CLIENT_ID,
|
||||
client_type=Application.CLIENT_PUBLIC,
|
||||
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='https://chatgpt.com/connector_platform_oauth_redirect')
|
||||
self.client.force_login(user)
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
consent = self.client.get('/o/authorize/', {
|
||||
'response_type': 'code', 'client_id': CHATGPT_CLIENT_ID,
|
||||
'redirect_uri': 'https://chatgpt.com/connector_platform_oauth_redirect',
|
||||
'scope': 'food:read food:write inventory:read inventory:write',
|
||||
'state': 'chatgpt-reconnect', 'code_challenge': challenge,
|
||||
'code_challenge_method': 'S256',
|
||||
}, HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
||||
self.assertEqual(consent.status_code, 200)
|
||||
self.assertContains(consent, 'grant_journal_scopes')
|
||||
form = consent.context['form']
|
||||
self.assertFalse(form['resource'].value())
|
||||
payload = {field.name: field.value() for field in form
|
||||
if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload.update(allow='Authorize', grant_journal_scopes='on',
|
||||
journal_scope_offer=consent.context['journal_scope_offer'])
|
||||
redirect = self.client.post('/o/authorize/', payload,
|
||||
HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
||||
self.assertEqual(redirect.status_code, 302, redirect.content[:200])
|
||||
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
||||
token = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
|
||||
'redirect_uri': 'https://chatgpt.com/connector_platform_oauth_redirect',
|
||||
'client_id': CHATGPT_CLIENT_ID, 'code_verifier': verifier},
|
||||
HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
||||
self.assertEqual(token.status_code, 200, token.content[:200])
|
||||
self.assertEqual(set(token.json()['scope'].split()),
|
||||
{'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'})
|
||||
|
||||
@override_settings(TASKNEST_MCP_PUBLIC_URL='http://localhost:8002/mcp')
|
||||
def test_existing_client_can_explicitly_add_journal_scopes_on_reconnect(self):
|
||||
user = get_user_model().objects.create_user('journal-upgrade', password='test')
|
||||
application = Application.objects.create(user=user, name='Existing assistant',
|
||||
client_type=Application.CLIENT_PUBLIC,
|
||||
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='http://localhost:9876/callback')
|
||||
self.client.force_login(user)
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
old_scopes = 'food:read food:write inventory:read inventory:write'
|
||||
metadata = self.client.get('/.well-known/oauth-authorization-server', HTTP_HOST='localhost').json()
|
||||
self.assertTrue({'journal:read', 'journal:write'} <= set(metadata['scopes_supported']))
|
||||
|
||||
def connect(state, add_journal=False):
|
||||
params = {'response_type': 'code', 'client_id': application.client_id,
|
||||
'redirect_uri': 'http://localhost:9876/callback', 'scope': old_scopes,
|
||||
'state': state, 'code_challenge': challenge, 'code_challenge_method': 'S256',
|
||||
'resource': 'http://localhost:8002/mcp'}
|
||||
consent = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
|
||||
self.assertEqual(consent.status_code, 200)
|
||||
self.assertContains(consent, 'grant_journal_scopes')
|
||||
form = consent.context['form']
|
||||
payload = {field.name: field.value() for field in form
|
||||
if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload['allow'] = 'Authorize'
|
||||
if add_journal:
|
||||
payload['grant_journal_scopes'] = 'on'
|
||||
payload['journal_scope_offer'] = consent.context['journal_scope_offer']
|
||||
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
self.assertEqual(redirect.status_code, 302, redirect.content[:200])
|
||||
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
||||
token_response = self.client.post('/o/token/', {
|
||||
'grant_type': 'authorization_code', 'code': code,
|
||||
'redirect_uri': 'http://localhost:9876/callback',
|
||||
'client_id': application.client_id, 'code_verifier': verifier,
|
||||
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
||||
self.assertEqual(token_response.status_code, 200, token_response.content[:200])
|
||||
return token_response.json()
|
||||
|
||||
original = connect('old-grant')
|
||||
old_scope_set = set(original['scope'].split())
|
||||
self.assertEqual(old_scope_set, set(old_scopes.split()))
|
||||
self.assertEqual(self.client.get('/api/v1/dreams/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {original['access_token']}", HTTP_HOST='localhost').status_code, 403)
|
||||
old_refresh = self.client.post('/o/token/', {'grant_type': 'refresh_token',
|
||||
'refresh_token': original['refresh_token'], 'client_id': application.client_id,
|
||||
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
||||
self.assertEqual(old_refresh.status_code, 200)
|
||||
self.assertEqual(set(old_refresh.json()['scope'].split()), old_scope_set)
|
||||
|
||||
upgraded = connect('upgraded-grant', add_journal=True)
|
||||
expected = set(old_scopes.split()) | {'journal:read', 'journal:write'}
|
||||
self.assertEqual(set(upgraded['scope'].split()), expected)
|
||||
self.assertEqual(self.client.get('/api/v1/dreams/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
||||
dream = self.client.post('/api/v1/dreams/',
|
||||
data='{"wake_up_date":"2026-10-18","title":"Test","narrative":"User supplied."}',
|
||||
content_type='application/json', HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}",
|
||||
HTTP_HOST='localhost')
|
||||
self.assertEqual(dream.status_code, 201, dream.content[:200])
|
||||
self.assertEqual(self.client.get('/api/v1/stress/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
||||
self.assertEqual(self.client.get('/api/v1/food/today/',
|
||||
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
||||
refreshed = self.client.post('/o/token/', {'grant_type': 'refresh_token',
|
||||
'refresh_token': upgraded['refresh_token'], 'client_id': application.client_id,
|
||||
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
||||
self.assertEqual(refreshed.status_code, 200)
|
||||
self.assertEqual(set(refreshed.json()['scope'].split()), expected)
|
||||
|
||||
@override_settings(TASKNEST_MCP_PUBLIC_URL='http://localhost:8002/mcp')
|
||||
def test_journal_upgrade_rejects_missing_or_changed_offer(self):
|
||||
user = get_user_model().objects.create_user('journal-offer', password='test')
|
||||
application = Application.objects.create(user=user, name='Offer test',
|
||||
client_type=Application.CLIENT_PUBLIC,
|
||||
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
||||
redirect_uris='http://localhost:9876/callback')
|
||||
self.client.force_login(user)
|
||||
verifier = 'v' * 64
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
||||
consent = self.client.get('/o/authorize/', {'response_type': 'code',
|
||||
'client_id': application.client_id, 'redirect_uri': 'http://localhost:9876/callback',
|
||||
'scope': 'food:read', 'state': 'offer-test', 'code_challenge': challenge,
|
||||
'code_challenge_method': 'S256', 'resource': 'http://localhost:8002/mcp'},
|
||||
HTTP_HOST='localhost')
|
||||
form = consent.context['form']
|
||||
payload = {field.name: field.value() for field in form
|
||||
if field.field.widget.is_hidden and field.value() is not None}
|
||||
payload.update(allow='Authorize', grant_journal_scopes='on')
|
||||
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'Journal permission offer expired')
|
||||
payload['journal_scope_offer'] = consent.context['journal_scope_offer']
|
||||
payload['scope'] = 'food:write'
|
||||
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'Journal permission offer changed')
|
||||
|
||||
def test_cimd_requires_explicit_public_client_support(self):
|
||||
metadata = {'token_endpoint_auth_method': 'private_key_jwt',
|
||||
'token_endpoint_auth_methods_supported': ['private_key_jwt']}
|
||||
|
||||
+27
-2
@@ -10,7 +10,7 @@ from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from planner.models import UserSettings
|
||||
|
||||
from .services.diary import diary_context
|
||||
from .services.diary import diary_context, ring_progress
|
||||
|
||||
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit, InventoryLocation, KitchenInventoryItem, InventoryConsumption
|
||||
|
||||
@@ -81,12 +81,37 @@ class FoodFoundationTests(TestCase):
|
||||
context = diary_context(self.user, date(2026, 10, 3))
|
||||
self.assertEqual(context['totals']['fibre_g'], Decimal('45'))
|
||||
fibre = context['macros'][3]
|
||||
self.assertEqual(fibre['percent'], 100)
|
||||
self.assertEqual(fibre['percent'], 113)
|
||||
self.assertEqual(fibre['remaining'], Decimal('-5'))
|
||||
self.assertFalse(fibre['incomplete'])
|
||||
self.client.force_login(self.user)
|
||||
self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-03'}), '5.0 g over target')
|
||||
|
||||
def test_ring_laps_and_over_target_accessible_text(self):
|
||||
for amount, percent, base, extra, laps in (
|
||||
('0', 0, '0.00', '0.00', 0),
|
||||
('36', 75, '75.00', '0.00', 0),
|
||||
('48', 100, '100.00', '0.00', 1),
|
||||
('60', 125, '100.00', '25.00', 1),
|
||||
('80.4', 168, '100.00', '67.50', 1),
|
||||
('96', 200, '100.00', '100.00', 2),
|
||||
('108', 225, '100.00', '25.00', 2),
|
||||
):
|
||||
with self.subTest(amount=amount):
|
||||
ring = ring_progress(Decimal(amount), Decimal('48'))
|
||||
self.assertEqual((ring['percent'], ring['base_lap'], ring['extra_lap'], ring['full_laps']),
|
||||
(percent, base, extra, laps))
|
||||
|
||||
UserSettings.objects.create(user=self.user, fat_goal_g=Decimal('48'))
|
||||
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.SNACKS,
|
||||
product_name_snapshot='Known fat', amount=Decimal('100'), unit=Unit.GRAM,
|
||||
fat_g=Decimal('80.4'))
|
||||
self.client.force_login(self.user)
|
||||
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
|
||||
self.assertContains(response, '168%')
|
||||
self.assertContains(response, '32.4 g over target')
|
||||
self.assertContains(response, 'stroke-dasharray="67.50 100"')
|
||||
|
||||
def test_favourite_and_portion_uniqueness(self):
|
||||
FoodFavourite.objects.create(user=self.user, product=self.product)
|
||||
FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('300'), unit=Unit.GRAM)
|
||||
|
||||
Reference in New Issue
Block a user