diff --git a/actions/supabase/queries/reports.ts b/actions/supabase/queries/reports.ts new file mode 100644 index 00000000..6bb0e1b5 --- /dev/null +++ b/actions/supabase/queries/reports.ts @@ -0,0 +1,29 @@ +"use server"; + +import { canViewSessionReport, getReportViewer } from "@/lib/reports"; +import { getSupabaseAdminClient } from "@/lib/supabase/server"; + +// Same rule the session report API enforces, without generating the PDF, +// so pages can show an access error right away. +export async function checkSessionReportAccess( + sessionId: string, +): Promise<"allowed" | "denied"> { + const admin = getSupabaseAdminClient(); + const { data: session } = await admin + .from("session") + .select("user_group_id") + .eq("session_id", sessionId) + .maybeSingle(); + if (!session) return "denied"; + + const viewer = await getReportViewer(); + if (!viewer) return "denied"; + + const allowed = await canViewSessionReport( + admin, + viewer, + sessionId, + session.user_group_id, + ); + return allowed ? "allowed" : "denied"; +} diff --git a/app/api/reports/session/[sessionId]/route.ts b/app/api/reports/session/[sessionId]/route.ts index 3087f4fc..0bc53441 100644 --- a/app/api/reports/session/[sessionId]/route.ts +++ b/app/api/reports/session/[sessionId]/route.ts @@ -7,6 +7,13 @@ import type { import { createClient } from "@supabase/supabase-js"; import { generateSessionReport } from "@/lib/pdf/generate"; import { loadPdfImages } from "@/lib/pdf/images"; +import { + accessDenied, + canViewSessionReport, + getReportViewer, + isStaffForGroup, + signedReportUrl, +} from "@/lib/reports"; import { buildSessionDisplayName } from "@/utils/session-details"; export const dynamic = "force-dynamic"; @@ -195,6 +202,7 @@ export async function GET( created_at, is_finished, template_id, + user_group_id, template ( template_name, summary, setting, current_activity ) `, ) @@ -205,6 +213,19 @@ export async function GET( return Response.json({ error: "Session not found" }, { status: 404 }); } + const viewer = await getReportViewer(); + if ( + !viewer || + !(await canViewSessionReport( + supabase, + viewer, + sessionId, + session.user_group_id, + )) + ) { + return accessDenied(viewer); + } + // Only use the cached file if the session is finished — in-progress PDFs // are stale the moment new responses arrive, so always regenerate those. const folderPath = `sessions/${sessionId}`; @@ -214,17 +235,17 @@ export async function GET( .list(folderPath); if (existingFiles && existingFiles.length > 0) { - const existing = existingFiles[0]; - const { data: urlData } = supabase.storage - .from("reports") - .getPublicUrl(`${folderPath}/${existing.name}`); - const updatedAt = - existingFiles[0].updated_at ?? existingFiles[0].created_at; - const bust = updatedAt ? new Date(updatedAt).getTime() : Date.now(); - return Response.json( - { url: `${urlData.publicUrl}?t=${bust}` }, - { headers: { "Cache-Control": "no-store" } }, + const url = await signedReportUrl( + supabase, + `${folderPath}/${existingFiles[0].name}`, ); + if (url) { + return Response.json( + { url }, + { headers: { "Cache-Control": "no-store" } }, + ); + } + // Couldn't sign the cached file: fall through and regenerate it. } } @@ -540,14 +561,12 @@ export async function GET( ); } - const { data: urlData } = supabase.storage - .from("reports") - .getPublicUrl(fileName); + const url = await signedReportUrl(supabase, fileName); + if (!url) { + return Response.json({ error: "Could not create link" }, { status: 500 }); + } - return Response.json( - { url: `${urlData.publicUrl}?t=${Date.now()}` }, - { headers: { "Cache-Control": "no-store" } }, - ); + return Response.json({ url }, { headers: { "Cache-Control": "no-store" } }); } export async function POST( @@ -571,6 +590,7 @@ export async function POST( session_name, created_at, template_id, + user_group_id, template ( template_name, summary, setting, current_activity ) `, ) @@ -581,6 +601,12 @@ export async function POST( return Response.json({ error: "Session not found" }, { status: 404 }); } + // Only staff can regenerate the report (it adds facilitator comments). + const viewer = await getReportViewer(); + if (!viewer || !isStaffForGroup(viewer, session.user_group_id)) { + return accessDenied(viewer); + } + const template = session.template as unknown as NestedTemplate | null; // Phases (ordered) — soft fail to empty array @@ -879,9 +905,13 @@ export async function POST( ); } - const { data: urlData } = supabase.storage - .from("reports") - .getPublicUrl(fileName); + const url = await signedReportUrl(supabase, fileName); + if (!url) { + return Response.json({ error: "Could not create link" }, { status: 500 }); + } - return Response.json({ url: urlData.publicUrl, sizeBytes: pdfBytes.length }); + return Response.json( + { url, sizeBytes: pdfBytes.length }, + { headers: { "Cache-Control": "no-store" } }, + ); } diff --git a/app/api/reports/template/[templateId]/route.ts b/app/api/reports/template/[templateId]/route.ts index fa19ce05..43ab4e6b 100644 --- a/app/api/reports/template/[templateId]/route.ts +++ b/app/api/reports/template/[templateId]/route.ts @@ -5,6 +5,12 @@ import type { import { createClient } from "@supabase/supabase-js"; import { generateSessionReport } from "@/lib/pdf/generate"; import { loadPdfImages } from "@/lib/pdf/images"; +import { + accessDenied, + getReportViewer, + isStaffForGroup, + signedReportUrl, +} from "@/lib/reports"; export const dynamic = "force-dynamic"; @@ -23,7 +29,9 @@ export async function GET( const { data: template, error: templateError } = await supabase .from("template") - .select("template_id, template_name, summary, setting, current_activity") + .select( + "template_id, template_name, summary, setting, current_activity, user_group_id, accessible_to_all", + ) .eq("template_id", templateId) .single(); @@ -32,6 +40,16 @@ export async function GET( return Response.json({ error: "Template not found" }, { status: 404 }); } + // Admins, or facilitators who can see this template in their list. + const viewer = await getReportViewer(); + const canView = + viewer && + (isStaffForGroup(viewer, template.user_group_id) || + (viewer.userType === "Facilitator" && template.accessible_to_all)); + if (!viewer || !canView) { + return accessDenied(viewer); + } + const { data: phases, error: phasesError } = await supabase .from("phase") .select("phase_id, phase_name, phase_number, phase_description") @@ -212,12 +230,13 @@ export async function GET( ); } - const { data: urlData } = supabase.storage - .from("reports") - .getPublicUrl(reportFileName); + const url = await signedReportUrl(supabase, reportFileName); + if (!url) { + return Response.json({ error: "Could not create link" }, { status: 500 }); + } return Response.json( - { url: `${urlData.publicUrl}?t=${Date.now()}`, sizeBytes: pdfBytes.length }, + { url, sizeBytes: pdfBytes.length }, { headers: { "Cache-Control": "no-store" } }, ); } diff --git a/app/sessions/session-finish/[sessionId]/page.tsx b/app/sessions/session-finish/[sessionId]/page.tsx index 9897ed53..74b935aa 100644 --- a/app/sessions/session-finish/[sessionId]/page.tsx +++ b/app/sessions/session-finish/[sessionId]/page.tsx @@ -3,7 +3,11 @@ import { useEffect, useState } from "react"; import Link from "next/link"; import { useParams } from "next/navigation"; +import { CircularProgress } from "@mui/material"; +import { checkSessionReportAccess } from "@/actions/supabase/queries/reports"; import { fetchPDFName } from "@/actions/supabase/queries/sessions"; +import { LoadingScreen } from "@/app/facilitator/participants/styles"; +import AccessError from "@/components/AccessError/AccessError"; import { getHomePath } from "@/utils/HomePage"; import { useProfile } from "@/utils/ProfileProvider"; import { buildSessionDisplayName } from "@/utils/session-details"; @@ -39,6 +43,9 @@ export default function SessionFinish() { const [pdfUrl, setPdfUrl] = useState(null); const [pdfSize, setPdfSize] = useState(null); const [pdfName, setPDFName] = useState(null); + const [access, setAccess] = useState<"checking" | "allowed" | "denied">( + "checking", + ); async function fetchOrGenerateReport() { if (!sessionId) return; @@ -54,6 +61,11 @@ export default function SessionFinish() { try { const res = await fetch(`/api/reports/session/${sessionId}`); + if (res.status === 401 || res.status === 403 || res.status === 404) { + setAccess("denied"); + return; + } + if (!res.ok) { const errBody = await res.json().catch(() => ({})); console.error("Report API error:", res.status, errBody); @@ -90,8 +102,7 @@ export default function SessionFinish() { } const data = await res.json(); - // Append cache-buster so the CDN doesn't serve the previous version - setPdfUrl(`${data.url}?t=${Date.now()}`); + setPdfUrl(data.url); setPdfSize(data.sizeBytes ?? null); } catch (err) { console.error(err); @@ -100,9 +111,20 @@ export default function SessionFinish() { } } - // Load existing report on page load, generate if none exists. + // Check access first, then load the existing report (or generate one). useEffect(() => { - fetchOrGenerateReport(); + if (!sessionId) return; + let cancelled = false; + checkSessionReportAccess(sessionId) + .catch(() => "denied" as const) + .then(result => { + if (cancelled) return; + setAccess(result); + if (result === "allowed") fetchOrGenerateReport(); + }); + return () => { + cancelled = true; + }; }, [sessionId]); async function handleSave() { @@ -123,6 +145,18 @@ export default function SessionFinish() { URL.revokeObjectURL(objectUrl); } + if (access === "denied") { + return ; + } + + if (access === "checking") { + return ( + + + + ); + } + return (
diff --git a/lib/reports.ts b/lib/reports.ts new file mode 100644 index 00000000..f04d0e2d --- /dev/null +++ b/lib/reports.ts @@ -0,0 +1,89 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; +import { getSupabaseServerClient } from "@/lib/supabase/server"; + +// Server-only helpers for the PDF report routes. +// assigns signed urls for signed in users + +export const REPORTS_BUCKET = "reports"; +const REPORT_URL_SECONDS = 60 * 60; // can only use for 1 hour + +export type ReportViewer = { + id: string; + userType: string; + userGroupId: string | null; +}; + +// The logged-in user making the request, or null if not logged in. +export async function getReportViewer(): Promise { + const supabase = await getSupabaseServerClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) return null; + + const { data: profile } = await supabase + .from("profile") + .select("user_type, user_group_id") + .eq("id", user.id) + .single(); + if (!profile) return null; + + return { + id: user.id, + userType: profile.user_type, + userGroupId: profile.user_group_id, + }; +} + +export function isStaffForGroup( + viewer: ReportViewer, + userGroupId: string | null, +): boolean { + if (viewer.userType === "Admin") return true; + return ( + viewer.userType === "Facilitator" && + userGroupId != null && + viewer.userGroupId === userGroupId + ); +} + +export async function canViewSessionReport( + admin: SupabaseClient, + viewer: ReportViewer, + sessionId: string, + sessionUserGroupId: string | null, +): Promise { + if (viewer.userType === "Admin") return true; + if (sessionUserGroupId != null && viewer.userGroupId === sessionUserGroupId) { + return true; + } + + const { data } = await admin + .from("participant_session") + .select("user_id") + .eq("session_id", sessionId) + .eq("user_id", viewer.id) + .limit(1); + return (data?.length ?? 0) > 0; +} + +export function accessDenied(viewer: ReportViewer | null): Response { + return viewer + ? Response.json({ error: "Not allowed" }, { status: 403 }) + : Response.json({ error: "Not logged in" }, { status: 401 }); +} + +// Each call returns a new URL (new token) +export async function signedReportUrl( + admin: SupabaseClient, + path: string, +): Promise { + const { data, error } = await admin.storage + .from(REPORTS_BUCKET) + .createSignedUrl(path, REPORT_URL_SECONDS); + if (error || !data) { + console.error("Failed to sign report URL:", error); + return null; + } + return data.signedUrl; +}