Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.dev.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Copy to `.env.dev` for machine-local overrides.
SPRING_PROFILES_ACTIVE=dev
APP_BOOTSTRAP_ENABLED=true
APP_SECURITY_JWT_SECRET=replace-with-a-local-dev-secret
APP_SECURITY_CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# Shared local development defaults. Copy to `.env`.
SPRING_PROFILES_ACTIVE=dev
APP_BOOTSTRAP_ENABLED=true
APP_SECURITY_JWT_ISSUER=https://nettdetektivene.local/backend
APP_SECURITY_JWT_AUDIENCE=nettdetektivene-web
APP_SECURITY_JWT_SECRET=change-me-development-secret-change-me-development-secret
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ jobs:
- name: Check out repository
uses: actions/checkout@v4

- name: Set up Java 25
- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '25'
java-version: '21'
cache: gradle

- name: Set up Gradle
Expand Down
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ description = 'backend'

java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
languageVersion = JavaLanguageVersion.of(21)
}
}

Expand Down Expand Up @@ -52,7 +52,7 @@ dependencies {
}

kotlin {
jvmToolchain(25)
jvmToolchain(21)
compilerOptions {
freeCompilerArgs.addAll '-Xjsr305=strict', '-Xannotation-default-target=param-property'
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package edu.ntnu.idi.idatt.backend.bootstrap

import edu.ntnu.idi.idatt.backend.iam.domain.PupilProfile
import edu.ntnu.idi.idatt.backend.iam.domain.RefreshToken
import edu.ntnu.idi.idatt.backend.iam.domain.TeacherProfile
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.domain.UserStatus
import edu.ntnu.idi.idatt.backend.iam.infrastructure.PupilProfileRepository
import edu.ntnu.idi.idatt.backend.iam.infrastructure.RefreshTokenRepository
import edu.ntnu.idi.idatt.backend.iam.infrastructure.TeacherProfileRepository
import edu.ntnu.idi.idatt.backend.iam.infrastructure.UserRepository
import org.slf4j.LoggerFactory
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.HexFormat

/**
* Seeds deterministic development data after Flyway has created the schema.
*
* The runner is idempotent so repeated local startups keep the same sample accounts while filling
* in any missing rows from the current schema.
*/
@Component
@ConditionalOnProperty(name = ["app.bootstrap.enabled"], havingValue = "true")
class DevDataBootstrap(
private val userRepository: UserRepository,
private val teacherProfileRepository: TeacherProfileRepository,
private val pupilProfileRepository: PupilProfileRepository,
private val refreshTokenRepository: RefreshTokenRepository,
private val passwordEncoder: PasswordEncoder,
) : ApplicationRunner {
private val logger = LoggerFactory.getLogger(javaClass)

@Transactional
override fun run(args: ApplicationArguments) {
val admin = seedUser(
email = "admin@nettdetektivene.local",
password = "Admin123!",
role = UserRole.ADMIN,
)
val teacher = seedUser(
email = "teacher@nettdetektivene.local",
password = "Teacher123!",
role = UserRole.TEACHER,
)
val pupilAda = seedUser(
username = "ada",
password = "Pupil123!",
role = UserRole.PUPIL,
)
val pupilNoah = seedUser(
username = "noah",
password = "Pupil123!",
role = UserRole.PUPIL,
)

seedTeacherProfile(teacher, "Ada Lunde", "Trondheim Montessori")
seedPupilProfile(pupilAda, "Ada", 1250, 4, 101)
seedPupilProfile(pupilNoah, "Noah", 420, 2, null)

seedRefreshToken(admin, "dev-admin-refresh-token", Instant.now().plus(14, ChronoUnit.DAYS), null)
seedRefreshToken(
teacher,
"dev-teacher-refresh-token",
Instant.now().plus(14, ChronoUnit.DAYS),
null,
)
seedRefreshToken(
pupilAda,
"dev-pupil-ada-refresh-token",
Instant.now().plus(7, ChronoUnit.DAYS),
null,
)
seedRefreshToken(
pupilNoah,
"dev-pupil-noah-revoked-token",
Instant.now().plus(1, ChronoUnit.DAYS),
Instant.now().minus(1, ChronoUnit.HOURS),
)

logger.info(
"Development bootstrap ensured sample rows for users, profiles, and refresh tokens",
)
}

private fun seedUser(
email: String? = null,
username: String? = null,
password: String,
role: UserRole,
): User {
val existingUser = when {
email != null -> userRepository.findByEmailIgnoreCase(email)
username != null -> userRepository.findByUsernameIgnoreCase(username)
else -> null
}
if (existingUser != null) {
existingUser.email = email
existingUser.username = username
existingUser.passwordHash = requireNotNull(passwordEncoder.encode(password))
existingUser.role = role
existingUser.status = UserStatus.ACTIVE
return existingUser
}

return userRepository.save(
User(
email = email,
username = username,
passwordHash = requireNotNull(passwordEncoder.encode(password)),
role = role,
status = UserStatus.ACTIVE,
),
)
}

private fun seedTeacherProfile(
user: User,
teacherName: String,
schoolName: String,
) {
val userId = requireNotNull(user.id) { "Teacher seed user must have an id" }
if (teacherProfileRepository.existsById(userId)) {
return
}

teacherProfileRepository.save(
TeacherProfile(
user = user,
teacherName = teacherName,
schoolName = schoolName,
),
)
}

private fun seedPupilProfile(
user: User,
displayName: String,
totalXp: Int,
currentLevel: Int,
currentClassroomId: Long?,
) {
val userId = requireNotNull(user.id) { "Pupil seed user must have an id" }
if (pupilProfileRepository.existsById(userId)) {
return
}

pupilProfileRepository.save(
PupilProfile(
user = user,
displayName = displayName,
totalXp = totalXp,
currentLevel = currentLevel,
currentClassroomId = currentClassroomId,
),
)
}

private fun seedRefreshToken(
user: User,
rawToken: String,
expiresAt: Instant,
revokedAt: Instant?,
) {
val tokenHash = hashToken(rawToken)
if (refreshTokenRepository.findByTokenHash(tokenHash) != null) {
return
}

refreshTokenRepository.save(
RefreshToken(
user = user,
tokenHash = tokenHash,
expiresAt = expiresAt,
revokedAt = revokedAt,
),
)
}

private fun hashToken(rawToken: String): String =
HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(rawToken.toByteArray(StandardCharsets.UTF_8)),
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package edu.ntnu.idi.idatt.backend.iam.api

import edu.ntnu.idi.idatt.backend.iam.application.AuthSession
import edu.ntnu.idi.idatt.backend.iam.application.AuthenticatedUser
import edu.ntnu.idi.idatt.backend.iam.application.ChangePasswordCommand
import edu.ntnu.idi.idatt.backend.iam.application.PupilLoginCommand
import edu.ntnu.idi.idatt.backend.iam.application.RegisteredTeacher
import edu.ntnu.idi.idatt.backend.iam.application.TeacherLoginCommand
import edu.ntnu.idi.idatt.backend.iam.application.TeacherRegistrationCommand

/**
* Converts the teacher login request payload to the application command.
*
* @return login command for teacher authentication
*/
fun TeacherLoginRequest.toCommand(): TeacherLoginCommand =
TeacherLoginCommand(
email = email,
password = password,
)

/**
* Converts the teacher registration request payload to the application command.
*
* @return registration command for teacher account creation
*/
fun TeacherRegistrationRequest.toCommand(): TeacherRegistrationCommand =
TeacherRegistrationCommand(
email = email,
password = password,
fullName = fullName,
schoolName = schoolName,
)

/**
* Converts the pupil login request payload to the application command.
*
* @return login command for pupil authentication
*/
fun PupilLoginRequest.toCommand(): PupilLoginCommand =
PupilLoginCommand(
username = username,
password = password,
)

/**
* Converts the internal session representation to the public login response payload.
*
* @return login response exposed by the auth API
*/
fun AuthSession.toLoginResponse(): LoginResponse =
LoginResponse(
accessToken = accessToken,
tokenType = "Bearer",
expiresInSeconds = expiresInSeconds,
refreshHandledViaCookie = true,
portalType = portalType,
user = user?.toAuthenticatedUserResponse(),
)

/**
* Converts a registered teacher result to the public registration response payload.
*
* @return teacher registration response exposed by the auth API
*/
fun RegisteredTeacher.toTeacherRegistrationResponse(): TeacherRegistrationResponse =
TeacherRegistrationResponse(
id = id,
role = role.name,
status = status.name,
)

fun ChangePasswordRequest.toCommand(subject: String): ChangePasswordCommand =
ChangePasswordCommand(
subject = subject,
currentPassword = currentPassword,
newPassword = newPassword,
)

private fun AuthenticatedUser.toAuthenticatedUserResponse(): AuthenticatedUserResponse =
AuthenticatedUserResponse(
subject = subject,
email = email,
)
Loading
Loading