Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Access Control Module
*
* Determines what access a user has to a player based on:
* - Parent-child relationship (always full access)
* - Teacher-student relationship (enrolled students)
* - Presence (student currently in teacher's classroom)
*
* Guest sharing rule:
* Shared (non-owned) students expire for guest accounts after 24 hours.
* This is enforced centrally via getParentedPlayerIds() and isParentOf().
* All access checks and player listings go through these functions.
*
* Two canonical primitives:
* 1. isParentOf(userId, playerId) — THE single-player parent check
* 2. getParentedPlayerIds(userId) — THE listing primitive (all player IDs a user has parent access to)
*
* Higher-level functions (getPlayerAccess, canPerformAction, getAccessiblePlayers)
* are built on top of these two primitives.
*/
import { and, eq } from 'drizzle-orm'
import { db } from '@/db'
import {
classroomEnrollments,
classroomPresence,
classrooms,
parentChild,
players,
type Player,
users,
} from '@/db/schema'
const GUEST_SHARE_EXPIRY_MS = 24 * 60 * 60 * 1000 // 24 hours
// ---------------------------------------------------------------------------
// Level 1 (internal): Guest detection
// ---------------------------------------------------------------------------
/** Check if a user is a guest (not yet authenticated). */
async function isGuestUser(userId: string): Promise<boolean> {
const user = await db.query.users.findFirst({
where: eq(users.id, userId),
columns: { upgradedAt: true },
})
return !user?.upgradedAt
}
// ---------------------------------------------------------------------------
// Level 2 (exported): Canonical parent-check primitives
// ---------------------------------------------------------------------------
/**
* Check if a user is a parent of a player.
*
* THE single-player parent check. Logic:
* 1. players.userId === userId → always true (ownership)
* 2. parent_child link exists + user is authenticated → true
* 3. parent_child link exists + user is guest + link < 24h → true
* 4. Otherwise → false
*/
export async function isParentOf(viewerId: string, playerId: string): Promise<boolean> {
// Check if viewer owns the player (always valid, regardless of parent_child links)
const player = await db.query.players.findFirst({
where: eq(players.id, playerId),
columns: { userId: true },
})
if (player?.userId === viewerId) return true
// Check parent_child link
const link = await db.query.parentChild.findFirst({
where: and(eq(parentChild.parentUserId, viewerId), eq(parentChild.childPlayerId, playerId)),
})
if (!link) return false
// Shared student — check guest expiry
const isGuest = await isGuestUser(viewerId)
if (!isGuest) return true
const cutoff = new Date(Date.now() - GUEST_SHARE_EXPIRY_MS)
return link.linkedAt >= cutoff
}
/**
* Get all player IDs that a user has parent access to.
*
* THE listing primitive. Returns all player IDs this user can access as a parent:
* - All players where players.userId = userId (owned)
* - All players linked via parent_child (with guest expiry for non-owned)
* - Union, deduplicated
*/
export async function getParentedPlayerIds(userId: string): Promise<string[]> {
const ownedPlayers = await db.query.players.findMany({
where: eq(players.userId, userId),
columns: { id: true },
})
const ownedIds = new Set(ownedPlayers.map((p) => p.id))
const links = await db.query.parentChild.findMany({
where: eq(parentChild.parentUserId, userId),
})
const linkedIds = links.map((l) => l.childPlayerId)
const isGuest = await isGuestUser(userId)
if (!isGuest) {
return [...new Set([...ownedIds, ...linkedIds])]
}
// Guest: apply 24h expiry to non-owned shared links
const cutoff = new Date(Date.now() - GUEST_SHARE_EXPIRY_MS)
const validLinkedIds = links
.filter((link) => ownedIds.has(link.childPlayerId) || link.linkedAt >= cutoff)
.map((l) => l.childPlayerId)
return [...new Set([...ownedIds, ...validLinkedIds])]
}
// ---------------------------------------------------------------------------
// Level 3 (exported): Access levels and player access
// ---------------------------------------------------------------------------
/**
* Access levels in order of increasing permissions:
* - 'none': No access to this player
* - 'teacher-enrolled': Can view history/skills (student is enrolled)
* - 'teacher-present': Can run sessions, observe, control (student is present)
* - 'parent': Full access always (parent-child relationship)
*/
export type AccessLevel = 'none' | 'teacher-enrolled' | 'teacher-present' | 'parent'
/**
* Result of checking a user's access to a player
*/
export interface PlayerAccess {
playerId: string
accessLevel: AccessLevel
isParent: boolean
isTeacher: boolean
isPresent: boolean
/** Classroom ID if the viewer is a teacher */
classroomId?: string
}
/**
* Determine what access a viewer has to a player
*/
export async function getPlayerAccess(viewerId: string, playerId: string): Promise<PlayerAccess> {
const start = performance.now()
const timings: Record<string, number> = {}
// Check parent relationship (with guest expiry)
let t = performance.now()
const isParent = await isParentOf(viewerId, playerId)
timings.parentCheck = performance.now() - t
// Check teacher relationship (enrolled in their classroom)
t = performance.now()
const classroom = await db.query.classrooms.findFirst({
where: eq(classrooms.teacherId, viewerId),
})
timings.classroomCheck = performance.now() - t
let isTeacher = false
let isPresent = false
if (classroom) {
t = performance.now()
const enrollment = await db.query.classroomEnrollments.findFirst({
where: and(
eq(classroomEnrollments.classroomId, classroom.id),
eq(classroomEnrollments.playerId, playerId)
),
})
timings.enrollmentCheck = performance.now() - t
isTeacher = !!enrollment
if (isTeacher) {
t = performance.now()
const presence = await db.query.classroomPresence.findFirst({
where: and(
eq(classroomPresence.classroomId, classroom.id),
eq(classroomPresence.playerId, playerId)
),
})
timings.presenceCheck = performance.now() - t
isPresent = !!presence
}
}
// Determine access level (parent takes precedence)
let accessLevel: AccessLevel = 'none'
if (isParent) {
accessLevel = 'parent'
} else if (isPresent) {
accessLevel = 'teacher-present'
} else if (isTeacher) {
accessLevel = 'teacher-enrolled'
}
const total = performance.now() - start
console.log(
`[PERF] getPlayerAccess: ${total.toFixed(1)}ms | ` +
`parent=${timings.parentCheck?.toFixed(1)}ms, ` +
`classroom=${timings.classroomCheck?.toFixed(1)}ms` +
(timings.enrollmentCheck ? `, enrollment=${timings.enrollmentCheck.toFixed(1)}ms` : '') +
(timings.presenceCheck ? `, presence=${timings.presenceCheck.toFixed(1)}ms` : '')
)
return {
playerId,
accessLevel,
isParent,
isTeacher,
isPresent,
classroomId: classroom?.id,
}
}
/**
* Actions that can be performed on a player
*/
export type PlayerAction =
| 'view' // View skills, history, progress
| 'start-session' // Start a practice session
| 'observe' // Watch an active session
| 'control-tutorial' // Control tutorial navigation
| 'control-abacus' // Control the abacus display
/**
* Check if viewer can perform action on player
*/
export async function canPerformAction(
viewerId: string,
playerId: string,
action: PlayerAction
): Promise<boolean> {
const start = performance.now()
const access = await getPlayerAccess(viewerId, playerId)
const accessTime = performance.now() - start
let result: boolean
switch (action) {
case 'view':
// Parent or any teacher relationship (enrolled or present)
result = access.accessLevel !== 'none'
break
case 'start-session':
case 'observe':
case 'control-tutorial':
case 'control-abacus':
// Parent always, or teacher with presence
result = access.isParent || access.isPresent
break
default:
result = false
}
console.log(
`[PERF] canPerformAction(${action}): ${(performance.now() - start).toFixed(1)}ms | getPlayerAccess=${accessTime.toFixed(1)}ms, result=${result}`
)
return result
}
// ---------------------------------------------------------------------------
// Level 4 (exported): Accessible players (bulk listing)
// ---------------------------------------------------------------------------
/**
* Result of getting all accessible players for a viewer
*/
export interface AccessiblePlayers {
/** Children where viewer is a parent (full access) */
ownChildren: Player[]
/** Students enrolled in viewer's classroom (view only unless present) */
enrolledStudents: Player[]
/** Students currently present in viewer's classroom (full access) */
presentStudents: Player[]
}
/**
* Get all players accessible to a viewer
*
* Returns three categories:
* - ownChildren: Viewer is a parent (always full access)
* - enrolledStudents: Enrolled in viewer's classroom (can be view-only or full)
* - presentStudents: Currently present in viewer's classroom (full access)
*
* Note: Own children who are also enrolled appear ONLY in ownChildren,
* not duplicated in enrolledStudents.
*/
export async function getAccessiblePlayers(viewerId: string): Promise<AccessiblePlayers> {
// Own children: all players the user has parent access to (via getParentedPlayerIds)
const allChildIds = await getParentedPlayerIds(viewerId)
let ownChildren: Player[] = []
if (allChildIds.length > 0) {
ownChildren = await db.query.players.findMany({
where: (p, { inArray }) => inArray(p.id, allChildIds),
})
}
const ownChildIds = new Set(ownChildren.map((c) => c.id))
// Check if viewer is a teacher
const classroom = await db.query.classrooms.findFirst({
where: eq(classrooms.teacherId, viewerId),
})
let enrolledStudents: Player[] = []
let presentStudents: Player[] = []
if (classroom) {
// Enrolled students (exclude own children to avoid duplication)
const enrollments = await db.query.classroomEnrollments.findMany({
where: eq(classroomEnrollments.classroomId, classroom.id),
})
const enrolledIds = enrollments.map((e) => e.playerId).filter((id) => !ownChildIds.has(id))
if (enrolledIds.length > 0) {
enrolledStudents = await db.query.players.findMany({
where: (players, { inArray }) => inArray(players.id, enrolledIds),
})
}
// Present students (subset of enrolled, for quick lookup)
const presences = await db.query.classroomPresence.findMany({
where: eq(classroomPresence.classroomId, classroom.id),
})
const presentIds = new Set(presences.map((p) => p.playerId))
// Present students includes both own children and enrolled students
presentStudents = [...ownChildren, ...enrolledStudents].filter((s) => presentIds.has(s.id))
}
return { ownChildren, enrolledStudents, presentStudents }
}
/**
* Check if a user is the teacher of a classroom where the player is enrolled
*/
export async function isTeacherOf(userId: string, playerId: string): Promise<boolean> {
const classroom = await db.query.classrooms.findFirst({
where: eq(classrooms.teacherId, userId),
})
if (!classroom) return false
const enrollment = await db.query.classroomEnrollments.findFirst({
where: and(
eq(classroomEnrollments.classroomId, classroom.id),
eq(classroomEnrollments.playerId, playerId)
),
})
return !!enrollment
}
// ---------------------------------------------------------------------------
// Authorization errors (for API responses)
// ---------------------------------------------------------------------------
/**
* Remediation types for authorization errors
*/
export type RemediationType =
| 'send-entry-prompt' // Teacher needs student to enter classroom
| 'enroll-student' // Teacher needs to enroll student first
| 'link-via-family-code' // User can link via family code
| 'create-classroom' // User needs to create a classroom to be a teacher
| 'no-access' // No remediation available
/**
* Structured authorization error for API responses
*/
export interface AuthorizationError {
error: string
message: string
accessLevel: AccessLevel
remediation: {
type: RemediationType
description: string
/** For send-entry-prompt: the classroom to send the prompt from */
classroomId?: string
/** For send-entry-prompt/enroll-student: the player to act on */
playerId?: string
/** Label for the action button in the UI */
actionLabel?: string
}
}
/**
* Generate a personalized authorization error based on the user's relationship
* with the student and the action they're trying to perform.
*/
export function generateAuthorizationError(
access: PlayerAccess,
action: PlayerAction,
context?: { actionDescription?: string }
): AuthorizationError {
const actionDesc = context?.actionDescription ?? action
// Case 1: Teacher with enrolled student, but student not present
// This is the most common case - teacher needs student to enter classroom
if (access.accessLevel === 'teacher-enrolled' && !access.isPresent) {
return {
error: 'Student not in classroom',
message: `This student is enrolled in your classroom but not currently present. To ${actionDesc}, they need to enter your classroom first.`,
accessLevel: access.accessLevel,
remediation: {
type: 'send-entry-prompt',
description:
"Send a notification to the student's parent to have them enter your classroom.",
classroomId: access.classroomId,
playerId: access.playerId,
actionLabel: 'Send Entry Prompt',
},
}
}
// Case 2: User has a classroom but student is not enrolled
if (access.accessLevel === 'none' && access.classroomId) {
return {
error: 'Student not enrolled',
message: 'This student is not enrolled in your classroom.',
accessLevel: access.accessLevel,
remediation: {
type: 'enroll-student',
description:
'You need to enroll this student in your classroom first. Ask their parent for their family code to send an enrollment request.',
classroomId: access.classroomId,
playerId: access.playerId,
actionLabel: 'Enroll Student',
},
}
}
// Case 3: User has no classroom and no parent relationship
if (access.accessLevel === 'none') {
return {
error: 'No access to this student',
message: 'Your account is not linked to this student.',
accessLevel: access.accessLevel,
remediation: {
type: 'link-via-family-code',
description:
"To access this student, you need their Family Code. Ask their parent to share it with you from the student's profile page.",
playerId: access.playerId,
actionLabel: 'Enter Family Code',
},
}
}
// Fallback for any other case
return {
error: 'Not authorized',
message: `You do not have permission to ${actionDesc} for this student.`,
accessLevel: access.accessLevel,
remediation: {
type: 'no-access',
description: "Contact the student's parent or your administrator for access.",
playerId: access.playerId,
},
}
}
|