Deduplicate logic across controllers, auth, and schema fixes
All checks were successful
build-and-deploy / build-deploy (push) Successful in 33s
All checks were successful
build-and-deploy / build-deploy (push) Successful in 33s
This commit is contained in:
@@ -5,7 +5,6 @@ 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.slf4j.LoggerFactory
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
@@ -19,12 +18,14 @@ import org.springframework.web.server.ResponseStatusException
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.http.ResponseEntity
|
||||
import java.util.UUID
|
||||
import com.android.trisolarisserver.security.AuthResolver
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
class Auth(
|
||||
private val appUserRepo: AppUserRepo,
|
||||
private val propertyUserRepo: PropertyUserRepo
|
||||
private val propertyUserRepo: PropertyUserRepo,
|
||||
private val authResolver: AuthResolver
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(Auth::class.java)
|
||||
|
||||
@@ -34,7 +35,8 @@ class Auth(
|
||||
request: HttpServletRequest
|
||||
): ResponseEntity<AuthResponse> {
|
||||
logger.info("Auth verify hit, principalPresent={}", principal != null)
|
||||
val resolved = principal?.let { ResolveResult(it) } ?: resolvePrincipalFromHeader(request)
|
||||
val resolved = principal?.let { ResolveResult(it) }
|
||||
?: ResolveResult(authResolver.resolveFromRequest(request, createIfMissing = true))
|
||||
return resolved.toResponseEntity()
|
||||
}
|
||||
|
||||
@@ -43,7 +45,8 @@ class Auth(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
request: HttpServletRequest
|
||||
): ResponseEntity<AuthResponse> {
|
||||
val resolved = principal?.let { ResolveResult(it) } ?: resolvePrincipalFromHeader(request)
|
||||
val resolved = principal?.let { ResolveResult(it) }
|
||||
?: ResolveResult(authResolver.resolveFromRequest(request, createIfMissing = true))
|
||||
return resolved.toResponseEntity()
|
||||
}
|
||||
|
||||
@@ -53,7 +56,8 @@ class Auth(
|
||||
request: HttpServletRequest,
|
||||
@RequestBody body: UpdateMeRequest
|
||||
): ResponseEntity<AuthResponse> {
|
||||
val resolved = principal?.let { ResolveResult(it) } ?: resolvePrincipalFromHeader(request)
|
||||
val resolved = principal?.let { ResolveResult(it) }
|
||||
?: ResolveResult(authResolver.resolveFromRequest(request, createIfMissing = true))
|
||||
if (resolved.principal == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(AuthResponse(status = "UNAUTHORIZED"))
|
||||
@@ -98,46 +102,6 @@ class Auth(
|
||||
)
|
||||
}
|
||||
|
||||
private fun resolvePrincipalFromHeader(request: HttpServletRequest): ResolveResult {
|
||||
val header = request.getHeader("Authorization") ?: throw ResponseStatusException(
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
"Missing Authorization token"
|
||||
)
|
||||
if (!header.startsWith("Bearer ")) {
|
||||
logger.warn("Auth verify invalid Authorization header")
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Authorization header")
|
||||
}
|
||||
val token = header.removePrefix("Bearer ").trim()
|
||||
val decoded = try {
|
||||
FirebaseAuth.getInstance().verifyIdToken(token)
|
||||
} catch (ex: Exception) {
|
||||
logger.warn("Auth verify failed: {}", ex.message)
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid token")
|
||||
}
|
||||
val user = appUserRepo.findByFirebaseUid(decoded.uid) ?: run {
|
||||
val phone = decoded.claims["phone_number"] as? String
|
||||
val name = decoded.claims["name"] as? String
|
||||
val makeSuperAdmin = appUserRepo.count() == 0L
|
||||
val created = appUserRepo.save(
|
||||
com.android.trisolarisserver.models.property.AppUser(
|
||||
firebaseUid = decoded.uid,
|
||||
phoneE164 = phone,
|
||||
name = name,
|
||||
superAdmin = makeSuperAdmin
|
||||
)
|
||||
)
|
||||
logger.warn("Auth verify auto-created user uid={}, userId={}", decoded.uid, created.id)
|
||||
created
|
||||
}
|
||||
logger.warn("Auth verify resolved uid={}, userId={}", decoded.uid, user.id)
|
||||
return ResolveResult(
|
||||
MyPrincipal(
|
||||
userId = user.id ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "User id missing"),
|
||||
firebaseUid = decoded.uid
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun ResolveResult.toResponseEntity(): ResponseEntity<AuthResponse> {
|
||||
return if (principal == null) {
|
||||
ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
|
||||
@@ -232,23 +232,12 @@ class BookingFlow(
|
||||
}
|
||||
|
||||
private fun requireActor(propertyId: UUID, principal: MyPrincipal?): com.android.trisolarisserver.models.property.AppUser {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER, Role.STAFF)
|
||||
return appUserRepo.findById(principal.userId).orElseThrow {
|
||||
val resolved = requireRole(propertyAccess, propertyId, principal, Role.ADMIN, Role.MANAGER, Role.STAFF)
|
||||
return appUserRepo.findById(resolved.userId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found")
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseOffset(value: String?): OffsetDateTime? {
|
||||
if (value.isNullOrBlank()) return null
|
||||
return try {
|
||||
OffsetDateTime.parse(value.trim())
|
||||
} catch (_: Exception) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseTransportMode(value: String): TransportMode {
|
||||
return try {
|
||||
TransportMode.valueOf(value)
|
||||
@@ -269,9 +258,4 @@ class BookingFlow(
|
||||
return allowed.contains(mode)
|
||||
}
|
||||
|
||||
private fun requirePrincipal(principal: MyPrincipal?) {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.android.trisolarisserver.controller
|
||||
|
||||
import java.time.OffsetDateTime
|
||||
|
||||
internal fun encodeBlock(value: String?): String {
|
||||
val raw = (value ?: "").padEnd(16).take(16)
|
||||
val bytes = raw.toByteArray(Charsets.UTF_8)
|
||||
val sb = StringBuilder(bytes.size * 2)
|
||||
for (b in bytes) {
|
||||
sb.append(String.format("%02X", b))
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
internal fun buildSector0Block2(roomNumber: Int, cardID: Int): String {
|
||||
val guestID = cardID + 1
|
||||
val cardIdStr = cardID.toString().padStart(6, '0')
|
||||
val guestIdStr = guestID.toString().padStart(6, '0')
|
||||
val finalRoom = roomNumber.toString().padStart(2, '0')
|
||||
return "472F${cardIdStr}2F${guestIdStr}00010000${finalRoom}0000"
|
||||
}
|
||||
|
||||
internal fun formatDateComponents(time: OffsetDateTime): String {
|
||||
val minute = time.minute.toString().padStart(2, '0')
|
||||
val hour = time.hour.toString().padStart(2, '0')
|
||||
val day = time.dayOfMonth.toString().padStart(2, '0')
|
||||
val month = time.monthValue.toString().padStart(2, '0')
|
||||
val year = time.year.toString().takeLast(2)
|
||||
return "${minute}${hour}${day}${month}${year}"
|
||||
}
|
||||
|
||||
internal fun calculateChecksum(dataHex: String): String {
|
||||
val data = hexStringToByteArray(dataHex)
|
||||
var checksum = 0
|
||||
for (byte in data) {
|
||||
checksum = calculateByteChecksum(byte, checksum)
|
||||
}
|
||||
return String.format("%02X", checksum)
|
||||
}
|
||||
|
||||
private fun calculateByteChecksum(byte: Byte, currentChecksum: Int): Int {
|
||||
var checksum = currentChecksum
|
||||
var b = byte.toInt()
|
||||
for (i in 0 until 8) {
|
||||
checksum = if ((checksum xor b) and 1 != 0) {
|
||||
(checksum xor 0x18) shr 1 or 0x80
|
||||
} else {
|
||||
checksum shr 1
|
||||
}
|
||||
b = b shr 1
|
||||
}
|
||||
return checksum
|
||||
}
|
||||
|
||||
private fun hexStringToByteArray(hexString: String): ByteArray {
|
||||
val len = hexString.length
|
||||
val data = ByteArray(len / 2)
|
||||
for (i in 0 until len step 2) {
|
||||
data[i / 2] = ((Character.digit(hexString[i], 16) shl 4)
|
||||
+ Character.digit(hexString[i + 1], 16)).toByte()
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.android.trisolarisserver.controller
|
||||
|
||||
import com.android.trisolarisserver.component.PropertyAccess
|
||||
import com.android.trisolarisserver.models.property.AppUser
|
||||
import com.android.trisolarisserver.models.property.Role
|
||||
import com.android.trisolarisserver.repo.AppUserRepo
|
||||
import com.android.trisolarisserver.security.MyPrincipal
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.web.server.ResponseStatusException
|
||||
import java.util.UUID
|
||||
|
||||
internal fun requirePrincipal(principal: MyPrincipal?): MyPrincipal {
|
||||
return principal ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
|
||||
internal fun requireUser(appUserRepo: AppUserRepo, principal: MyPrincipal?): AppUser {
|
||||
val resolved = requirePrincipal(principal)
|
||||
return appUserRepo.findById(resolved.userId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun requireMember(
|
||||
propertyAccess: PropertyAccess,
|
||||
propertyId: UUID,
|
||||
principal: MyPrincipal?
|
||||
): MyPrincipal {
|
||||
val resolved = requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, resolved.userId)
|
||||
return resolved
|
||||
}
|
||||
|
||||
internal fun requireRole(
|
||||
propertyAccess: PropertyAccess,
|
||||
propertyId: UUID,
|
||||
principal: MyPrincipal?,
|
||||
vararg roles: Role
|
||||
): MyPrincipal {
|
||||
val resolved = requireMember(propertyAccess, propertyId, principal)
|
||||
propertyAccess.requireAnyRole(propertyId, resolved.userId, *roles)
|
||||
return resolved
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.android.trisolarisserver.controller
|
||||
|
||||
import com.android.trisolarisserver.db.repo.GuestRepo
|
||||
import com.android.trisolarisserver.models.booking.Guest
|
||||
import com.android.trisolarisserver.models.property.Property
|
||||
import com.android.trisolarisserver.models.room.RoomStay
|
||||
import com.android.trisolarisserver.repo.PropertyRepo
|
||||
import com.android.trisolarisserver.repo.RoomStayRepo
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.web.server.ResponseStatusException
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
import java.util.UUID
|
||||
|
||||
internal data class PropertyGuest(
|
||||
val property: Property,
|
||||
val guest: Guest
|
||||
)
|
||||
|
||||
internal fun requireProperty(propertyRepo: PropertyRepo, propertyId: UUID): Property {
|
||||
return propertyRepo.findById(propertyId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Property not found")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun requirePropertyGuest(
|
||||
propertyRepo: PropertyRepo,
|
||||
guestRepo: GuestRepo,
|
||||
propertyId: UUID,
|
||||
guestId: UUID
|
||||
): PropertyGuest {
|
||||
val property = requireProperty(propertyRepo, propertyId)
|
||||
val guest = guestRepo.findById(guestId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Guest not found")
|
||||
}
|
||||
if (guest.property.id != property.id) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Guest not in property")
|
||||
}
|
||||
return PropertyGuest(property, guest)
|
||||
}
|
||||
|
||||
internal fun requireRoomStayForProperty(
|
||||
roomStayRepo: RoomStayRepo,
|
||||
propertyId: UUID,
|
||||
roomStayId: UUID
|
||||
): RoomStay {
|
||||
val stay = roomStayRepo.findById(roomStayId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found")
|
||||
}
|
||||
if (stay.property.id != propertyId) {
|
||||
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found for property")
|
||||
}
|
||||
return stay
|
||||
}
|
||||
|
||||
internal fun requireOpenRoomStayForProperty(
|
||||
roomStayRepo: RoomStayRepo,
|
||||
propertyId: UUID,
|
||||
roomStayId: UUID,
|
||||
closedMessage: String
|
||||
): RoomStay {
|
||||
val stay = requireRoomStayForProperty(roomStayRepo, propertyId, roomStayId)
|
||||
if (stay.toAt != null) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, closedMessage)
|
||||
}
|
||||
return stay
|
||||
}
|
||||
|
||||
internal fun parseOffset(value: String?): OffsetDateTime? {
|
||||
if (value.isNullOrBlank()) return null
|
||||
return try {
|
||||
OffsetDateTime.parse(value.trim())
|
||||
} catch (_: Exception) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun nowForProperty(timezone: String?): OffsetDateTime {
|
||||
val zone = try {
|
||||
if (timezone.isNullOrBlank()) ZoneId.of("Asia/Kolkata") else ZoneId.of(timezone)
|
||||
} catch (_: Exception) {
|
||||
ZoneId.of("Asia/Kolkata")
|
||||
}
|
||||
return OffsetDateTime.now(zone)
|
||||
}
|
||||
@@ -53,7 +53,7 @@ class GuestDocuments(
|
||||
@RequestParam("bookingId") bookingId: UUID,
|
||||
@RequestPart("file") file: MultipartFile
|
||||
): GuestDocumentResponse {
|
||||
val user = requireUser(principal)
|
||||
val user = requireUser(appUserRepo, principal)
|
||||
propertyAccess.requireMember(propertyId, user.id!!)
|
||||
propertyAccess.requireAnyRole(propertyId, user.id!!, Role.ADMIN, Role.MANAGER)
|
||||
|
||||
@@ -65,15 +65,7 @@ class GuestDocuments(
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Video files are not allowed")
|
||||
}
|
||||
|
||||
val property = propertyRepo.findById(propertyId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Property not found")
|
||||
}
|
||||
val guest = guestRepo.findById(guestId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Guest not found")
|
||||
}
|
||||
if (guest.property.id != property.id) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Guest not in property")
|
||||
}
|
||||
val (property, guest) = requirePropertyGuest(propertyRepo, guestRepo, propertyId, guestId)
|
||||
val booking = bookingRepo.findById(bookingId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Booking not found")
|
||||
}
|
||||
@@ -106,9 +98,7 @@ class GuestDocuments(
|
||||
@PathVariable guestId: UUID,
|
||||
@AuthenticationPrincipal principal: MyPrincipal?
|
||||
): List<GuestDocumentResponse> {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
requireRole(propertyAccess, propertyId, principal, Role.ADMIN, Role.MANAGER)
|
||||
|
||||
return guestDocumentRepo
|
||||
.findByPropertyIdAndGuestIdOrderByUploadedAtDesc(propertyId, guestId)
|
||||
@@ -124,9 +114,7 @@ class GuestDocuments(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?
|
||||
): ResponseEntity<FileSystemResource> {
|
||||
if (token == null) {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
requireRole(propertyAccess, propertyId, principal, Role.ADMIN, Role.MANAGER)
|
||||
} else if (!tokenService.validateToken(token, documentId.toString())) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid token")
|
||||
}
|
||||
@@ -207,20 +195,6 @@ class GuestDocuments(
|
||||
}
|
||||
}
|
||||
|
||||
private fun requirePrincipal(principal: MyPrincipal?) {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
}
|
||||
|
||||
private fun requireUser(principal: MyPrincipal?): com.android.trisolarisserver.models.property.AppUser {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
return appUserRepo.findById(principal.userId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class GuestDocumentResponse(
|
||||
|
||||
@@ -42,18 +42,9 @@ class GuestRatings(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
@RequestBody request: GuestRatingCreateRequest
|
||||
): GuestRatingResponse {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
val resolved = requireMember(propertyAccess, propertyId, principal)
|
||||
|
||||
val property = propertyRepo.findById(propertyId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Property not found")
|
||||
}
|
||||
val guest = guestRepo.findById(guestId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Guest not found")
|
||||
}
|
||||
if (guest.property.id != property.id) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Guest not in property")
|
||||
}
|
||||
val (property, guest) = requirePropertyGuest(propertyRepo, guestRepo, propertyId, guestId)
|
||||
|
||||
val booking = bookingRepo.findById(request.bookingId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Booking not found")
|
||||
@@ -75,7 +66,7 @@ class GuestRatings(
|
||||
booking = booking,
|
||||
score = score,
|
||||
notes = request.notes?.trim(),
|
||||
createdBy = appUserRepo.findById(principal.userId).orElse(null)
|
||||
createdBy = appUserRepo.findById(resolved.userId).orElse(null)
|
||||
)
|
||||
guestRatingRepo.save(rating)
|
||||
return rating.toResponse()
|
||||
@@ -87,18 +78,9 @@ class GuestRatings(
|
||||
@PathVariable guestId: UUID,
|
||||
@AuthenticationPrincipal principal: MyPrincipal?
|
||||
): List<GuestRatingResponse> {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
requireMember(propertyAccess, propertyId, principal)
|
||||
|
||||
val property = propertyRepo.findById(propertyId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Property not found")
|
||||
}
|
||||
val guest = guestRepo.findById(guestId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Guest not found")
|
||||
}
|
||||
if (guest.property.id != property.id) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Guest not in property")
|
||||
}
|
||||
val (_, guest) = requirePropertyGuest(propertyRepo, guestRepo, propertyId, guestId)
|
||||
|
||||
return guestRatingRepo.findByGuestIdOrderByCreatedAtDesc(guestId).map { it.toResponse() }
|
||||
}
|
||||
@@ -126,9 +108,4 @@ class GuestRatings(
|
||||
)
|
||||
}
|
||||
|
||||
private fun requirePrincipal(principal: MyPrincipal?) {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,16 +33,13 @@ class Guests(
|
||||
@RequestParam(required = false) phone: String?,
|
||||
@RequestParam(required = false) vehicleNumber: String?
|
||||
): List<GuestResponse> {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
requireMember(propertyAccess, propertyId, principal)
|
||||
|
||||
if (phone.isNullOrBlank() && vehicleNumber.isNullOrBlank()) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "phone or vehicleNumber required")
|
||||
}
|
||||
|
||||
val property = propertyRepo.findById(propertyId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Property not found")
|
||||
}
|
||||
requireProperty(propertyRepo, propertyId)
|
||||
|
||||
val guests = mutableSetOf<Guest>()
|
||||
if (!phone.isNullOrBlank()) {
|
||||
@@ -64,18 +61,9 @@ class Guests(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
@RequestBody request: GuestVehicleRequest
|
||||
): GuestResponse {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
requireMember(propertyAccess, propertyId, principal)
|
||||
|
||||
val property = propertyRepo.findById(propertyId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Property not found")
|
||||
}
|
||||
val guest = guestRepo.findById(guestId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Guest not found")
|
||||
}
|
||||
if (guest.property.id != property.id) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Guest not in property")
|
||||
}
|
||||
val (property, guest) = requirePropertyGuest(propertyRepo, guestRepo, propertyId, guestId)
|
||||
if (guestVehicleRepo.existsByPropertyIdAndVehicleNumberIgnoreCase(property.id!!, request.vehicleNumber)) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "Vehicle number already exists")
|
||||
}
|
||||
@@ -89,11 +77,6 @@ class Guests(
|
||||
return setOf(guest).toResponse(guestVehicleRepo, guestRatingRepo).first()
|
||||
}
|
||||
|
||||
private fun requirePrincipal(principal: MyPrincipal?) {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Set<Guest>.toResponse(
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.android.trisolarisserver.controller
|
||||
|
||||
import com.android.trisolarisserver.controller.dto.IssuedCardResponse
|
||||
import com.android.trisolarisserver.models.room.IssuedCard
|
||||
|
||||
internal fun IssuedCard.toResponse(): IssuedCardResponse {
|
||||
return IssuedCardResponse(
|
||||
id = id!!,
|
||||
propertyId = property.id!!,
|
||||
roomId = room.id!!,
|
||||
roomStayId = roomStay?.id,
|
||||
cardId = cardId,
|
||||
cardIndex = cardIndex,
|
||||
issuedAt = issuedAt.toString(),
|
||||
expiresAt = expiresAt.toString(),
|
||||
issuedByUserId = issuedBy?.id,
|
||||
revokedAt = revokedAt?.toString()
|
||||
)
|
||||
}
|
||||
@@ -26,7 +26,6 @@ import org.springframework.web.bind.annotation.ResponseStatus
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import org.springframework.web.server.ResponseStatusException
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
import java.util.UUID
|
||||
|
||||
@RestController
|
||||
@@ -50,15 +49,7 @@ class IssuedCards(
|
||||
@RequestBody request: CardPrepareRequest
|
||||
): CardPrepareResponse {
|
||||
val actor = requireIssueActor(propertyId, principal)
|
||||
val stay = roomStayRepo.findById(roomStayId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found")
|
||||
}
|
||||
if (stay.property.id != propertyId) {
|
||||
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found for property")
|
||||
}
|
||||
if (stay.toAt != null) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "Room stay closed")
|
||||
}
|
||||
val stay = requireOpenRoomStayForProperty(roomStayRepo, propertyId, roomStayId, "Room stay closed")
|
||||
|
||||
val issuedAt = nowForProperty(stay.property.timezone)
|
||||
val expiresAt = request.expiresAt?.let { parseOffset(it) } ?: stay.toAt
|
||||
@@ -97,15 +88,7 @@ class IssuedCards(
|
||||
if (request.cardIndex <= 0) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "cardIndex required")
|
||||
}
|
||||
val stay = roomStayRepo.findById(roomStayId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found")
|
||||
}
|
||||
if (stay.property.id != propertyId) {
|
||||
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found for property")
|
||||
}
|
||||
if (stay.toAt != null) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "Room stay closed")
|
||||
}
|
||||
val stay = requireOpenRoomStayForProperty(roomStayRepo, propertyId, roomStayId, "Room stay closed")
|
||||
val issuedAt = parseOffset(request.issuedAt) ?: nowForProperty(stay.property.timezone)
|
||||
val expiresAt = parseOffset(request.expiresAt)
|
||||
?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "expiresAt required")
|
||||
@@ -140,12 +123,7 @@ class IssuedCards(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?
|
||||
): List<IssuedCardResponse> {
|
||||
requireViewActor(propertyId, principal)
|
||||
val stay = roomStayRepo.findById(roomStayId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found")
|
||||
}
|
||||
if (stay.property.id != propertyId) {
|
||||
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found for property")
|
||||
}
|
||||
val stay = requireRoomStayForProperty(roomStayRepo, propertyId, roomStayId)
|
||||
return issuedCardRepo.findByRoomStayIdOrderByIssuedAtDesc(roomStayId)
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
@@ -183,34 +161,6 @@ class IssuedCards(
|
||||
return card.toResponse()
|
||||
}
|
||||
|
||||
private fun parseOffset(value: String?): OffsetDateTime? {
|
||||
if (value.isNullOrBlank()) return null
|
||||
return try {
|
||||
OffsetDateTime.parse(value.trim())
|
||||
} catch (_: Exception) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
private fun nowForProperty(timezone: String?): OffsetDateTime {
|
||||
val zone = try {
|
||||
if (timezone.isNullOrBlank()) ZoneId.of("Asia/Kolkata") else ZoneId.of(timezone)
|
||||
} catch (_: Exception) {
|
||||
ZoneId.of("Asia/Kolkata")
|
||||
}
|
||||
return OffsetDateTime.now(zone)
|
||||
}
|
||||
|
||||
private fun encodeBlock(value: String?): String {
|
||||
val raw = (value ?: "").padEnd(16).take(16)
|
||||
val bytes = raw.toByteArray(Charsets.UTF_8)
|
||||
val sb = StringBuilder(bytes.size * 2)
|
||||
for (b in bytes) {
|
||||
sb.append(String.format("%02X", b))
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
private fun requireMember(propertyId: UUID, principal: MyPrincipal?) {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
@@ -303,73 +253,9 @@ class IssuedCards(
|
||||
val checkSum = calculateChecksum((key ?: "") + newData)
|
||||
return newData + checkSum
|
||||
}
|
||||
|
||||
private fun buildSector0Block2(roomNumber: Int, cardID: Int): String {
|
||||
val guestID = cardID + 1
|
||||
val cardIdStr = cardID.toString().padStart(6, '0')
|
||||
val guestIdStr = guestID.toString().padStart(6, '0')
|
||||
val finalRoom = roomNumber.toString().padStart(2, '0')
|
||||
return "472F${cardIdStr}2F${guestIdStr}00010000${finalRoom}0000"
|
||||
}
|
||||
|
||||
private fun formatDateComponents(time: OffsetDateTime): String {
|
||||
val minute = time.minute.toString().padStart(2, '0')
|
||||
val hour = time.hour.toString().padStart(2, '0')
|
||||
val day = time.dayOfMonth.toString().padStart(2, '0')
|
||||
val month = time.monthValue.toString().padStart(2, '0')
|
||||
val year = time.year.toString().takeLast(2)
|
||||
return "${minute}${hour}${day}${month}${year}"
|
||||
}
|
||||
|
||||
private fun calculateChecksum(dataHex: String): String {
|
||||
val data = hexStringToByteArray(dataHex)
|
||||
var checksum = 0
|
||||
for (byte in data) {
|
||||
checksum = calculateByteChecksum(byte, checksum)
|
||||
}
|
||||
return String.format("%02X", checksum)
|
||||
}
|
||||
|
||||
private fun calculateByteChecksum(byte: Byte, currentChecksum: Int): Int {
|
||||
var checksum = currentChecksum
|
||||
var b = byte.toInt()
|
||||
for (i in 0 until 8) {
|
||||
checksum = if ((checksum xor b) and 1 != 0) {
|
||||
(checksum xor 0x18) shr 1 or 0x80
|
||||
} else {
|
||||
checksum shr 1
|
||||
}
|
||||
b = b shr 1
|
||||
}
|
||||
return checksum
|
||||
}
|
||||
|
||||
private fun hexStringToByteArray(hexString: String): ByteArray {
|
||||
val len = hexString.length
|
||||
val data = ByteArray(len / 2)
|
||||
for (i in 0 until len step 2) {
|
||||
data[i / 2] = ((Character.digit(hexString[i], 16) shl 4)
|
||||
+ Character.digit(hexString[i + 1], 16)).toByte()
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
private data class Sector0Payload(
|
||||
val key: String,
|
||||
val timeData: String
|
||||
)
|
||||
private fun IssuedCard.toResponse(): IssuedCardResponse {
|
||||
return IssuedCardResponse(
|
||||
id = id!!,
|
||||
propertyId = property.id!!,
|
||||
roomId = room.id!!,
|
||||
roomStayId = roomStay?.id,
|
||||
cardId = cardId,
|
||||
cardIndex = cardIndex,
|
||||
issuedAt = issuedAt.toString(),
|
||||
expiresAt = expiresAt.toString(),
|
||||
issuedByUserId = issuedBy?.id,
|
||||
revokedAt = revokedAt?.toString()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -86,10 +86,7 @@ class RoomImages(
|
||||
@RequestParam("file") file: MultipartFile,
|
||||
@RequestParam(required = false) tagIds: List<UUID>?
|
||||
): RoomImageResponse {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
val room = ensureRoom(propertyId, roomId)
|
||||
val room = requireRoomAdmin(propertyId, roomId, principal)
|
||||
|
||||
if (file.isEmpty) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "File is empty")
|
||||
@@ -132,10 +129,7 @@ class RoomImages(
|
||||
@PathVariable imageId: UUID,
|
||||
@AuthenticationPrincipal principal: MyPrincipal?
|
||||
) {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
ensureRoom(propertyId, roomId)
|
||||
requireRoomAdmin(propertyId, roomId, principal)
|
||||
|
||||
val image = roomImageRepo.findByIdAndRoomIdAndPropertyId(imageId, roomId, propertyId)
|
||||
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Image not found")
|
||||
@@ -187,10 +181,7 @@ class RoomImages(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
@RequestBody request: RoomImageTagUpdateRequest
|
||||
) {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
ensureRoom(propertyId, roomId)
|
||||
requireRoomAdmin(propertyId, roomId, principal)
|
||||
|
||||
val image = roomImageRepo.findByIdAndRoomIdAndPropertyId(imageId, roomId, propertyId)
|
||||
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Image not found")
|
||||
@@ -208,10 +199,7 @@ class RoomImages(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
@RequestBody request: RoomImageReorderRequest
|
||||
) {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
ensureRoom(propertyId, roomId)
|
||||
requireRoomAdmin(propertyId, roomId, principal)
|
||||
|
||||
if (request.imageIds.isEmpty()) {
|
||||
return
|
||||
@@ -239,10 +227,7 @@ class RoomImages(
|
||||
@AuthenticationPrincipal principal: MyPrincipal?,
|
||||
@RequestBody request: RoomImageReorderRequest
|
||||
) {
|
||||
requirePrincipal(principal)
|
||||
propertyAccess.requireMember(propertyId, principal!!.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER)
|
||||
val room = ensureRoom(propertyId, roomId)
|
||||
val room = requireRoomAdmin(propertyId, roomId, principal)
|
||||
|
||||
if (request.imageIds.isEmpty()) {
|
||||
return
|
||||
@@ -299,10 +284,9 @@ class RoomImages(
|
||||
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Room not found")
|
||||
}
|
||||
|
||||
private fun requirePrincipal(principal: MyPrincipal?) {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
private fun requireRoomAdmin(propertyId: UUID, roomId: UUID, principal: MyPrincipal?): com.android.trisolarisserver.models.room.Room {
|
||||
requireRole(propertyAccess, propertyId, principal, Role.ADMIN, Role.MANAGER)
|
||||
return ensureRoom(propertyId, roomId)
|
||||
}
|
||||
|
||||
private fun resolveTags(tagIds: List<UUID>?): Set<RoomImageTag> {
|
||||
|
||||
@@ -47,15 +47,12 @@ class RoomStayFlow(
|
||||
): RoomChangeResponse {
|
||||
val actor = requireActor(propertyId, principal)
|
||||
|
||||
val stay = roomStayRepo.findById(roomStayId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found")
|
||||
}
|
||||
if (stay.property.id != propertyId) {
|
||||
throw ResponseStatusException(HttpStatus.NOT_FOUND, "Room stay not found for property")
|
||||
}
|
||||
if (stay.toAt != null) {
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "Room stay already closed")
|
||||
}
|
||||
val stay = requireOpenRoomStayForProperty(
|
||||
roomStayRepo,
|
||||
propertyId,
|
||||
roomStayId,
|
||||
"Room stay already closed"
|
||||
)
|
||||
if (request.idempotencyKey.isBlank()) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "idempotencyKey required")
|
||||
}
|
||||
@@ -114,22 +111,9 @@ class RoomStayFlow(
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseOffset(value: String?): OffsetDateTime? {
|
||||
if (value.isNullOrBlank()) return null
|
||||
return try {
|
||||
OffsetDateTime.parse(value.trim())
|
||||
} catch (_: Exception) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
private fun requireActor(propertyId: UUID, principal: MyPrincipal?): com.android.trisolarisserver.models.property.AppUser {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
}
|
||||
propertyAccess.requireMember(propertyId, principal.userId)
|
||||
propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER, Role.STAFF)
|
||||
return appUserRepo.findById(principal.userId).orElseThrow {
|
||||
val resolved = requireRole(propertyAccess, propertyId, principal, Role.ADMIN, Role.MANAGER, Role.STAFF)
|
||||
return appUserRepo.findById(resolved.userId).orElseThrow {
|
||||
ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@ import org.springframework.web.bind.annotation.ResponseStatus
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import org.springframework.web.server.ResponseStatusException
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
import java.util.UUID
|
||||
|
||||
@RestController
|
||||
@@ -105,34 +104,6 @@ class TemporaryRoomCards(
|
||||
return issuedCardRepo.save(card).toResponse()
|
||||
}
|
||||
|
||||
private fun parseOffset(value: String?): OffsetDateTime? {
|
||||
if (value.isNullOrBlank()) return null
|
||||
return try {
|
||||
OffsetDateTime.parse(value.trim())
|
||||
} catch (_: Exception) {
|
||||
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
private fun encodeBlock(value: String?): String {
|
||||
val raw = (value ?: "").padEnd(16).take(16)
|
||||
val bytes = raw.toByteArray(Charsets.UTF_8)
|
||||
val sb = StringBuilder(bytes.size * 2)
|
||||
for (b in bytes) {
|
||||
sb.append(String.format("%02X", b))
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
private fun nowForProperty(timezone: String?): OffsetDateTime {
|
||||
val zone = try {
|
||||
if (timezone.isNullOrBlank()) ZoneId.of("Asia/Kolkata") else ZoneId.of(timezone)
|
||||
} catch (_: Exception) {
|
||||
ZoneId.of("Asia/Kolkata")
|
||||
}
|
||||
return OffsetDateTime.now(zone)
|
||||
}
|
||||
|
||||
private fun requireIssueActor(propertyId: UUID, principal: MyPrincipal?): com.android.trisolarisserver.models.property.AppUser {
|
||||
if (principal == null) {
|
||||
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal")
|
||||
@@ -175,74 +146,9 @@ class TemporaryRoomCards(
|
||||
val finalData = newData + checkSum
|
||||
return TempSector0Payload(key, finalData)
|
||||
}
|
||||
|
||||
private fun buildSector0Block2(roomNumber: Int, cardID: Int): String {
|
||||
val guestID = cardID + 1
|
||||
val cardIdStr = cardID.toString().padStart(6, '0')
|
||||
val guestIdStr = guestID.toString().padStart(6, '0')
|
||||
val finalRoom = roomNumber.toString().padStart(2, '0')
|
||||
return "472F${cardIdStr}2F${guestIdStr}00010000${finalRoom}0000"
|
||||
}
|
||||
|
||||
private fun formatDateComponents(time: OffsetDateTime): String {
|
||||
val minute = time.minute.toString().padStart(2, '0')
|
||||
val hour = time.hour.toString().padStart(2, '0')
|
||||
val day = time.dayOfMonth.toString().padStart(2, '0')
|
||||
val month = time.monthValue.toString().padStart(2, '0')
|
||||
val year = time.year.toString().takeLast(2)
|
||||
return "${minute}${hour}${day}${month}${year}"
|
||||
}
|
||||
|
||||
private fun calculateChecksum(dataHex: String): String {
|
||||
val data = hexStringToByteArray(dataHex)
|
||||
var checksum = 0
|
||||
for (byte in data) {
|
||||
checksum = calculateByteChecksum(byte, checksum)
|
||||
}
|
||||
return String.format("%02X", checksum)
|
||||
}
|
||||
|
||||
private fun calculateByteChecksum(byte: Byte, currentChecksum: Int): Int {
|
||||
var checksum = currentChecksum
|
||||
var b = byte.toInt()
|
||||
for (i in 0 until 8) {
|
||||
checksum = if ((checksum xor b) and 1 != 0) {
|
||||
(checksum xor 0x18) shr 1 or 0x80
|
||||
} else {
|
||||
checksum shr 1
|
||||
}
|
||||
b = b shr 1
|
||||
}
|
||||
return checksum
|
||||
}
|
||||
|
||||
private fun hexStringToByteArray(hexString: String): ByteArray {
|
||||
val len = hexString.length
|
||||
val data = ByteArray(len / 2)
|
||||
for (i in 0 until len step 2) {
|
||||
data[i / 2] = ((Character.digit(hexString[i], 16) shl 4)
|
||||
+ Character.digit(hexString[i + 1], 16)).toByte()
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
private data class TempSector0Payload(
|
||||
val key: String,
|
||||
val timeData: String
|
||||
)
|
||||
|
||||
private fun IssuedCard.toResponse(): IssuedCardResponse {
|
||||
return IssuedCardResponse(
|
||||
id = id!!,
|
||||
propertyId = property.id!!,
|
||||
roomId = room.id!!,
|
||||
roomStayId = roomStay?.id,
|
||||
cardId = cardId,
|
||||
cardIndex = cardIndex,
|
||||
issuedAt = issuedAt.toString(),
|
||||
expiresAt = expiresAt.toString(),
|
||||
issuedByUserId = issuedBy?.id,
|
||||
revokedAt = revokedAt?.toString()
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user