Update so there is an open landing page and a login page

- make / public
- add login on index.html
- add UserAttribute
- add hasRole to RemoteAuthentication
- update HomeController to give welcome instead of index if login.
- add welcome.html
This commit is contained in:
2025-01-20 21:43:36 +01:00
parent 9f6d7066b7
commit 3212226853
6 changed files with 76 additions and 2 deletions

View File

@@ -40,5 +40,6 @@ class SecurityConfiguration {
"/actuator/**",
"/login",
"/logout",
"/",
)
}

View File

@@ -1,13 +1,24 @@
package ltd.hlaeja.controller
import ltd.hlaeja.security.RemoteUserDetail
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import reactor.core.publisher.Mono
@Controller
class HomeController {
@Suppress("UnusedParameter", "FunctionOnlyReturningConstant")
@GetMapping("/")
fun home(model: Model): String = "home/index"
fun home(model: Model): Mono<String> = ReactiveSecurityContextHolder.getContext()
.filter { it.authentication?.isAuthenticated == true }
.map {
(it.authentication.principal as RemoteUserDetail).let { user ->
model.addAttribute("id", user.id)
model.addAttribute("username", user.username)
}
"home/welcome"
}
.defaultIfEmpty("home/index")
}

View File

@@ -0,0 +1,29 @@
package ltd.hlaeja.controller.advice
import java.util.UUID
import kotlinx.coroutines.reactive.awaitFirstOrNull
import ltd.hlaeja.security.RemoteAuthentication
import ltd.hlaeja.security.RemoteUserDetail
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ModelAttribute
@ControllerAdvice
class UserAttribute {
@ModelAttribute
suspend fun remoteUser(model: Model) {
val remoteAuthentication: RemoteAuthentication = ReactiveSecurityContextHolder.getContext()
.awaitFirstOrNull()
?.let { it.authentication as RemoteAuthentication }
?: RemoteAuthentication(
RemoteUserDetail(
UUID.fromString("00000000-0000-0000-0000-000000000000"),
"n/a",
),
mutableListOf(),
)
model.addAttribute("remoteUser", remoteAuthentication)
}
}

View File

@@ -24,4 +24,13 @@ data class RemoteAuthentication(
override fun setAuthenticated(isAuthenticated: Boolean) {
authenticated = isAuthenticated
}
fun hasRole(role: String): Boolean {
authorities.forEach {
if (it.authority.equals("role_$role", true)) {
return true
}
}
return false
}
}