Fix watch tracking, video unlocking and access-control gaps
Deploy Vault CMS / deploy (push) Failing after 38s
Deploy Vault CMS / deploy (push) Failing after 38s
Watch progress and unlocking: - Player samples the playhead and reports the ranges actually played, so skipped sections earn no credit and early plays are not lost - Server merges ranges into compact segment rows; progress never regresses - Single 80% unlock rule enforced server-side (lib/watch-progress.ts); the Unlock button and automatic unlock now agree - Lock state and progress bar update live from each progress save - Playlist is derived from the video, so unlocks work for shared playlists and for links from watch history and liked videos - First/previous video decided by playlist position, not index numbers Access control: - Video API and HLS/MP4 routes require a signed-in viewer who is enrolled and has the video unlocked; thumbnails require sign-in - Enrolment sync reads course codes from the allow-list, not the request - /api/admin/meta is admin-only - Account status, role and levels are re-checked from the database during a session, so deactivated students lose access within a minute Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
// 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): 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) {
|
||||
// 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 (allowed.size >= MAX_ENTRIES) allowed.clear();
|
||||
allowed.set(key, Date.now() + TTL_MS);
|
||||
return { ok: true };
|
||||
}
|
||||
Reference in New Issue
Block a user