Fix auth verify access and token fallback
All checks were successful
build-and-deploy / build-deploy (push) Successful in 27s
All checks were successful
build-and-deploy / build-deploy (push) Successful in 27s
This commit is contained in:
@@ -5,6 +5,8 @@ import com.android.trisolarisserver.controller.dto.UserResponse
|
||||
import com.android.trisolarisserver.repo.AppUserRepo
|
||||
import com.android.trisolarisserver.repo.PropertyUserRepo
|
||||
import com.android.trisolarisserver.security.MyPrincipal
|
||||
import com.google.firebase.auth.FirebaseAuth
|
||||
import jakarta.servlet.http.HttpServletRequest
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
@@ -21,13 +23,19 @@ class Auth(
|
||||
) {
|
||||
|
||||
@PostMapping("/verify")
|
||||
fun verify(@AuthenticationPrincipal principal: MyPrincipal?): AuthResponse {
|
||||
return buildAuthResponse(principal)
|
||||
fun verify(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
request: HttpServletRequest
|
||||
): AuthResponse {
|
||||
return buildAuthResponse(principal ?: resolvePrincipalFromHeader(request))
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
fun me(@AuthenticationPrincipal principal: MyPrincipal?): AuthResponse {
|
||||
return buildAuthResponse(principal)
|
||||
fun me(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
request: HttpServletRequest
|
||||
): AuthResponse {
|
||||
return buildAuthResponse(principal ?: resolvePrincipalFromHeader(request))
|
||||
}
|
||||
|
||||
private fun buildAuthResponse(principal: MyPrincipal?): AuthResponse {
|
||||
@@ -56,6 +64,28 @@ class Auth(
|
||||
properties = memberships
|
||||
)
|
||||
}
|
||||
|
||||
private fun resolvePrincipalFromHeader(request: HttpServletRequest): MyPrincipal {
|
||||
val header = request.getHeader("Authorization") ?: throw ResponseStatusException(
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
"Missing Authorization token"
|
||||
)
|
||||
if (!header.startsWith("Bearer ")) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Authorization header")
|
||||
}
|
||||
val token = header.removePrefix("Bearer ").trim()
|
||||
val decoded = try {
|
||||
FirebaseAuth.getInstance().verifyIdToken(token)
|
||||
} catch (ex: Exception) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid token")
|
||||
}
|
||||
val user = appUserRepo.findByFirebaseUid(decoded.uid)
|
||||
?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found")
|
||||
return MyPrincipal(
|
||||
userId = user.id ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "User id missing"),
|
||||
firebaseUid = decoded.uid
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
data class AuthResponse(
|
||||
|
||||
Reference in New Issue
Block a user