Files
Vault/lib/video-access.ts
T
twotalesanimation 9a73058eb4
Deploy Vault CMS / deploy (push) Failing after 4m1s
Upgrade Next.js to 16.4.6 and show locks on latest videos
- Upgrade next and eslint-config-next from 16.3.5 to 16.4.6. The older
  version has critical advisories, which made the Docker build's
  `pnpm audit --audit-level critical` step fail and blocked deploys.
- /api/videos/latest now reports whether the viewer can open each video;
  the dashboard shows a lock and the reason instead of opening the player.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 17:56:19 +02:00

70 lines
2.6 KiB
TypeScript

// lib/video-access.ts
// Who is asking, and may they watch this video? Shared by the video API and
// the routes that serve the media files themselves.
import { getServerSession } from 'next-auth';
import { authOptions } from './auth-options';
import { prisma } from './prisma';
import { checkUnlockEligibility } from './watch-progress';
export type Viewer = { id: string; isAdmin: boolean };
/** The signed-in user, or null. Does not touch the database. */
export async function getViewer(): Promise<Viewer | null> {
const session = await getServerSession(authOptions);
const user = session?.user as { id?: string; email?: string; role?: string } | undefined;
if (!user?.email || !user.id) return null;
return { id: user.id, isAdmin: user.role === 'admin' || user.role === 'superadmin' };
}
export type AccessResult = { ok: true } | { ok: false; status: number; error: string };
// A playing video requests a media chunk every few seconds, so a positive
// answer is remembered briefly. Refusals are never cached: an unlock applies
// straight away, while a newly applied lock can take up to this long to bite.
const TTL_MS = 60_000;
const MAX_ENTRIES = 20_000;
const allowed = new Map<string, number>();
/**
* Admins may watch anything. Students need to be enrolled, and the video must
* be open to them: first in its playlist, instant access, already unlocked, or
* earned by completing the video before it.
*/
export async function checkVideoAccess(
viewer: Viewer,
videoId: string,
// `peek` only answers the question (for listings); it records nothing.
opts: { peek?: boolean } = {}
): Promise<AccessResult> {
if (viewer.isAdmin) return { ok: true };
const key = `${viewer.id}:${videoId}`;
const expires = allowed.get(key);
if (expires && expires > Date.now()) return { ok: true };
const check = await checkUnlockEligibility(viewer.id, videoId);
const where = { userId_videoId: { userId: viewer.id, videoId } };
if (check.ok) {
if (!check.free && !opts.peek) {
// Earned but never recorded (e.g. completed before unlocks were tracked).
await prisma.videoUnlock.upsert({
where,
update: {},
create: { userId: viewer.id, videoId },
});
}
} else {
const unlocked =
check.reason === 'not_earned' &&
(await prisma.videoUnlock.findUnique({ where, select: { id: true } }));
if (!unlocked) return { ok: false, status: check.status, error: check.error };
}
if (!opts.peek) {
if (allowed.size >= MAX_ENTRIES) allowed.clear();
allowed.set(key, Date.now() + TTL_MS);
}
return { ok: true };
}