Files
nahodka-back/src/test/java/com/krylov/refound/service/UserServiceTest.java
SlimusMinus 477737c161 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>
2026-10-20 01:32:13 +03:00

172 lines
6.0 KiB
Java

package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
class UserServiceTest {
private UserRepository repository;
private UserService service;
private JwtService jwtService;
private RefreshTokenService refreshTokenService;
@BeforeEach
void setUp() {
repository = mock(UserRepository.class);
jwtService = mock(JwtService.class);
refreshTokenService = mock(RefreshTokenService.class);
service = new UserService(repository, mock(FileStorageService.class), jwtService, refreshTokenService);
}
@AfterEach
void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
void adminIsRecognisedByRolePrefixedAuthority() {
// Так роль кладёт JwtAuthenticationFilter
authenticate("admin", "ROLE_ADMIN");
assertThat(service.isCurrentUserAdmin()).isTrue();
}
@Test
void adminCanModifyForeignProfile() {
authenticate("admin", "ROLE_ADMIN");
User target = user(2L, "bob");
when(repository.findById(2L)).thenReturn(Optional.of(target));
UserUpdateDto dto = new UserUpdateDto();
dto.setFirstName("Боб");
service.updateUser(2L, dto, null);
assertThat(target.getName()).isEqualTo("Боб");
}
@Test
void userCannotModifyForeignProfile() {
authenticate("alice", "ROLE_USER");
when(repository.findByLogin("alice")).thenReturn(Optional.of(user(1L, "alice")));
assertThatThrownBy(() -> service.updateUser(2L, new UserUpdateDto(), null))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
verify(repository, never()).save(any());
}
@Test
void updateKeepsLoginWhenItIsNotSent() {
authenticate("alice", "ROLE_USER");
User alice = user(1L, "alice");
when(repository.findByLogin("alice")).thenReturn(Optional.of(alice));
when(repository.findById(1L)).thenReturn(Optional.of(alice));
service.updateUser(1L, new UserUpdateDto(), null);
assertThat(alice.getLogin()).isEqualTo("alice");
}
@Test
void anonymousRequestIsUnauthorizedNotNotFound() {
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(
"key", "anonymousUser", List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
assertThatThrownBy(service::getCurrentUser)
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED));
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))));
}
private static User user(Long id, String login) {
User user = new User();
user.setId(id);
user.setLogin(login);
return user;
}
}