chore: clean up api, add user support
Signed-off-by: Alan Brault <alan.brault@visus.io>
This commit is contained in:
54
src/main/kotlin/io/visus/demos/kotlinapi/seed/DataSeeder.kt
Normal file
54
src/main/kotlin/io/visus/demos/kotlinapi/seed/DataSeeder.kt
Normal file
@@ -0,0 +1,54 @@
|
||||
package io.visus.demos.kotlinapi.seed
|
||||
|
||||
import io.visus.demos.kotlinapi.domain.model.User
|
||||
import io.visus.demos.kotlinapi.infrastructure.user.UserRepository
|
||||
import org.springframework.boot.ApplicationArguments
|
||||
import org.springframework.boot.ApplicationRunner
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
@Component
|
||||
class DataSeeder(
|
||||
private val userRepository: UserRepository,
|
||||
private val passwordEncoder: PasswordEncoder,
|
||||
) : ApplicationRunner {
|
||||
override fun run(args: ApplicationArguments) {
|
||||
seedUser(
|
||||
email = "user@example.com",
|
||||
rawPassword = "user12345",
|
||||
role = "ROLE_USER",
|
||||
)
|
||||
|
||||
seedUser(
|
||||
email = "admin@example.com",
|
||||
rawPassword = "admin12345",
|
||||
role = "ROLE_ADMIN",
|
||||
)
|
||||
}
|
||||
|
||||
private fun seedUser(
|
||||
email: String,
|
||||
rawPassword: String,
|
||||
role: String,
|
||||
) {
|
||||
if (userRepository.findByEmail(email) != null) {
|
||||
println("User '$email' already exists — skipping.")
|
||||
return
|
||||
}
|
||||
|
||||
val hashedPassword =
|
||||
passwordEncoder.encode(rawPassword)
|
||||
?: error("Password encoding returned null")
|
||||
|
||||
val user =
|
||||
User(
|
||||
email = email,
|
||||
passwordHash = hashedPassword,
|
||||
role = role,
|
||||
)
|
||||
|
||||
val saved = userRepository.save(user)
|
||||
val savedId = saved.id ?: "unknown"
|
||||
println("Seeded user '${saved.email}' with id=$savedId and role=${saved.role}")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user