Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions actions/supabase/queries/reports.ts
Original file line number Diff line number Diff line change
@@ -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";
}
72 changes: 51 additions & 21 deletions app/api/reports/session/[sessionId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -195,6 +202,7 @@ export async function GET(
created_at,
is_finished,
template_id,
user_group_id,
template ( template_name, summary, setting, current_activity )
`,
)
Expand All @@ -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}`;
Expand All @@ -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.
}
}

Expand Down Expand Up @@ -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(
Expand All @@ -571,6 +590,7 @@ export async function POST(
session_name,
created_at,
template_id,
user_group_id,
template ( template_name, summary, setting, current_activity )
`,
)
Expand All @@ -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
Expand Down Expand Up @@ -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" } },
);
}
29 changes: 24 additions & 5 deletions app/api/reports/template/[templateId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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();

Expand All @@ -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")
Expand Down Expand Up @@ -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" } },
);
}
42 changes: 38 additions & 4 deletions app/sessions/session-finish/[sessionId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -39,6 +43,9 @@
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
const [pdfSize, setPdfSize] = useState<number | null>(null);
const [pdfName, setPDFName] = useState<string | null>(null);
const [access, setAccess] = useState<"checking" | "allowed" | "denied">(
"checking",
);

async function fetchOrGenerateReport() {
if (!sessionId) return;
Expand All @@ -54,6 +61,11 @@
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);
Expand Down Expand Up @@ -90,8 +102,7 @@
}

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);
Expand All @@ -100,10 +111,21 @@
}
}

// 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]);

Check warning on line 128 in app/sessions/session-finish/[sessionId]/page.tsx

View workflow job for this annotation

GitHub Actions / Run ESLint, Prettier, and TypeScript compiler

React Hook useEffect has a missing dependency: 'fetchOrGenerateReport'. Either include it or remove the dependency array

Check warning on line 128 in app/sessions/session-finish/[sessionId]/page.tsx

View workflow job for this annotation

GitHub Actions / Run ESLint, Prettier, and TypeScript compiler

React Hook useEffect has a missing dependency: 'fetchOrGenerateReport'. Either include it or remove the dependency array

Check warning on line 128 in app/sessions/session-finish/[sessionId]/page.tsx

View workflow job for this annotation

GitHub Actions / Run ESLint, Prettier, and TypeScript compiler

React Hook useEffect has a missing dependency: 'fetchOrGenerateReport'. Either include it or remove the dependency array

async function handleSave() {
await regenerateReportWithComments(comments.trim() || null);
Expand All @@ -123,6 +145,18 @@
URL.revokeObjectURL(objectUrl);
}

if (access === "denied") {
return <AccessError />;
}

if (access === "checking") {
return (
<LoadingScreen>
<CircularProgress color="inherit" aria-label="Loading…" />
</LoadingScreen>
);
}

return (
<Main>
<Container>
Expand Down
89 changes: 89 additions & 0 deletions lib/reports.ts
Original file line number Diff line number Diff line change
@@ -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<ReportViewer | null> {
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<boolean> {
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<string | null> {
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;
}
Loading