Files
nahodka-back/src/main/java/com/krylov/refound/controller/FileStorageController.java
SlimusMinus 5cd60b6318 Harden auth: separate access/refresh JWT, atomic refresh rotation, admin checks
- Refresh JWT carried no role but was accepted by JwtAuthenticationFilter and
  the STOMP CONNECT as an access token; tokens now carry a typ claim and the
  filters accept only access tokens (legacy tokens are told apart by role).
- Refresh rotation uses GETDEL, so one refresh token cannot be spent twice;
  refresh tokens are no longer written to logs.
- isCurrentUserAdmin and file deletion compared authorities with "ADMIN"
  instead of "ROLE_ADMIN", so admins were never recognised.
- getCurrentUser answers 401 for anonymous requests; profile update keeps the
  login when the field is not sent; registration rejects empty login/password.
- GlobalExceptionHandler turned AccessDenied, BadCredentials, EntityNotFound,
  Spring MVC 4xx errors and upload limits into 500.
- Presigned URL TTL is capped at 7 days.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:56:38 +03:00

86 lines
4.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.krylov.refound.controller;
import com.krylov.refound.service.FileStorageService;
import java.time.Duration;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileStorageController {
/**
* Сколько браузер помнит редирект на presigned URL и не ходит за ним на бэк.
* Вместе с кэшем ссылки (12ч) укладывается в её срок жизни (24ч).
*/
private static final Duration REDIRECT_CACHE_MAX_AGE = Duration.ofHours(6);
private static final long MAX_PRESIGNED_TTL_HOURS = 7 * 24;
private final FileStorageService fileStorageService;
@PostMapping
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
log.info("uploadFile");
String objectName = fileStorageService.uploadFile(file);
return ResponseEntity.ok(objectName); // фронт сохранит objectName как ключ картинки
}
@GetMapping("/{*objectName}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
// objectName придёт как "/avatars/cf80aebe-...jpg" — обрежь ведущий слэш
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
return fileStorageService.downloadFile(key);
}
/**
* Редирект на presigned URL для прямой загрузки файла с MinIO (Вариант B).
* Браузер перейдёт по 302 на временную ссылку и скачает картинку напрямую с MinIO.
* Ссылка стабильна (кэшируется) и сам редирект кэшируется браузером — повторный
* показ картинки не требует ни запроса на бэк, ни повторной загрузки.
*/
@GetMapping(value = "/{*objectName}", params = "presigned=true")
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String url = fileStorageService.getCachedPresignedDownloadUrl(key);
return ResponseEntity.status(302)
.header(HttpHeaders.LOCATION, url)
.cacheControl(CacheControl.maxAge(REDIRECT_CACHE_MAX_AGE).cachePrivate())
.build();
}
/**
* Возвращает presigned URL в JSON.
* PathPatternParser не допускает ничего после {*...}, поэтому "url" вынесен в префикс:
* GET /api/v1/files/url/avatars/cf80aebe-...jpg?ttlHours=24
*/
@GetMapping("/url/{*objectName}")
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
// SigV4 не подписывает ссылки дольше 7 дней: больший ttlHours ронял presigner с 500
Duration ttl = ttlHours > 0 ? Duration.ofHours(Math.min(ttlHours, MAX_PRESIGNED_TTL_HOURS)) : Duration.ofHours(24);
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
return ResponseEntity.ok(Map.of("url", url));
}
@DeleteMapping("/{*objectName}")
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
log.info("deleteFile {}", objectName);
// objectName может прийти как "/avatars/cf80aebe-...jpg" — обрежем ведущий слэш
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
fileStorageService.deleteFileAsCurrentUser(key);
return ResponseEntity.noContent().build();
}
}