Reject duplicate guest documents by hash
All checks were successful
build-and-deploy / build-deploy (push) Successful in 31s
All checks were successful
build-and-deploy / build-deploy (push) Successful in 31s
This commit is contained in:
@@ -28,6 +28,7 @@ import java.time.OffsetDateTime
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.util.UUID
|
||||
import java.security.MessageDigest
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/properties/{propertyId}/guests/{guestId}/documents")
|
||||
@@ -82,6 +83,17 @@ class GuestDocuments(
|
||||
}
|
||||
|
||||
val stored = storage.store(propertyId, guestId, bookingId, file)
|
||||
val fileHash = hashFile(stored.storagePath)
|
||||
if (fileHash != null && guestDocumentRepo.existsByPropertyIdAndGuestIdAndBookingIdAndFileHash(
|
||||
propertyId,
|
||||
guestId,
|
||||
bookingId,
|
||||
fileHash
|
||||
)
|
||||
) {
|
||||
Files.deleteIfExists(Paths.get(stored.storagePath))
|
||||
throw ResponseStatusException(HttpStatus.CONFLICT, "Duplicate document")
|
||||
}
|
||||
val document = GuestDocument(
|
||||
property = property,
|
||||
guest = guest,
|
||||
@@ -90,7 +102,8 @@ class GuestDocuments(
|
||||
originalFilename = stored.originalFilename,
|
||||
contentType = stored.contentType,
|
||||
sizeBytes = stored.sizeBytes,
|
||||
storagePath = stored.storagePath
|
||||
storagePath = stored.storagePath,
|
||||
fileHash = fileHash
|
||||
)
|
||||
val saved = guestDocumentRepo.save(document)
|
||||
runExtraction(saved.id!!, propertyId, guestId)
|
||||
@@ -236,6 +249,27 @@ class GuestDocuments(
|
||||
}
|
||||
}
|
||||
|
||||
private fun hashFile(storagePath: String): String? {
|
||||
return try {
|
||||
val path = Paths.get(storagePath)
|
||||
if (!Files.exists(path)) return null
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
Files.newInputStream(path).use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var read = input.read(buffer)
|
||||
while (read >= 0) {
|
||||
if (read > 0) {
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
read = input.read(buffer)
|
||||
}
|
||||
}
|
||||
digest.digest().joinToString("") { "%02x".format(it) }
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
data class GuestDocumentResponse(
|
||||
|
||||
Reference in New Issue
Block a user