Hide private profile data and reissue tokens when users change their login

- GET /api/v1/users/{id} returns email and phone only to the user themself
  and to admins.
- When a user changes their own login, the PUT response carries a new token
  pair (login is the JWT subject, so the old tokens stop matching); old
  refresh tokens fail on their own because the stored login differs.
- The old avatar is deleted only after the profile is saved; login length is
  checked against the column size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 01:32:13 +03:00
parent 48351398b5
commit 477737c161
3 changed files with 138 additions and 23 deletions

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.dto.user;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.krylov.refound.enums.Role;
import lombok.Builder;
import lombok.Data;
@@ -15,4 +16,13 @@ public class UserResponseDto {
private String email;
private String avatar;
private Role role;
/**
* Новая пара токенов — только в ответе PUT /api/v1/users/{id}, когда пользователь
* сменил свой логин (логин — subject JWT, прежние токены больше не подходят).
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
private String token;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String refreshToken;
}

View File

@@ -7,6 +7,7 @@ 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 com.krylov.refound.security.JwtService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
@@ -24,7 +25,11 @@ public class UserService {
public static final String ADMIN_AUTHORITY = "ROLE_" + Role.ADMIN.name();
private final UserRepository repository;
private static final int MAX_LOGIN_LENGTH = 255;
private final FileStorageService fileStorageService;
private final JwtService jwtService;
private final RefreshTokenService refreshTokenService;
public User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@@ -68,10 +73,31 @@ public class UserService {
}
}
/**
* Профиль пользователя. Email и телефон — личные данные: их видит сам
* пользователь и администратор, остальным они не отдаются (контакт для
* объявления — телефон в самом объявлении или чат).
*/
public UserResponseDto getUserById(Long id) {
User user = repository.findById(id)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
return getUserResponseDto(user);
UserResponseDto dto = getUserResponseDto(user);
if (!canSeePrivateData(user.getId())) {
dto.setEmail(null);
dto.setPhone(null);
}
return dto;
}
private boolean canSeePrivateData(Long userId) {
if (isCurrentUserAdmin()) {
return true;
}
try {
return getCurrentUser().getId().equals(userId);
} catch (ApiException e) {
return false;
}
}
public UserResponseDto updateUser(Long id, UserUpdateDto dto, Boolean removeAvatar) {
@@ -80,12 +106,21 @@ public class UserService {
User user = repository.findById(id)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
// Правит ли пользователь сам себя (а не админ чужой профиль) — до смены логина
boolean selfUpdate = isCurrentUser(user);
// Логин не прислали — оставляем прежний: null в login ломал вход в аккаунт
boolean loginChanged = false;
if (StringUtils.hasText(dto.getLogin()) && !dto.getLogin().equals(user.getLogin())) {
if (dto.getLogin().length() > MAX_LOGIN_LENGTH) {
throw new ApiException(ErrorCode.VALIDATION_ERROR,
"Логин длиннее " + MAX_LOGIN_LENGTH + " символов", HttpStatus.BAD_REQUEST);
}
if (repository.existsByLogin(dto.getLogin())) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Логин уже занят", HttpStatus.BAD_REQUEST);
}
user.setLogin(dto.getLogin());
loginChanged = true;
}
user.setName(dto.getFirstName());
user.setLastName(dto.getLastName());
@@ -93,39 +128,44 @@ public class UserService {
user.setEmail(dto.getEmail());
MultipartFile avatar = dto.getAvatar();
String replacedAvatarKey = null;
if (avatar != null && !avatar.isEmpty()) {
String oldAvatarKey = user.getAvatarUrl();
String newAvatarKey = fileStorageService.uploadFile(avatar, "avatars");
user.setAvatarUrl(newAvatarKey);
// подчищаем старый файл, если он был и это реально ключ MinIO
if (oldAvatarKey != null && !oldAvatarKey.isBlank() && isMinioKey(oldAvatarKey)) {
try {
fileStorageService.deleteFile(oldAvatarKey);
} catch (Exception e) {
log.warn("Не удалось удалить старый аватар из хранилища: {}", oldAvatarKey, e);
}
}
replacedAvatarKey = user.getAvatarUrl();
user.setAvatarUrl(fileStorageService.uploadFile(avatar, "avatars"));
} else if (Boolean.TRUE.equals(removeAvatar)) {
String oldAvatarKey = user.getAvatarUrl();
if (oldAvatarKey != null && !oldAvatarKey.isBlank() && isMinioKey(oldAvatarKey)) {
try {
fileStorageService.deleteFile(oldAvatarKey);
} catch (Exception e) {
log.warn("Не удалось удалить старый аватар из хранилища: {}", oldAvatarKey, e);
}
}
replacedAvatarKey = user.getAvatarUrl();
user.setAvatarUrl(null);
}
repository.save(user);
// Старый аватар удаляем после сохранения профиля: если сохранение упадёт,
// у пользователя не останется ссылки на удалённый файл
if (replacedAvatarKey != null && !replacedAvatarKey.isBlank() && isMinioKey(replacedAvatarKey)) {
try {
fileStorageService.deleteFile(replacedAvatarKey);
} catch (Exception e) {
log.warn("Не удалось удалить старый аватар из хранилища: {}", replacedAvatarKey, e);
}
}
UserResponseDto userResponseDto = getUserResponseDto(user);
if (loginChanged && selfUpdate) {
// В JWT логин — subject: старые токены после смены логина не находят пользователя.
// Отдаём новую пару; старые refresh-токены перестают работать сами (логин в них не совпадёт).
userResponseDto.setToken(jwtService.generateAccessToken(user.getLogin(), user.getRole().name()));
userResponseDto.setRefreshToken(refreshTokenService.issue(user.getLogin()));
}
log.info("User updated: {}", userResponseDto.getLogin());
return userResponseDto;
}
private boolean isCurrentUser(User user) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken)
&& user.getLogin().equals(authentication.getName());
}
/** Ключ MinIO — относительный (без хоста и без ведущего слеша). */
private static boolean isMinioKey(String key) {
return !key.startsWith("http://") && !key.startsWith("https://") && !key.startsWith("/") && !key.contains("\\");