-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileServiceImpl.java
More file actions
706 lines (632 loc) · 29.1 KB
/
Copy pathFileServiceImpl.java
File metadata and controls
706 lines (632 loc) · 29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
package com.itasocialacademy.oitassist.filemanager.service;
import static com.itasocialacademy.oitassist.filemanager.validation.util.FileValidationUtils.*;
import com.itasocialacademy.oitassist.core.enums.ErrorCode;
import com.itasocialacademy.oitassist.core.exceptions.AuthorizationException;
import com.itasocialacademy.oitassist.core.exceptions.ValidationException;
import com.itasocialacademy.oitassist.filemanager.api.dto.FileDetailsDTO;
import com.itasocialacademy.oitassist.filemanager.dao.enums.FileRole;
import com.itasocialacademy.oitassist.filemanager.dao.enums.FileStatus;
import com.itasocialacademy.oitassist.filemanager.dao.enums.RelatedEntityType;
import com.itasocialacademy.oitassist.filemanager.dao.enums.StorageProviderType;
import com.itasocialacademy.oitassist.filemanager.dao.model.FileAsset;
import com.itasocialacademy.oitassist.filemanager.dao.repository.FileRepository;
import com.itasocialacademy.oitassist.filemanager.dao.specification.FileAssetSpecification;
import com.itasocialacademy.oitassist.filemanager.dto.request.FileUploadRequestDto;
import com.itasocialacademy.oitassist.filemanager.dto.request.UpdateFileRoleRequestDto;
import com.itasocialacademy.oitassist.filemanager.dto.response.FileResponseDto;
import com.itasocialacademy.oitassist.filemanager.exceptions.FileAssetNotFoundException;
import com.itasocialacademy.oitassist.filemanager.exceptions.FileUploadException;
import com.itasocialacademy.oitassist.filemanager.mapper.FileMapper;
import com.itasocialacademy.oitassist.filemanager.providers.interfaces.StorageProvider;
import com.itasocialacademy.oitassist.filemanager.providers.resolver.StorageProviderResolver;
import com.itasocialacademy.oitassist.filemanager.service.interfaces.FileService;
import com.itasocialacademy.oitassist.filemanager.validation.interfaces.FilePolicy;
import com.itasocialacademy.oitassist.filemanager.validation.interfaces.FileValidationStrategy;
import com.itasocialacademy.oitassist.filemanager.validation.model.ValidationResult;
import com.itasocialacademy.oitassist.filemanager.validation.resolvers.FilePolicyResolver;
import com.itasocialacademy.oitassist.filemanager.validation.resolvers.FileValidationStrategyResolver;
import com.itasocialacademy.oitassist.security.api.interfaces.SecurityFacade;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
private final StorageProviderResolver providerResolver;
private final FileValidationStrategyResolver validationStrategyResolver;
private final FileRepository repository;
private final FileMapper fileMapper;
private final SecurityFacade securityFacade;
private final FilePolicyResolver filePolicyResolver;
/**
* Role identifier for administrative users. Used for role-based access control
* checks throughout this service.
*/
private static final String ROLE_ADMIN = "ADMIN";
/**
* Error message indicating that the user is not authenticated. Used when an
* operation requires authentication, but it is invalid.
*/
public static final String NOT_AUTHENTICATED = "Not authenticated";
/**
* Error message prefix indicating that a requested file could not be found in
* the database. This message is typically appended with the file identifier to
* provide context.
*/
public static final String FILE_NOT_FOUND_IN_THE_DATABASE = "File not found in the database: ";
/**
* {@inheritDoc}
*
* <p>
* Resolves the validation strategy for the given entity type, validates all
* files against the applicable policy, then delegates each file to
* {@link #uploadSingle}.
* </p>
*/
@Override
@Transactional
public List<FileResponseDto> upload(List<MultipartFile> files, FileUploadRequestDto requestDto) {
Long currentUserId = securityFacade.getCurrentUserId()
.orElseThrow(() -> new AuthorizationException(
NOT_AUTHENTICATED, ErrorCode.ACCESS_DENIED));
checkValidation(files, requestDto);
return files.stream()
.map(file -> uploadSingle(file, requestDto, currentUserId))
.toList();
}
/**
* {@inheritDoc}
*
* <p>
* Resolves the validation strategy for the given entity type, validates all
* files against the applicable policy, then delegates each file to
* {@link #uploadSingleToFileDetails}.
* </p>
*/
@Override
@Transactional
public List<FileDetailsDTO> uploadToFileDetails(List<MultipartFile> files, FileUploadRequestDto requestDto) {
Long currentUserId = securityFacade.getCurrentUserId()
.orElseThrow(() -> new AuthorizationException(
NOT_AUTHENTICATED, ErrorCode.ACCESS_DENIED));
checkValidation(files, requestDto);
return files.stream()
.map(file -> uploadSingleToFileDetails(file, requestDto, currentUserId))
.toList();
}
/**
* Method to perform a status change of the file. It marks the file as
* SOFT_DELETED, which can be used in further storage cleanup operations either
* manual, or scheduled. The physical record of the file after method execution
* remains intact.
*
* @param fileId id of the file.
*/
@Override
@Transactional
public void deleteSoft(Long fileId) {
Long currentUserId = securityFacade.getCurrentUserId()
.orElseThrow(() -> new AuthorizationException(
NOT_AUTHENTICATED, ErrorCode.ACCESS_DENIED));
FileAsset file = repository.findById(fileId)
.orElseThrow(() -> new FileAssetNotFoundException(FILE_NOT_FOUND_IN_THE_DATABASE + fileId));
checkOwnerOrAdmin(file.getUserId(), currentUserId);
file.setStatus(FileStatus.SOFT_DELETED);
file.setDeletedAt(OffsetDateTime.now());
repository.save(file);
}
/**
* Method to handle physical deletion of a file. Used for permanent deletion,
* cleanup scheduling or orphaned files' cleanup.
*
* @param fileId id of the file.
*/
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void deleteHard(Long fileId) {
FileAsset file = repository.findById(fileId)
.orElseThrow(() -> new FileAssetNotFoundException(FILE_NOT_FOUND_IN_THE_DATABASE + fileId));
validateAdmin();
StorageProvider provider = providerResolver.resolve(file.getStorageProvider());
try {
provider.deletePhysical(file.getStorageKey());
file.setStatus(FileStatus.HARD_DELETED);
file.setDeletedAt(OffsetDateTime.now());
file.setStorageKey("");
} catch (Exception e) {
log.error("Physical deletion failed for file {}, but DB record updated", fileId, e);
file.setStatus(FileStatus.FAILED);
}
repository.save(file);
}
/**
* Transitions a batch of {@link FileStatus#TEMPORARY} files to
* {@link FileStatus#ATTACHED} and establishes their relationship with the
* specified entity.
*
* @param entityId the ID of the entity to link files to
* @param entityType the type of the related entity
* @param fileIds the IDs of the files to attach; no-op if {@code null} or
* empty
* @param userId the ID of the user performing the file linking operation;
* must own all files or possess the ADMIN role
*/
@Override
@Transactional
public void linkFilesToEntity(Long entityId, RelatedEntityType entityType, List<Long> fileIds, Long userId) {
if (fileIds == null || fileIds.isEmpty()) {
log.debug("No files to link to entity {} with id={}", entityType, entityId);
return;
}
boolean isAdmin = securityFacade.hasRole(ROLE_ADMIN);
List<FileAsset> files = repository.findAllById(fileIds);
for (FileAsset file : files) {
checkOwnerOrAdmin(file.getUserId(), userId, isAdmin);
if (file.getStatus() == FileStatus.TEMPORARY) {
file.setStatus(FileStatus.ATTACHED);
file.setRelatedEntityId(entityId);
file.setRelatedEntityType(entityType);
log.debug("Linked file id={} to {} with id={}", file.getId(), entityType, entityId);
} else {
log.warn("Skipped file id={} with status={} (expected TEMPORARY)", file.getId(), file.getStatus());
}
}
repository.saveAll(files);
}
/**
* Marks a batch of files as {@link FileStatus#SOFT_DELETED}. Called via event
* after a news update removes files from content. Validates ownership for each
* file using the explicitly provided userId.
*
* @param entityType the type of the related entity
* @param entityId the ID of the entity to detach files to
* @param fileIds the IDs of files to soft-delete
* @param userId the ID of the user who triggered detach (from the event)
*/
@Override
@Transactional
public void detachFiles(RelatedEntityType entityType, Long entityId, List<Long> fileIds, Long userId) {
if (fileIds == null || fileIds.isEmpty()) {
return;
}
List<FileAsset> files = repository.findAllById(fileIds);
detachFilesHelper(entityType, entityId, userId, files);
}
@Override
@Transactional
public void detachFilesForMultiOwnerEntity(RelatedEntityType entityType, Long entityId, List<Long> fileIds) {
if (fileIds == null || fileIds.isEmpty()) {
return;
}
List<FileAsset> files = repository.findAllById(fileIds);
for (FileAsset file : files) {
validateEntityBoundary(file, entityType, entityId);
markAsSoftDeleted(file);
}
repository.saveAll(files);
}
/**
* {@inheritDoc}
*/
@Override
@Transactional
public void detachAllFilesByEntityId(RelatedEntityType entityType, Long entityId, Long userId) {
List<FileAsset> files = repository
.findByRelatedEntityTypeAndRelatedEntityIdAndStatus(
entityType, entityId, FileStatus.ATTACHED);
detachFilesHelper(entityType, entityId, userId, files);
}
/**
* Returns all {@link FileStatus#ATTACHED} files for the given entity, enriched
* with their publicly accessible URLs resolved from the storage provider.
*
* @param entityType the type of the related entity
* @param entityId the ID of the related entity
* @return list of file DTOs with resolved URLs
*/
@Override
@Transactional(readOnly = true)
public List<FileResponseDto> getFilesByEntity(RelatedEntityType entityType, Long entityId) {
List<FileAsset> files = repository
.findByRelatedEntityTypeAndRelatedEntityIdAndStatus(
entityType, entityId, FileStatus.ATTACHED);
return files.stream()
.map(file -> {
FileResponseDto dto = fileMapper.toDto(file);
StorageProvider provider = providerResolver.resolve(file.getStorageProvider());
dto.setUrl(provider.getFileUrl(file.getStorageKey()));
return dto;
})
.toList();
}
/**
* {@inheritDoc}
*
* <p>
* Uses JPA Specifications to filter by entity type, entity ID, ATTACHED status,
* and the provided set of file roles. Maps results directly to
* {@link FileDetailsDTO} via the file mapper.
* </p>
*/
@Override
@Transactional(readOnly = true)
public List<FileDetailsDTO> getFilesByEntity(RelatedEntityType entityType, Long entityId, Set<FileRole> roles) {
Specification<FileAsset> spec = Specification
.where(FileAssetSpecification.hasEntityType(entityType))
.and(FileAssetSpecification.hasEntityId(entityId))
.and(FileAssetSpecification.hasStatus(FileStatus.ATTACHED))
.and(FileAssetSpecification.hasFileRoleIn(roles));
return repository.findAll(spec).stream()
.map(file -> {
StorageProvider provider = providerResolver.resolve(file.getStorageProvider());
return fileMapper.toDetails(file, provider.getFileUrl(file.getStorageKey()));
})
.toList();
}
/**
* {@inheritDoc}
*
* <p>
* Uses JPA Specifications to filter by entity type, entity IDs, ATTACHED
* status, and the provided set of file roles. Maps results directly to
* {@link FileDetailsDTO} via the file mapper and groups them by entity ID.
* </p>
*/
@Override
@Transactional(readOnly = true)
public Map<Long, List<FileDetailsDTO>> getFilesByEntities(RelatedEntityType entityType, List<Long> entityIds,
Set<FileRole> roles) {
if (entityIds == null || entityIds.isEmpty()) {
return Collections.emptyMap();
}
Specification<FileAsset> spec = Specification
.where(FileAssetSpecification.hasEntityType(entityType))
.and(FileAssetSpecification.hasEntityIdIn(entityIds))
.and(FileAssetSpecification.hasStatus(FileStatus.ATTACHED))
.and(FileAssetSpecification.hasFileRoleIn(roles));
List<FileAsset> files = repository.findAll(spec);
Map<Long, List<FileDetailsDTO>> resultMap = new HashMap<>();
for (Long id : entityIds) {
resultMap.put(id, new ArrayList<>());
}
for (FileAsset file : files) {
StorageProvider provider = providerResolver.resolve(file.getStorageProvider());
FileDetailsDTO dto = fileMapper.toDetails(file, provider.getFileUrl(file.getStorageKey()));
resultMap.computeIfAbsent(file.getRelatedEntityId(), k -> new ArrayList<>()).add(dto);
}
return resultMap;
}
@Override
@Transactional
public FileResponseDto updateRoleGeneral(Long fileId, UpdateFileRoleRequestDto request) {
Long currentUserId = securityFacade.getCurrentUserId()
.orElseThrow(() -> new AuthorizationException(
NOT_AUTHENTICATED, ErrorCode.ACCESS_DENIED));
FileAsset file = repository.findById(fileId)
.orElseThrow(() -> new FileAssetNotFoundException(
FILE_NOT_FOUND_IN_THE_DATABASE + fileId));
checkOwnerOrAdmin(file.getUserId(), currentUserId);
FileAsset saved = validateAndUpdateRole(file, request.getNewRole(),
file.getRelatedEntityType(), file.getRelatedEntityId());
StorageProvider provider = providerResolver.resolve(saved.getStorageProvider());
FileResponseDto dto = fileMapper.toDto(saved);
dto.setUrl(provider.getFileUrl(saved.getStorageKey()));
return dto;
}
@Override
@Transactional
public void updateRoleForMultiOwnerEntity(Long fileId, FileRole newRole, RelatedEntityType entityType,
Long entityId) {
FileAsset file = repository.findById(fileId)
.orElseThrow(() -> new FileAssetNotFoundException(
FILE_NOT_FOUND_IN_THE_DATABASE + fileId));
validateAndUpdateRole(file, newRole, entityType, entityId);
}
/**
* Validates and updates the role of a given file asset. Ensures the file is in
* an ATTACHED state, belongs to the specified entity, and that the new role is
* allowed for its extension based on the entity's policy.
*
* @param file the file asset to update
* @param newRole the new role to assign
* @param entityType the expected related entity type
* @param entityId the expected related entity ID
* @return the saved file asset (or the original if the role is already set)
* @throws ValidationException if the file is not ATTACHED, does not belong to
* the entity, or the extension is disallowed
*/
private FileAsset validateAndUpdateRole(FileAsset file, FileRole newRole, RelatedEntityType entityType,
Long entityId) {
if (!file.getStatus().equals(FileStatus.ATTACHED)) {
throw new ValidationException(
"File must be in ATTACHED state to update its role",
ErrorCode.FILE_VALIDATION_FAILED);
}
validateEntityBoundary(file, entityType, entityId);
if (file.getFileRole().equals(newRole)) {
return file;
}
FilePolicy newPolicy = filePolicyResolver.resolve(entityType, newRole);
String extension = extractExtension(file.getOriginalFilename());
if (isExtensionNotAllowed(extension, newPolicy.getAllowedExtensions())) {
throw new ValidationException(
"File '%s' has extension '%s' which is not allowed for role %s. Allowed: %s."
.formatted(file.getOriginalFilename(), extension, newRole,
formatAllowed(newPolicy.getAllowedExtensions())),
ErrorCode.FILE_VALIDATION_FAILED);
}
file.setFileRole(newRole);
FileAsset saved = repository.save(file);
log.debug("Updated file role for id={} to {} (entity {}:{})",
file.getId(), newRole, entityType, entityId);
return saved;
}
/**
* Marks a batch of files as SOFT_DELETED. Called when files are removed from
* content. Validates ownership for each file using the provided userId.
*
* @param entityType the type of the related entity
* @param entityId the ID of the entity to detach files from
* @param userId the ID of the user who triggered detach
* @param files files to detach
*/
private void detachFilesHelper(RelatedEntityType entityType, Long entityId, Long userId, List<FileAsset> files) {
boolean isAdmin = securityFacade.hasRole(ROLE_ADMIN);
for (FileAsset file : files) {
validateEntityBoundary(file, entityType, entityId);
checkOwnerOrAdmin(file.getUserId(), userId, isAdmin);
file.setStatus(FileStatus.SOFT_DELETED);
markAsSoftDeleted(file);
}
repository.saveAll(files);
}
/**
* Validates that the given file asset belongs to the specified entity.
*
* @param file the file asset to validate
* @param entityType the expected related entity type
* @param entityId the expected related entity ID
* @throws ValidationException if the file does not belong to the entity
*/
private void validateEntityBoundary(FileAsset file, RelatedEntityType entityType, Long entityId) {
if (!entityType.equals(file.getRelatedEntityType()) || !entityId.equals(file.getRelatedEntityId())) {
throw new ValidationException(
"File id=" + file.getId() + " does not belong to " + entityType + " id=" + entityId,
ErrorCode.FILE_VALIDATION_FAILED);
}
}
/**
* Updates the file status to SOFT_DELETED and sets the deletion timestamp.
* Note: This does not persist the changes to the database; the caller must save
* the entity.
*
* @param file the file asset to mark as soft deleted
*/
private void markAsSoftDeleted(FileAsset file) {
file.setStatus(FileStatus.SOFT_DELETED);
file.setDeletedAt(OffsetDateTime.now());
}
/**
* Checks if given files are valid according to the validation strategy.
*
* @param files the files to upload
* @param requestDto upload context metadata (entity type and optional entity
* ID)
* @throws ValidationException if any file fails the policy validation
*/
private void checkValidation(List<MultipartFile> files, FileUploadRequestDto requestDto)
throws ValidationException {
RelatedEntityType entityType = requestDto.getRelatedEntityType();
FileRole role = requestDto.getFileRole();
FileValidationStrategy strategy = validationStrategyResolver.resolve(entityType, role);
FilePolicy policy = filePolicyResolver.resolve(entityType, role);
ValidationResult result = strategy.validate(files, requestDto, policy);
if (!result.valid()) {
throw new ValidationException(
String.join(", ", result.violations()),
ErrorCode.FILE_VALIDATION_FAILED);
}
}
/**
* Uploads a single file to the default storage provider and persists its
* metadata.
*
* @param file the file to upload
* @param requestDto upload context metadata
* @param userId the ID of the uploading user
* @return the persisted file record as a {@link FileResponseDto}
* @throws FileUploadException if the file stream cannot be read or the upload
* fails
*/
private FileResponseDto uploadSingle(MultipartFile file, FileUploadRequestDto requestDto, Long userId) {
StorageProvider provider = providerResolver.resolveDefault();
FileAsset saved = uploadFileAndGetFileAsset(file, requestDto, userId, provider);
FileResponseDto dto = fileMapper.toDto(saved);
dto.setUrl(provider.getFileUrl(saved.getStorageKey()));
return dto;
}
/**
* Uploads a single file to the default storage provider and persists its
* metadata.
*
* @param file the file to upload
* @param requestDto upload context metadata
* @param userId the ID of the uploading user
* @return the persisted file record as a {@link FileDetailsDTO}
* @throws FileUploadException if the file stream cannot be read or the upload
* fails
*/
private FileDetailsDTO uploadSingleToFileDetails(MultipartFile file, FileUploadRequestDto requestDto, Long userId) {
StorageProvider provider = providerResolver.resolveDefault();
FileAsset saved = uploadFileAndGetFileAsset(file, requestDto, userId, provider);
return fileMapper.toDetails(saved, provider.getFileUrl(saved.getStorageKey()));
}
/**
* Uploads a single file to the default storage provider and persists its
* metadata.
*
* @param file the file to upload
* @param requestDto upload context metadata
* @param userId the ID of the uploading user
* @param provider the resolved StorageProvider
* @return the persisted file record as a {@link FileAsset}
* @throws FileUploadException if the file stream cannot be read or the upload
* fails
*/
private FileAsset uploadFileAndGetFileAsset(MultipartFile file, FileUploadRequestDto requestDto, Long userId,
StorageProvider provider) {
String originalFilename = file.getOriginalFilename() != null ? file.getOriginalFilename() : "";
String storedFilename = generateStoredFilename(originalFilename);
String relativePath = buildRelativePath(requestDto);
String storageKey;
try (var inputStream = file.getInputStream()) {
storageKey = provider.upload(inputStream, storedFilename, relativePath);
} catch (IOException e) {
log.error("Failed to upload file: {}", originalFilename, e);
throw new FileUploadException(originalFilename, e);
}
FileAsset fileAsset = buildFileAsset(
file,
requestDto,
originalFilename,
storedFilename,
storageKey,
userId,
provider.getType());
return repository.save(fileAsset);
}
/**
* Generates a unique filename by prepending a UUID to the original file
* extension.
*
* @param originalFilename the original name of the uploaded file
* @return a unique filename safe for storage
*/
private String generateStoredFilename(String originalFilename) {
return UUID.randomUUID() + extractExtensionWithDot(originalFilename);
}
/**
* Extracts the file extension including the leading dot (e.g., {@code ".pdf"}).
*
* @param originalFilename the original filename
* @return the extension with dot, or an empty string if no extension is present
*/
private String extractExtensionWithDot(String originalFilename) {
if (originalFilename == null || !originalFilename.contains(".")) {
return "";
}
return originalFilename.substring(originalFilename.lastIndexOf('.'));
}
/**
* Builds the relative storage directory path derived from the entity type.
*
* @param requestDto the upload request containing the entity type
* @return a lowercase subdirectory name (e.g., {@code "news"}, {@code "task"})
*/
private String buildRelativePath(FileUploadRequestDto requestDto) {
return requestDto.getRelatedEntityType().name().toLowerCase();
}
/**
* Constructs a {@link FileAsset} entity from upload context data.
*
* @param file the uploaded file
* @param requestDto the upload request metadata
* @param originalFilename the original client-provided filename
* @param storedFilename the unique filename used on disk
* @param storageKey the relative storage key returned by the provider
* @param userId the ID of the uploading user
* @param providerType the storage provider type used for this upload
* @return a new {@link FileAsset} ready for persistence
*/
private FileAsset buildFileAsset(
MultipartFile file,
FileUploadRequestDto requestDto,
String originalFilename,
String storedFilename,
String storageKey,
Long userId,
StorageProviderType providerType) {
return FileAsset.builder()
.userId(userId)
.relatedEntityType(requestDto.getRelatedEntityType())
.relatedEntityId(requestDto.getRelatedEntityId())
.status(resolveStatus(requestDto))
.storageProvider(providerType)
.originalFilename(originalFilename)
.storedFilename(storedFilename)
.storageKey(storageKey)
.mimeType(file.getContentType())
.size(file.getSize())
.fileRole(requestDto.getFileRole())
.build();
}
/**
* Determines the initial {@link FileStatus} based on whether the upload is
* linked to a specific entity. Returns {@code TEMPORARY} when no entity ID is
* present, or {@code ATTACHED} when linked.
*
* @param requestDto the upload request metadata
* @return the appropriate initial file status
*/
private FileStatus resolveStatus(FileUploadRequestDto requestDto) {
return requestDto.getRelatedEntityId() == null
? FileStatus.TEMPORARY
: FileStatus.ATTACHED;
}
/**
* Core authorization check — verifies that the given user is either the file
* owner or an administrator. Used in batch operations where {@code isAdmin} is
* resolved once outside the loop to avoid redundant Security Context calls.
*
* @param fileOwnerId the ID of the user who owns the file
* @param currentUserId the ID of the user performing the operation
* @param isAdmin whether the current user has the ADMIN role
* @throws AuthorizationException if the user is neither owner nor admin
*/
private void checkOwnerOrAdmin(Long fileOwnerId, Long currentUserId, boolean isAdmin) {
boolean isOwner = fileOwnerId.equals(currentUserId);
if (!isOwner && !isAdmin) {
log.warn("Security Breach: User {} attempted to access file owned by {}",
currentUserId, fileOwnerId);
throw new AuthorizationException(
"You do not have permission to modify this file.",
ErrorCode.ACCESS_DENIED);
}
}
/**
* Convenience overload for single-file operations where {@code isAdmin} is
* resolved internally. Used in {@link #deleteSoft} where only one file is
* processed and a single Security Context call is acceptable.
*
* @param fileOwnerId the ID of the user who owns the file
* @param currentUserId the ID of the user performing the operation
* @throws AuthorizationException if the user is neither owner nor admin
*/
private void checkOwnerOrAdmin(Long fileOwnerId, Long currentUserId) {
checkOwnerOrAdmin(fileOwnerId, currentUserId, securityFacade.hasRole(ROLE_ADMIN));
}
/**
* Restricts the operation to administrators only. Used exclusively by
* {@link #deleteHard} which requires elevated privileges regardless of
* ownership.
*
* @throws AuthorizationException if the authenticated user does not have the
* ADMIN role
*/
private void validateAdmin() {
if (!securityFacade.hasRole(ROLE_ADMIN)) {
log.warn("Security Breach: User attempted to access file with insufficient authorities");
throw new AuthorizationException(
"You do not have permission to modify this file.",
ErrorCode.ACCESS_DENIED);
}
}
}