changed jdk on 25 springBoot on 3.5.6 and fix code

This commit is contained in:
SlimusMinus
2026-09-30 00:27:10 +03:00
parent 1efb67824f
commit 015b68d96d
19 changed files with 2226 additions and 71 deletions

View File

@@ -115,6 +115,18 @@ public class ChatService {
}
/**
* Проверка для STOMP-интерцептора: пользователь состоит в чате или нет.
* Не бросает исключений — вызывается на этапе авторизации подписки.
*/
@Transactional(readOnly = true)
public boolean isParticipant(Long chatId, Long userId) {
if (chatId == null || userId == null) {
return false;
}
return chatRepository.isParticipantOfChat(chatId, userId);
}
private Chat getChatOrThrow(Long chatId) {
return chatRepository.findById(chatId).orElseThrow(() -> new IllegalArgumentException("Чат не найден"));
}

View File

@@ -3,21 +3,26 @@ package com.krylov.refound.service;
import com.krylov.refound.config.MinioProperties;
import com.krylov.refound.dto.DownloadedFile;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.enums.Role;
import com.krylov.refound.exception.ApiException;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
@@ -40,11 +45,20 @@ import software.amazon.awssdk.core.exception.SdkClientException;
public class FileStorageService {
private final S3Client s3Client;
private final MinioProperties properties;
private final StringRedisTemplate redisTemplate;
private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
private static final Set<String> ALLOWED_CONTENT_TYPES = Set.of("image/jpeg", "image/png", "image/webp");
private static final String ORIGINAL_FILENAME_METADATA_KEY = "original-filename";
/**
* Сколько живёт запись о владельце файла. Совпадает с правилом жизненного цикла бакета
* (180 дней), который ставит StorageStructureService: раньше файл исчезнет из MinIO,
* чем протухнет отметка о нём.
*/
private static final Duration OWNER_TTL = Duration.ofDays(180);
private static final String OWNER_KEY_PREFIX = "files:owner:";
/**
* Загружает файл в MinIO в корень бакета.
*/
@@ -79,6 +93,7 @@ public class FileStorageService {
.build();
s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
registerOwner(objectName);
log.info("Файл '{}' успешно загружен.", objectName);
return objectName;
@@ -122,6 +137,8 @@ public class FileStorageService {
/**
* Удаляет файл из MinIO по его имени.
* Служебный метод без проверки прав: вызывается только из кода, который сам
* проверил, что файл можно удалять (удаление поста, аватара, модерация).
*/
public void deleteFile(String objectName) {
try {
@@ -132,6 +149,7 @@ public class FileStorageService {
.build();
s3Client.deleteObject(request);
forgetOwner(objectName);
log.info("Файл '{}' успешно удален.", objectName);
} catch (S3Exception | SdkClientException e) {
log.error("Ошибка при удалении файла '{}': {}", objectName, e.getMessage(), e);
@@ -139,6 +157,81 @@ public class FileStorageService {
}
}
/**
* Удаляет файл по запросу пользователя: свой файл удалить можно всегда,
* чужой — только администратору. Отсутствие отметки о владельце означает,
* что сервис не знает, кому файл принадлежит, поэтому удалять его нельзя.
*/
public void deleteFileAsCurrentUser(String objectName) {
assertCanDeleteFile(objectName);
deleteFile(objectName);
}
private void assertCanDeleteFile(String objectName) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication.getPrincipal() == null) {
throw new ApiException(ErrorCode.UNAUTHORIZED, "Пользователь не авторизован", HttpStatus.UNAUTHORIZED);
}
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> Role.ADMIN.name().equals(authority.getAuthority()));
if (isAdmin) {
return;
}
String owner = readOwner(objectName);
if (owner == null) {
log.warn("Удаление файла '{}': владелец неизвестен, доступ запрещён.", objectName);
throw new ApiException(ErrorCode.FORBIDDEN, "Удалить этот файл нельзя", HttpStatus.FORBIDDEN);
}
if (!owner.equals(authentication.getPrincipal())) {
log.warn("Попытка удалить чужой файл '{}' пользователем '{}'.", objectName, authentication.getPrincipal());
throw new ApiException(ErrorCode.FORBIDDEN, "Удалить можно только свои файлы", HttpStatus.FORBIDDEN);
}
}
// ---------- владение файлами ----------
private void registerOwner(String objectName) {
String login = currentLogin();
if (login == null) {
// Служебная загрузка без HTTP-контекста (модерация, сидер) — владельца нет.
return;
}
try {
redisTemplate.opsForValue().set(OWNER_KEY_PREFIX + objectName, login, OWNER_TTL);
} catch (RuntimeException e) {
// Файл уже загружен; не роняем запрос из-за вторичной операции.
log.warn("Не удалось сохранить владельца файла '{}': {}", objectName, e.getMessage());
}
}
private void forgetOwner(String objectName) {
try {
redisTemplate.delete(OWNER_KEY_PREFIX + objectName);
} catch (RuntimeException e) {
log.warn("Не удалось удалить отметку о владельце файла '{}': {}", objectName, e.getMessage());
}
}
private String readOwner(String objectName) {
try {
return redisTemplate.opsForValue().get(OWNER_KEY_PREFIX + objectName);
} catch (RuntimeException e) {
log.warn("Не удалось прочитать владельца файла '{}': {}", objectName, e.getMessage());
return null;
}
}
private String currentLogin() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
return principal instanceof String login && authentication.isAuthenticated() ? login : null;
}
// ---------- вспомогательные методы ----------
private DownloadedFile fetchFile(String objectName) {

View File

@@ -4,9 +4,9 @@ import com.krylov.refound.dto.user.UserResponseDto;
import com.krylov.refound.dto.user.UserUpdateDto;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.enums.Role;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.UserRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
@@ -35,15 +35,48 @@ public class UserService {
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
}
/** Текущий запрос сделал администратор. */
public boolean isCurrentUserAdmin() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
return authentication.getAuthorities().stream()
.anyMatch(authority -> Role.ADMIN.name().equals(authority.getAuthority()));
}
/**
* Проверяет, что текущий пользователь имеет право менять профиль {@code targetUserId}.
* Своим профилем управляет сам пользователь, чужим — только администратор.
*/
public void assertCanModifyUser(Long targetUserId) {
if (isCurrentUserAdmin()) {
return;
}
User current = getCurrentUser();
if (!current.getId().equals(targetUserId)) {
log.warn("Попытка изменить чужой профиль: current={} target={}", current.getId(), targetUserId);
throw new ApiException(ErrorCode.FORBIDDEN,
"Изменять можно только свой профиль", HttpStatus.FORBIDDEN);
}
}
public UserResponseDto getUserById(Long id) {
User user = repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
return getUserResponseDto(user);
}
public UserResponseDto updateUser(Long id, UserUpdateDto dto, Boolean removeAvatar) {
assertCanModifyUser(id);
User user = repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
if (dto.getLogin() != null && !dto.getLogin().equals(user.getLogin())
&& repository.existsByLogin(dto.getLogin())) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Логин уже занят", HttpStatus.BAD_REQUEST);
}
user.setLogin(dto.getLogin());
user.setName(dto.getFirstName());
@@ -92,7 +125,13 @@ public class UserService {
public Long getUserIdByLogin(String login) {
return repository.findUserByLogin(login)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
}
public String getRoleByLogin(String login) {
return repository.findByLogin(login)
.map(user -> user.getRole() != null ? user.getRole().name() : Role.USER.name())
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
}
private static UserResponseDto getUserResponseDto(User user) {