// 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 { 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(); /** * 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 { 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 }; }