Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package edu.ntnu.idi.idatt.backend.game.application

import edu.ntnu.idi.idatt.backend.classroom.domain.Classroom
import edu.ntnu.idi.idatt.backend.classroom.infrastructure.ClassroomRepository
import edu.ntnu.idi.idatt.backend.iam.application.CurrentUserResolver
import edu.ntnu.idi.idatt.backend.iam.domain.User
import edu.ntnu.idi.idatt.backend.iam.domain.UserRole
import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException

/**
* Resolves classroom-scoped game read capabilities from the authenticated session.
*
* This centralizes the differences between normal pupil access, normal teacher/admin access, and
* read-only teacher preview sessions so map-stop and task endpoints apply consistent rules.
*/
@Service
class GameAccessContextResolver(
private val currentUserResolver: CurrentUserResolver,
private val classroomRepository: ClassroomRepository,
) {
/**
* Resolves the caller's effective read capabilities for one classroom.
*
* @param currentUser authenticated principal from the access token
* @param classroomId classroom being accessed
* @return effective access context for classroom game reads
*/
fun resolveReadContext(
currentUser: CurrentUser,
classroomId: Long,
): GameAccessContext {
val user = currentUserResolver.requireUser(currentUser.subject)
val classroom = classroomRepository.findById(classroomId)
.orElseThrow {
ResponseStatusException(HttpStatus.NOT_FOUND, "Classroom not found")
}
val userId = requireNotNull(user.id) { "Authenticated user is missing an id" }

if (currentUser.isPreviewSession()) {
if (user.role !in setOf(UserRole.TEACHER, UserRole.ADMIN)) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Only teachers and admins may use preview")
}
if (currentUser.previewClassroomId != classroomId) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Preview session is limited to one classroom")
}
if (user.role == UserRole.TEACHER && classroom.ownerTeacherId != userId) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "Only the classroom owner may preview this classroom")
}
return GameAccessContext(
classroom = classroom,
user = user,
pupilUserId = null,
publishedOnly = true,
includeAnswers = true,
allStopsOpen = true,
readOnly = true,
)
}

return when (user.role) {
UserRole.PUPIL -> {
if (!classroom.hasPupilMembership(userId)) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "User does not have access to this classroom")
}
GameAccessContext(
classroom = classroom,
user = user,
pupilUserId = userId,
publishedOnly = true,
includeAnswers = false,
allStopsOpen = false,
readOnly = false,
)
}

UserRole.TEACHER -> {
if (classroom.ownerTeacherId != userId) {
throw ResponseStatusException(HttpStatus.FORBIDDEN, "User does not have access to this classroom")
}
GameAccessContext(
classroom = classroom,
user = user,
pupilUserId = null,
publishedOnly = false,
includeAnswers = true,
allStopsOpen = true,
readOnly = false,
)
}

UserRole.ADMIN -> GameAccessContext(
classroom = classroom,
user = user,
pupilUserId = null,
publishedOnly = false,
includeAnswers = true,
allStopsOpen = true,
readOnly = false,
)
}
}
}

/**
* Effective classroom game-read capabilities for one authenticated request.
*/
data class GameAccessContext(
val classroom: Classroom,
val user: User,
val pupilUserId: Long?,
val publishedOnly: Boolean,
val includeAnswers: Boolean,
val allStopsOpen: Boolean,
val readOnly: Boolean,
)
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class MapStopsController(
@PathVariable classroomId: Long,
): List<MapStopOverviewResponse> =
mapStopService
.getMapOverview(currentUser.subject.toLong(), classroomId)
.getMapOverview(currentUser, classroomId)
.map { it.toResponse() }

/**
Expand All @@ -50,6 +50,6 @@ class MapStopsController(
@PathVariable slug: String,
): MapStopOverviewResponse =
mapStopService
.getMapStopOverviewBySlug(currentUser.subject.toLong(), classroomId, slug)
.getMapStopOverviewBySlug(currentUser, classroomId, slug)
.toResponse()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,17 @@ class PupilStopProgressController(
* @return updated progress record
*/
@PatchMapping("/{stopId}")
@PreAuthorize("#pupilUserId == T(java.lang.Long).parseLong(authentication.principal.subject)")
@PreAuthorize("hasRole('PUPIL') and #pupilUserId == T(java.lang.Long).parseLong(authentication.principal.subject)")
fun updateStopProgress(
@AuthenticationPrincipal currentUser: CurrentUser,
@PathVariable classroomId: Long,
@PathVariable pupilUserId: Long,
@PathVariable stopId: Long,
@Valid @RequestBody request: UpdateStopProgressRequest,
): StopProgressResponse =
progressService
): StopProgressResponse {
currentUserResolver.requirePupil(currentUser.subject)
return progressService
.updateProgress(pupilUserId, classroomId, stopId, request.toCommand())
.toStopProgressResponse()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package edu.ntnu.idi.idatt.backend.game.mapstops.application

import edu.ntnu.idi.idatt.backend.game.application.GameAccessContext
import edu.ntnu.idi.idatt.backend.game.application.GameAccessContextResolver
import edu.ntnu.idi.idatt.backend.game.mapstops.domain.MapStop
import edu.ntnu.idi.idatt.backend.game.mapstops.domain.StopProgressStatus
import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.MapStopsRepository
import edu.ntnu.idi.idatt.backend.game.mapstops.infrastructure.PupilStopProgressRepository
import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
Expand All @@ -18,6 +21,7 @@ import org.springframework.web.server.ResponseStatusException
class MapStopService(
private val mapStopsRepository: MapStopsRepository,
private val pupilStopProgressRepository: PupilStopProgressRepository,
private val gameAccessContextResolver: GameAccessContextResolver,
) {
/**
* Returns all active map stops sorted by display order.
Expand All @@ -36,6 +40,7 @@ class MapStopService(
*/
fun getMapStopBySlug(slug: String): MapStop {
return mapStopsRepository.findBySlugIgnoreCase(slug)
?.takeIf { it.isActive == true }
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "No map stop found for slug: $slug")
}

Expand All @@ -47,10 +52,14 @@ class MapStopService(
* @param classroomId classroom to scope the progress lookup to
* @return sorted list of stops with progress state for the pupil
*/
fun getMapOverview(pupilUserId: Long, classroomId: Long): List<MapStopOverviewEntry> {
fun getMapOverview(currentUser: CurrentUser, classroomId: Long): List<MapStopOverviewEntry> {
val accessContext = gameAccessContextResolver.resolveReadContext(currentUser, classroomId)
val stops = mapStopsRepository.findAllByIsActiveTrueOrderByDisplayOrderAsc()
if (accessContext.allStopsOpen || accessContext.pupilUserId == null) {
return stops.mapNotNull { stop -> stop.toOpenOverviewEntry() }
}
val progressByStopId = pupilStopProgressRepository
.findAllByIdPupilUserIdAndIdClassroomId(pupilUserId, classroomId)
.findAllByIdPupilUserIdAndIdClassroomId(accessContext.pupilUserId, classroomId)
.associateBy { it.id.stopId }

return stops.mapNotNull { stop ->
Expand Down Expand Up @@ -79,13 +88,21 @@ class MapStopService(
* @return map stop matching the given slug with progress state for the pupil
* @throws ResponseStatusException 404 if no stop matches the slug
*/
fun getMapStopOverviewBySlug(pupilUserId: Long, classroomId: Long, slug: String): MapStopOverviewEntry {
fun getMapStopOverviewBySlug(
currentUser: CurrentUser,
classroomId: Long,
slug: String,
): MapStopOverviewEntry {
val accessContext = gameAccessContextResolver.resolveReadContext(currentUser, classroomId)
val stop = getMapStopBySlug(slug)
if (accessContext.allStopsOpen || accessContext.pupilUserId == null) {
return stop.toOpenOverviewEntry()
}
val stopId = stop.id
?: throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Map stop has no id")

val progress = pupilStopProgressRepository
.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(pupilUserId, classroomId, stopId)
.findByIdPupilUserIdAndIdClassroomIdAndIdStopId(accessContext.pupilUserId, classroomId, stopId)

return MapStopOverviewEntry(
stopId = stopId,
Expand All @@ -112,6 +129,31 @@ class MapStopService(
}
}

private fun MapStop.toOpenOverviewEntry(): MapStopOverviewEntry {
val stopId = id ?: return MapStopOverviewEntry(
stopId = 0,
slug = slug,
title = title,
category = category,
displayOrder = displayOrder ?: 0,
isFinalBoss = isFinalBoss ?: false,
status = StopProgressStatus.NOT_STARTED,
stars = 0,
medalAwarded = false,
)
return MapStopOverviewEntry(
stopId = stopId,
slug = slug,
title = title,
category = category,
displayOrder = displayOrder ?: 0,
isFinalBoss = isFinalBoss ?: false,
status = StopProgressStatus.NOT_STARTED,
stars = 0,
medalAwarded = false,
)
}

/**
* Aggregated view of a map stop enriched with a pupil's current progress state.
*
Expand All @@ -135,4 +177,4 @@ data class MapStopOverviewEntry(
val status: StopProgressStatus,
val stars: Int,
val medalAwarded: Boolean,
)
)
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class TaskController(
@RequestParam(required = false) stopId: Long?,
@AuthenticationPrincipal currentUser: CurrentUser,
): List<TaskSummaryResponse> =
taskService.listTasks(currentUser.subject, classroomId, stopId).map { it.toResponse() }
taskService.listTasks(currentUser, classroomId, stopId).map { it.toResponse() }

/**
* Returns the full contents of one task.
Expand All @@ -48,8 +48,8 @@ class TaskController(
@AuthenticationPrincipal currentUser: CurrentUser,
): TaskResponse =
taskService
.getTask(currentUser.subject, classroomId, taskId)
.toResponse(includeAnswers = currentUser.portalType != "PUPIL")
.getTask(currentUser, classroomId, taskId)
.let { it.task.toResponse(includeAnswers = it.includeAnswers) }

/**
* Creates a new draft task owned by the classroom's teacher.
Expand All @@ -61,7 +61,7 @@ class TaskController(
@RequestBody @Valid request: CreateTaskRequest,
@AuthenticationPrincipal currentUser: CurrentUser,
): TaskResponse =
taskService.createTask(request.toCommand(classroomId, currentUser.subject)).toResponse()
taskService.createTask(request.toCommand(classroomId, currentUser)).toResponse()

/**
* Replaces the editable contents of an existing task.
Expand All @@ -73,7 +73,7 @@ class TaskController(
@RequestBody @Valid request: UpdateTaskRequest,
@AuthenticationPrincipal currentUser: CurrentUser,
): TaskResponse =
taskService.updateTask(request.toCommand(classroomId, taskId, currentUser.subject)).toResponse()
taskService.updateTask(request.toCommand(classroomId, taskId, currentUser)).toResponse()

/**
* Publishes or unpublishes a task.
Expand All @@ -85,7 +85,7 @@ class TaskController(
@RequestBody request: UpdateTaskPublishStateRequest,
@AuthenticationPrincipal currentUser: CurrentUser,
): TaskResponse =
taskService.updatePublishState(currentUser.subject, classroomId, taskId, request.published).toResponse()
taskService.updatePublishState(currentUser, classroomId, taskId, request.published).toResponse()

/**
* Deletes a task from the classroom.
Expand All @@ -97,6 +97,6 @@ class TaskController(
@PathVariable taskId: Long,
@AuthenticationPrincipal currentUser: CurrentUser,
) {
taskService.deleteTask(currentUser.subject, classroomId, taskId)
taskService.deleteTask(currentUser, classroomId, taskId)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import edu.ntnu.idi.idatt.backend.game.tasks.application.ReplaceTaskOptionComman
import edu.ntnu.idi.idatt.backend.game.tasks.application.UpdateTaskCommand
import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskPassingRule
import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskType
import edu.ntnu.idi.idatt.backend.iam.security.CurrentUser
import jakarta.validation.Valid
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.NotBlank
Expand Down Expand Up @@ -122,10 +123,11 @@ data class UpdateTaskPublishStateRequest(
*/
fun CreateTaskRequest.toCommand(
classroomId: Long,
authenticatedSubject: String,
currentUser: CurrentUser,
): CreateTaskCommand =
CreateTaskCommand(
authenticatedSubject = authenticatedSubject,
authenticatedSubject = currentUser.subject,
sessionMode = currentUser.sessionMode,
classroomId = classroomId,
stopId = stopId,
title = title.toLocalizedText(),
Expand All @@ -144,10 +146,11 @@ fun CreateTaskRequest.toCommand(
fun UpdateTaskRequest.toCommand(
classroomId: Long,
taskId: Long,
authenticatedSubject: String,
currentUser: CurrentUser,
): UpdateTaskCommand =
UpdateTaskCommand(
authenticatedSubject = authenticatedSubject,
authenticatedSubject = currentUser.subject,
sessionMode = currentUser.sessionMode,
classroomId = classroomId,
taskId = taskId,
stopId = stopId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package edu.ntnu.idi.idatt.backend.game.tasks.application

import edu.ntnu.idi.idatt.backend.iam.application.SessionMode
import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskPassingRule
import edu.ntnu.idi.idatt.backend.game.tasks.domain.TaskType
import java.time.Instant
Expand Down Expand Up @@ -46,6 +47,7 @@ data class ReplaceTaskItemCommand(
*/
data class CreateTaskCommand(
val authenticatedSubject: String,
val sessionMode: SessionMode,
val classroomId: Long,
val stopId: Long,
val title: LocalizedText,
Expand All @@ -63,6 +65,7 @@ data class CreateTaskCommand(
*/
data class UpdateTaskCommand(
val authenticatedSubject: String,
val sessionMode: SessionMode,
val classroomId: Long,
val taskId: Long,
val stopId: Long,
Expand Down Expand Up @@ -120,6 +123,14 @@ data class TaskDetails(
val items: List<TaskItemDetails>,
)

/**
* Task read result bundled with the caller's answer-visibility capability.
*/
data class TaskReadResult(
val task: TaskDetails,
val includeAnswers: Boolean,
)

/**
* Lightweight task projection used by list endpoints.
*/
Expand Down
Loading