(all) add organizations, resources, channels, and infra migration (#34)

Add multi-tenant organization model populated from OIDC claims with
org-scoped user discovery, CalDAV principal filtering, and cross-org
isolation at the SabreDAV layer.

Add bookable resource principals (rooms, equipment) with CalDAV
auto-scheduling that handles conflict detection, auto-accept/decline,
and org-scoped booking enforcement. Fixes #14.

Replace CalendarSubscriptionToken with a unified Channel model
supporting CalDAV integration tokens and iCal feed URLs, with
encrypted token storage and role-based access control. Fixes #16.

Migrate task queue from Celery to Dramatiq with async ICS import,
progress tracking, and task status polling endpoint.

Replace nginx with Caddy for both the reverse proxy and frontend
static serving. Switch frontend package manager from yarn/pnpm to
npm and upgrade Node to 24, Next.js to 16, TypeScript to 5.9.

Harden security with fail-closed entitlements, RSVP rate limiting
and token expiry, CalDAV proxy path validation blocking internal
API routes, channel path scope enforcement, and ETag-based
conflict prevention.

Add frontend pages for resource management and integration channel
CRUD, with resource booking in the event modal.

Restructure CalDAV paths to /calendars/users/ and
/calendars/resources/ with nested principal collections in SabreDAV.
This commit is contained in:
Sylvain Zimmer
2026-03-09 09:09:34 +01:00
committed by GitHub
parent cd2b15b3b5
commit 9c18f96090
176 changed files with 26903 additions and 12108 deletions

View File

@@ -1,16 +1,28 @@
"""RSVP view for handling invitation responses from email links."""
"""RSVP view for handling invitation responses from email links.
GET /rsvp/?token=...&action=accepted -> renders a confirmation page that
auto-submits via JavaScript (no extra click for the user).
POST /api/v1.0/rsvp/ -> processes the RSVP and returns a
result page. Link previewers / prefetchers only issue GET, so the
state-changing work is safely behind POST.
"""
import logging
import re
from datetime import timezone as dt_timezone
from django.core.signing import BadSignature, Signer
from django.conf import settings
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.shortcuts import render
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from rest_framework.throttling import AnonRateThrottle
from rest_framework.views import APIView
from core.models import User
from core.services.caldav_service import CalDAVHTTPClient
from core.services.translation_service import TranslationService
@@ -35,7 +47,7 @@ PARTSTAT_VALUES = {
}
def _render_error(request, message, lang="fr"):
def _render_error(request, message, lang="en"):
"""Render the RSVP error page."""
t = TranslationService.t
return render(
@@ -85,69 +97,169 @@ def _is_event_past(icalendar_data):
return False
@method_decorator(csrf_exempt, name="dispatch")
class RSVPView(View):
"""Handle RSVP responses from invitation email links."""
def _validate_token(token, max_age=None):
"""Unsign and validate an RSVP token.
def get(self, request): # noqa: PLR0911 # pylint: disable=too-many-return-statements
"""Process an RSVP response."""
Returns (payload, error_key). On success error_key is None.
"""
ts_signer = TimestampSigner(salt="rsvp")
try:
payload = ts_signer.unsign_object(token, max_age=max_age)
except SignatureExpired:
return None, "token_expired"
except BadSignature:
return None, "invalid_token"
uid = payload.get("uid")
recipient_email = payload.get("email")
organizer_email = payload.get("organizer", "")
# Strip mailto: prefix (case-insensitive) in case it leaked into the token
organizer_email = re.sub(r"^mailto:", "", organizer_email, flags=re.IGNORECASE)
if not uid or not recipient_email or not organizer_email:
return None, "invalid_payload"
payload["organizer"] = organizer_email
return payload, None
_TOKEN_ERROR_KEYS = {
"token_expired": "rsvp.error.tokenExpired",
"invalid_token": "rsvp.error.invalidToken",
"invalid_payload": "rsvp.error.invalidPayload",
}
def _validate_and_render_error(request, token, action, lang):
"""Validate action + token; return (payload, error_response).
On success error_response is None.
"""
t = TranslationService.t
if action not in PARTSTAT_VALUES:
return None, _render_error(request, t("rsvp.error.invalidAction", lang), lang)
payload, error = _validate_token(
token, max_age=settings.RSVP_TOKEN_MAX_AGE_RECURRING
)
if error:
return None, _render_error(request, t(_TOKEN_ERROR_KEYS[error], lang), lang)
return payload, None
@method_decorator(csrf_exempt, name="dispatch")
class RSVPConfirmView(View):
"""GET handler: render auto-submitting confirmation page.
This page is safe for link previewers / prefetchers because it
doesn't change any state — only the POST endpoint does.
"""
def get(self, request):
"""Render a page that auto-submits the RSVP via POST."""
token = request.GET.get("token", "")
action = request.GET.get("action", "")
lang = TranslationService.resolve_language(request=request)
_, error_response = _validate_and_render_error(request, token, action, lang)
if error_response:
return error_response
# Render auto-submit page
label = TranslationService.t(f"rsvp.{action}", lang)
return render(
request,
"rsvp/confirm.html",
{
"page_title": label,
"token": token,
"action": action,
"lang": lang,
"heading": label,
"status_icon": PARTSTAT_ICONS[action],
"header_color": PARTSTAT_COLORS[action],
"submit_label": label,
"post_url": f"/api/{settings.API_VERSION}/rsvp/",
},
)
class RSVPThrottle(AnonRateThrottle):
"""Throttle RSVP POST requests: 30/min per IP."""
rate = "30/minute"
def _process_rsvp(request, payload, action, lang):
"""Execute the RSVP: find event, update PARTSTAT, PUT back.
Returns an error response on failure, or the updated calendar data
string on success.
"""
t = TranslationService.t
http = CalDAVHTTPClient()
try:
organizer = User.objects.get(email=payload["organizer"])
except User.DoesNotExist:
return _render_error(request, t("rsvp.error.eventNotFound", lang), lang)
calendar_data, href, etag = http.find_event_by_uid(organizer, payload["uid"])
if not calendar_data or not href:
return _render_error(request, t("rsvp.error.eventNotFound", lang), lang)
if _is_event_past(calendar_data):
return _render_error(request, t("rsvp.error.eventPast", lang), lang)
updated_data = CalDAVHTTPClient.update_attendee_partstat(
calendar_data, payload["email"], PARTSTAT_VALUES[action]
)
if not updated_data:
return _render_error(request, t("rsvp.error.notAttendee", lang), lang)
if not http.put_event(organizer, href, updated_data, etag=etag):
return _render_error(request, t("rsvp.error.updateFailed", lang), lang)
return calendar_data
class RSVPProcessView(APIView):
"""POST handler: actually process the RSVP.
Uses DRF's AnonRateThrottle for rate limiting. No authentication
required — the signed token acts as authorization.
"""
authentication_classes = []
permission_classes = []
throttle_classes = [RSVPThrottle]
def post(self, request):
"""Process the RSVP response."""
token = request.data.get("token", "")
action = request.data.get("action", "")
lang = TranslationService.resolve_language(request=request)
t = TranslationService.t
# Validate action
if action not in PARTSTAT_VALUES:
return _render_error(request, t("rsvp.error.invalidAction", lang), lang)
# Unsign token — tokens don't have a built-in expiry,
# but RSVPs are rejected once the event has ended (_is_event_past).
signer = Signer(salt="rsvp")
try:
payload = signer.unsign_object(token)
except BadSignature:
return _render_error(request, t("rsvp.error.invalidToken", lang), lang)
uid = payload.get("uid")
recipient_email = payload.get("email")
# Strip mailto: prefix (case-insensitive) in case it leaked into the token
organizer_email = re.sub(
r"^mailto:", "", payload.get("organizer", ""), flags=re.IGNORECASE
payload, error_response = _validate_and_render_error(
request, token, action, lang
)
if error_response:
return error_response
if not uid or not recipient_email or not organizer_email:
return _render_error(request, t("rsvp.error.invalidPayload", lang), lang)
result = _process_rsvp(request, payload, action, lang)
http = CalDAVHTTPClient()
# result is either an error HttpResponse or calendar data string
if not isinstance(result, str):
return result
# Find the event in the organizer's CalDAV calendars
calendar_data, href = http.find_event_by_uid(organizer_email, uid)
if not calendar_data or not href:
return _render_error(request, t("rsvp.error.eventNotFound", lang), lang)
# Check if the event is already over
if _is_event_past(calendar_data):
return _render_error(request, t("rsvp.error.eventPast", lang), lang)
# Update the attendee's PARTSTAT
partstat = PARTSTAT_VALUES[action]
updated_data = CalDAVHTTPClient.update_attendee_partstat(
calendar_data, recipient_email, partstat
)
if not updated_data:
return _render_error(request, t("rsvp.error.notAttendee", lang), lang)
# PUT the updated event back to CalDAV
success = http.put_event(organizer_email, href, updated_data)
if not success:
return _render_error(request, t("rsvp.error.updateFailed", lang), lang)
# Extract event summary for display
from core.services.calendar_invitation_service import ( # noqa: PLC0415 # pylint: disable=import-outside-toplevel
ICalendarParser,
)
summary = ICalendarParser.extract_property(calendar_data, "SUMMARY") or ""
summary = ICalendarParser.extract_property(result, "SUMMARY") or ""
label = t(f"rsvp.{action}", lang)
return render(