Files
Django_TasksApp/main/food/oauth_authorize.py
T
2026-10-19 16:51:53 +02:00

54 lines
2.5 KiB
Python

"""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)