Fix watch tracking, video unlocking and access-control gaps
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:
twotalesanimation
2026-11-11 16:58:07 +02:00
parent 08b6e58b8e
commit a834caa511
16 changed files with 922 additions and 667 deletions
+54 -98
View File
@@ -1,122 +1,78 @@
// app/api/enrollments/sync/route.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';
import { normalizeEmail } from '@/lib/normalize-email';
export async function POST(req: NextRequest) {
console.log('🔥 [SYNC-ENROLLMENTS] POST endpoint called');
console.log('🔥 [SYNC-ENROLLMENTS] Request method:', req.method);
console.log('🔥 [SYNC-ENROLLMENTS] Request URL:', req.url);
/**
* Enrols the signed-in user in the courses listed for them on the allow-list.
* The course codes are read from the database; anything the browser sends is
* ignored, so a user cannot enrol themselves in a course they were not given.
*/
export async function POST() {
try {
const session = await getServerSession(authOptions);
console.log('🔥 [SYNC-ENROLLMENTS] Session check:', !!session?.user?.email);
console.log('🔥 [SYNC-ENROLLMENTS] Session user:', session?.user);
if (!session?.user?.email) {
console.log('🔥 [SYNC-ENROLLMENTS] No session or email, returning 401');
const email = normalizeEmail(session?.user?.email);
if (!email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userEmail = session.user.email;
console.log('🔥 [SYNC-ENROLLMENTS] About to parse request body...');
const body = await req.json();
console.log('🔥 [SYNC-ENROLLMENTS] Raw body received:', JSON.stringify(body, null, 2));
const levels: string[] = body?.levels || [];
console.log('🔥 [SYNC-ENROLLMENTS] Extracted levels:', levels);
console.log('🔥 [SYNC-ENROLLMENTS] Levels type check - isArray:', Array.isArray(levels));
console.log('🔥 [SYNC-ENROLLMENTS] Levels length:', levels.length);
console.log('🔥 [SYNC-ENROLLMENTS] User:', userEmail);
console.log('🔥 [SYNC-ENROLLMENTS] Received levels:', levels);
if (!Array.isArray(levels) || levels.length === 0) {
console.log('🔥 [SYNC-ENROLLMENTS] VALIDATION FAILED!');
console.log('🔥 [SYNC-ENROLLMENTS] levels isArray:', Array.isArray(levels));
console.log('🔥 [SYNC-ENROLLMENTS] levels length:', levels?.length);
console.log('🔥 [SYNC-ENROLLMENTS] levels value:', levels);
console.log('🔥 [SYNC-ENROLLMENTS] Returning 400 - Levels array required');
return NextResponse.json(
{ error: 'Levels array required' },
{ status: 400 }
);
}
// Get user
const user = await prisma.user.findUnique({
where: { email: userEmail },
const user = await prisma.user.findFirst({
where: { email: { equals: email, mode: 'insensitive' } },
select: { id: true },
});
if (!user) {
console.log('[SYNC-ENROLLMENTS] User not found in database:', userEmail);
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
console.log('[SYNC-ENROLLMENTS] Found user:', user.id, user.email);
const allowedStudent = await prisma.allowedStudent.findFirst({
where: { email: { equals: email, mode: 'insensitive' } },
select: { levels: true, active: true },
});
const createdEnrollments = [];
const levels = allowedStudent?.active
? allowedStudent.levels
.split(',')
.map((level) => level.trim())
.filter((level) => level.length > 0)
: [];
// For each course level, find the course and create enrollment
for (const level of levels) {
try {
console.log('[SYNC-ENROLLMENTS] Looking for course with code:', level);
const course = await prisma.course.findUnique({
where: { code: level },
});
if (!course) {
console.warn(`[SYNC-ENROLLMENTS] Course code not found: ${level}`);
continue;
}
console.log('[SYNC-ENROLLMENTS] Found course:', course.id, course.code, course.title);
// Check if enrollment already exists
const existing = await prisma.enrollment.findFirst({
where: { userId: user.id, courseId: course.id },
});
if (existing) {
console.log('[SYNC-ENROLLMENTS] Enrollment already exists:', existing.id);
} else {
const enrollment = await prisma.enrollment.create({
data: {
userId: user.id,
courseId: course.id,
},
});
console.log('[SYNC-ENROLLMENTS] Created new enrollment:', enrollment.id);
createdEnrollments.push({
courseCode: level,
courseId: course.id,
enrollmentId: enrollment.id,
});
}
} catch (err) {
console.error(`[SYNC-ENROLLMENTS] Failed to create enrollment for level ${level}:`, err);
}
if (levels.length === 0) {
return NextResponse.json({ message: 'Enrollments synced', created: [] });
}
console.log('[SYNC-ENROLLMENTS] Summary - Created enrollments:', createdEnrollments.length);
console.log('[SYNC-ENROLLMENTS] Details:', createdEnrollments);
const courses = await prisma.course.findMany({
where: { code: { in: levels } },
select: { id: true, code: true },
});
return NextResponse.json(
{
message: 'Enrollments synced',
created: createdEnrollments,
},
{ status: 200 }
);
const missing = levels.filter((level) => !courses.some((c) => c.code === level));
if (missing.length > 0) {
console.warn(`[SYNC-ENROLLMENTS] Course codes not found: ${missing.join(', ')}`);
}
const created = [];
for (const course of courses) {
const existing = await prisma.enrollment.findUnique({
where: { userId_courseId: { userId: user.id, courseId: course.id } },
select: { id: true },
});
if (existing) continue;
const enrollment = await prisma.enrollment.create({
data: { userId: user.id, courseId: course.id },
});
created.push({
courseCode: course.code,
courseId: course.id,
enrollmentId: enrollment.id,
});
}
return NextResponse.json({ message: 'Enrollments synced', created });
} catch (err) {
console.error('🔥 [SYNC-ENROLLMENTS] FATAL ERROR:', err);
console.error('🔥 [SYNC-ENROLLMENTS] Error stack:', err instanceof Error ? err.stack : 'No stack');
return NextResponse.json(
{ error: 'Failed to sync enrollments' },
{ status: 500 }
);
console.error('[SYNC-ENROLLMENTS] error:', err);
return NextResponse.json({ error: 'Failed to sync enrollments' }, { status: 500 });
}
}