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:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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("\\");
|
||||
|
||||
@@ -12,6 +12,7 @@ import com.krylov.refound.dto.user.UserUpdateDto;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -27,11 +28,15 @@ class UserServiceTest {
|
||||
|
||||
private UserRepository repository;
|
||||
private UserService service;
|
||||
private JwtService jwtService;
|
||||
private RefreshTokenService refreshTokenService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
repository = mock(UserRepository.class);
|
||||
service = new UserService(repository, mock(FileStorageService.class));
|
||||
jwtService = mock(JwtService.class);
|
||||
refreshTokenService = mock(RefreshTokenService.class);
|
||||
service = new UserService(repository, mock(FileStorageService.class), jwtService, refreshTokenService);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -92,6 +97,66 @@ class UserServiceTest {
|
||||
verify(repository, never()).findByLogin(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignProfileHidesEmailAndPhone() {
|
||||
authenticate("alice", "ROLE_USER");
|
||||
when(repository.findByLogin("alice")).thenReturn(Optional.of(user(1L, "alice")));
|
||||
User bob = user(2L, "bob");
|
||||
bob.setEmail("bob@example.com");
|
||||
bob.setPhone("+7 900 000-00-00");
|
||||
when(repository.findById(2L)).thenReturn(Optional.of(bob));
|
||||
|
||||
var dto = service.getUserById(2L);
|
||||
|
||||
assertThat(dto.getEmail()).isNull();
|
||||
assertThat(dto.getPhone()).isNull();
|
||||
assertThat(dto.getLogin()).isEqualTo("bob");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownProfileShowsEmailAndPhone() {
|
||||
authenticate("alice", "ROLE_USER");
|
||||
User alice = user(1L, "alice");
|
||||
alice.setEmail("alice@example.com");
|
||||
when(repository.findByLogin("alice")).thenReturn(Optional.of(alice));
|
||||
when(repository.findById(1L)).thenReturn(Optional.of(alice));
|
||||
|
||||
assertThat(service.getUserById(1L).getEmail()).isEqualTo("alice@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingOwnLoginReturnsNewTokens() {
|
||||
authenticate("alice", "ROLE_USER");
|
||||
User alice = user(1L, "alice");
|
||||
alice.setRole(com.krylov.refound.enums.Role.USER);
|
||||
when(repository.findByLogin("alice")).thenReturn(Optional.of(alice));
|
||||
when(repository.findById(1L)).thenReturn(Optional.of(alice));
|
||||
when(jwtService.generateAccessToken("alice2", "USER")).thenReturn("new-access");
|
||||
when(refreshTokenService.issue("alice2")).thenReturn("new-refresh");
|
||||
|
||||
UserUpdateDto dto = new UserUpdateDto();
|
||||
dto.setLogin("alice2");
|
||||
var response = service.updateUser(1L, dto, null);
|
||||
|
||||
assertThat(response.getLogin()).isEqualTo("alice2");
|
||||
assertThat(response.getToken()).isEqualTo("new-access");
|
||||
assertThat(response.getRefreshToken()).isEqualTo("new-refresh");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminChangingForeignLoginGetsNoTokens() {
|
||||
authenticate("admin", "ROLE_ADMIN");
|
||||
User bob = user(2L, "bob");
|
||||
when(repository.findById(2L)).thenReturn(Optional.of(bob));
|
||||
|
||||
UserUpdateDto dto = new UserUpdateDto();
|
||||
dto.setLogin("bob2");
|
||||
var response = service.updateUser(2L, dto, null);
|
||||
|
||||
assertThat(response.getToken()).isNull();
|
||||
verify(refreshTokenService, never()).issue(any());
|
||||
}
|
||||
|
||||
private static void authenticate(String login, String authority) {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(login, null, List.of(new SimpleGrantedAuthority(authority))));
|
||||
|
||||
Reference in New Issue
Block a user