swagger
This commit is contained in:
@@ -31,3 +31,6 @@ replay_pid*
|
|||||||
/.zcode/plans/
|
/.zcode/plans/
|
||||||
/.zcodeignore
|
/.zcodeignore
|
||||||
/.env
|
/.env
|
||||||
|
/auth-keys/
|
||||||
|
/postgres-data/
|
||||||
|
/keys/
|
||||||
|
|||||||
+2
-2
@@ -20,12 +20,12 @@ services:
|
|||||||
|
|
||||||
open_cv:
|
open_cv:
|
||||||
image: git.gorodar.ru/gorodar/open_cv:latest
|
image: git.gorodar.ru/gorodar/open_cv:latest
|
||||||
ports:
|
#ports:
|
||||||
# - "8010:8010"
|
# - "8010:8010"
|
||||||
#env_file: .env # секреты не коммитятся
|
#env_file: .env # секреты не коммитятся
|
||||||
environment:
|
environment:
|
||||||
PORT: 8010
|
PORT: 8010
|
||||||
APP_API_KEY: 4c15963f-2802-4d22-aaab-11db2ffe0eed
|
APP_API_KEY: ${GORODAR_OPENCV_API_KEY}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 1 # stateless: реплики за балансировщиком
|
replicas: 1 # stateless: реплики за балансировщиком
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// Плагины Spring Boot и dependency-management опубликованы в Maven Central.
|
||||||
|
// Резолвим их оттуда: plugins.gradle.org (Cloudflare) из сети сборки докера
|
||||||
|
// доступен нестабильно — TLS-рукопожатие обрывается. Портал остаётся запасным.
|
||||||
|
beforeSettings { settings ->
|
||||||
|
settings.pluginManagement {
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package ru.gorodar.api.admin;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
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.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import ru.gorodar.api.dto.UserDtos.GrantRoleRequest;
|
||||||
|
import ru.gorodar.api.dto.UserDtos.UserRolesResponse;
|
||||||
|
import ru.gorodar.service.UserService;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/users")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Tag(name = "admin")
|
||||||
|
public class AdminUserController {
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public UserRolesResponse get(@RequestParam String email) {
|
||||||
|
return userService.getByEmail(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/{id}/roles")
|
||||||
|
public UserRolesResponse grantRole(@PathVariable UUID id, @Valid @RequestBody GrantRoleRequest request) {
|
||||||
|
return userService.grantRole(id, request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package ru.gorodar.api.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public final class UserDtos {
|
||||||
|
|
||||||
|
private UserDtos() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record UserRolesResponse(UUID userId, String email, List<String> roles) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record GrantRoleRequest(@NotBlank String role) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package ru.gorodar.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.client.RestClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Бин-строитель RestClient для интеграций (open_cv). В Boot 4 автоконфигурация
|
||||||
|
* RestClient вынесена в отдельный модуль spring-boot-restclient, которого нет
|
||||||
|
* в classpath, поэтому описываем прототипный бин явно — как это делала Boot 3.
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
public class RestClientConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RestClient.Builder restClientBuilder() {
|
||||||
|
return RestClient.builder();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package ru.gorodar.security;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Роли приложения: хранятся строками в user_roles, попадают в claim
|
||||||
|
* resource_access.gorodar.roles и должны совпадать с authority в SecurityConfig.
|
||||||
|
*/
|
||||||
|
public final class Roles {
|
||||||
|
|
||||||
|
public static final String MANAGE_AREA = "manage_area";
|
||||||
|
public static final String MANAGE_ATTRACTION = "manage_attraction";
|
||||||
|
public static final String MANAGE_ROLES = "manage_roles";
|
||||||
|
|
||||||
|
public static final Set<String> KNOWN = Set.of(MANAGE_AREA, MANAGE_ATTRACTION, MANAGE_ROLES);
|
||||||
|
|
||||||
|
private Roles() {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -47,11 +47,11 @@ public class SecurityConfig {
|
|||||||
.requestMatchers("/api/admin/**").denyAll()
|
.requestMatchers("/api/admin/**").denyAll()
|
||||||
// публичный каталог
|
// публичный каталог
|
||||||
.requestMatchers(HttpMethod.GET, "/api/areas/**", "/api/attractions/**").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/areas/**", "/api/attractions/**").permitAll()
|
||||||
|
// сервисные пути (обязательно до /api/** — иначе swagger потребует токен)
|
||||||
|
.requestMatchers("/error", "/actuator/health/**", "/actuator/info",
|
||||||
|
"/api/swagger-ui/**", "/api/swagger-ui.html", "/api/v3/api-docs/**").permitAll()
|
||||||
// персональное
|
// персональное
|
||||||
.requestMatchers("/api/**").authenticated()
|
.requestMatchers("/api/**").authenticated()
|
||||||
// сервисные пути
|
|
||||||
.requestMatchers("/error", "/actuator/health/**", "/actuator/info",
|
|
||||||
"/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
|
|
||||||
.anyRequest().denyAll())
|
.anyRequest().denyAll())
|
||||||
.oauth2ResourceServer(oauth2 -> oauth2
|
.oauth2ResourceServer(oauth2 -> oauth2
|
||||||
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)));
|
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)));
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package ru.gorodar.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import ru.gorodar.api.dto.UserDtos.GrantRoleRequest;
|
||||||
|
import ru.gorodar.api.dto.UserDtos.UserRolesResponse;
|
||||||
|
import ru.gorodar.dao.UserRepository;
|
||||||
|
import ru.gorodar.dao.UserRoleRepository;
|
||||||
|
import ru.gorodar.dao.entity.User;
|
||||||
|
import ru.gorodar.dao.entity.UserRole;
|
||||||
|
import ru.gorodar.exception.ApiException;
|
||||||
|
import ru.gorodar.exception.ErrorCode;
|
||||||
|
import ru.gorodar.security.Roles;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserService {
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final UserRoleRepository userRoleRepository;
|
||||||
|
|
||||||
|
public UserRolesResponse getByEmail(String rawEmail) {
|
||||||
|
String email = rawEmail.trim().toLowerCase();
|
||||||
|
User user = userRepository.findByEmail(email)
|
||||||
|
.orElseThrow(() -> new ApiException(ErrorCode.USER_NOT_FOUND));
|
||||||
|
return toResponse(user, rolesOf(user.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public UserRolesResponse grantRole(UUID userId, GrantRoleRequest request) {
|
||||||
|
User user = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new ApiException(ErrorCode.USER_NOT_FOUND));
|
||||||
|
String role = request.role();
|
||||||
|
if (!Roles.KNOWN.contains(role)) {
|
||||||
|
throw new ApiException(ErrorCode.UNKNOWN_ROLE, "Неизвестная роль: " + role);
|
||||||
|
}
|
||||||
|
List<String> roles = rolesOf(userId);
|
||||||
|
if (roles.contains(role)) {
|
||||||
|
throw new ApiException(ErrorCode.ROLE_ALREADY_GRANTED);
|
||||||
|
}
|
||||||
|
UserRole userRole = new UserRole();
|
||||||
|
userRole.setId(UUID.randomUUID());
|
||||||
|
userRole.setUser(user);
|
||||||
|
userRole.setRole(role);
|
||||||
|
userRoleRepository.save(userRole);
|
||||||
|
List<String> updated = new ArrayList<>(roles);
|
||||||
|
updated.add(role);
|
||||||
|
return toResponse(user, List.copyOf(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> rolesOf(UUID userId) {
|
||||||
|
return userRoleRepository.findByUserId(userId).stream()
|
||||||
|
.map(UserRole::getRole)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserRolesResponse toResponse(User user, List<String> roles) {
|
||||||
|
return new UserRolesResponse(user.getId(), user.getEmail(), roles);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,10 @@ spring:
|
|||||||
max-file-size: 20MB
|
max-file-size: 20MB
|
||||||
max-request-size: 22MB
|
max-request-size: 22MB
|
||||||
|
|
||||||
|
output:
|
||||||
|
ansi:
|
||||||
|
enabled: ALWAYS
|
||||||
|
|
||||||
gorodar:
|
gorodar:
|
||||||
auth:
|
auth:
|
||||||
client-id: gorodar
|
client-id: gorodar
|
||||||
@@ -59,5 +63,7 @@ management:
|
|||||||
include: health,info
|
include: health,info
|
||||||
|
|
||||||
springdoc:
|
springdoc:
|
||||||
|
api-docs:
|
||||||
|
path: /api/v3/api-docs
|
||||||
swagger-ui:
|
swagger-ui:
|
||||||
path: /swagger-ui.html
|
path: /api/swagger-ui.html
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
databaseChangeLog:
|
||||||
|
- changeSet:
|
||||||
|
id: 006-seed-admin-user
|
||||||
|
author: gorodar
|
||||||
|
comment: Идемпотентный seed администратора bukan87@mail.ru со всеми ролями;
|
||||||
|
ON CONFLICT DO NOTHING — условные вставки OSS-Liquibase нативно не умеет
|
||||||
|
changes:
|
||||||
|
- sql:
|
||||||
|
dbms: postgresql
|
||||||
|
sql: |
|
||||||
|
insert into users (id, email)
|
||||||
|
values ('3f1a2b74-9c58-4d27-8e64-91c0a5b2d8e3', 'bukan87@mail.ru')
|
||||||
|
on conflict (email) do nothing;
|
||||||
|
|
||||||
|
insert into user_roles (id, user_id, role)
|
||||||
|
select '5d2c8f31-a7b4-4e19-bf52-08e3d6c9a4f7', u.id, 'manage_area'
|
||||||
|
from users u where u.email = 'bukan87@mail.ru'
|
||||||
|
on conflict (user_id, role) do nothing;
|
||||||
|
|
||||||
|
insert into user_roles (id, user_id, role)
|
||||||
|
select '8e4b1d69-c3f2-4a75-9d08-6b1e5f8a2c9d', u.id, 'manage_attraction'
|
||||||
|
from users u where u.email = 'bukan87@mail.ru'
|
||||||
|
on conflict (user_id, role) do nothing;
|
||||||
|
|
||||||
|
insert into user_roles (id, user_id, role)
|
||||||
|
select 'c7a9e5f0-2b8d-4613-8f4e-0d9a3c6e1b52', u.id, 'manage_roles'
|
||||||
|
from users u where u.email = 'bukan87@mail.ru'
|
||||||
|
on conflict (user_id, role) do nothing;
|
||||||
|
rollback:
|
||||||
|
- sql:
|
||||||
|
dbms: postgresql
|
||||||
|
sql: |
|
||||||
|
delete from auth_codes
|
||||||
|
where user_id in (select id from users where email = 'bukan87@mail.ru');
|
||||||
|
|
||||||
|
delete from refresh_tokens
|
||||||
|
where user_id in (select id from users where email = 'bukan87@mail.ru');
|
||||||
|
|
||||||
|
delete from user_roles
|
||||||
|
where user_id in (select id from users where email = 'bukan87@mail.ru');
|
||||||
|
|
||||||
|
delete from users where email = 'bukan87@mail.ru';
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package ru.gorodar.service;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import ru.gorodar.api.dto.UserDtos.GrantRoleRequest;
|
||||||
|
import ru.gorodar.api.dto.UserDtos.UserRolesResponse;
|
||||||
|
import ru.gorodar.dao.UserRepository;
|
||||||
|
import ru.gorodar.dao.UserRoleRepository;
|
||||||
|
import ru.gorodar.dao.entity.User;
|
||||||
|
import ru.gorodar.dao.entity.UserRole;
|
||||||
|
import ru.gorodar.exception.ApiException;
|
||||||
|
import ru.gorodar.exception.ErrorCode;
|
||||||
|
import ru.gorodar.security.Roles;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class UserServiceTest {
|
||||||
|
|
||||||
|
private final UUID userId = UUID.randomUUID();
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserRepository userRepository;
|
||||||
|
@Mock
|
||||||
|
private UserRoleRepository userRoleRepository;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private UserService service;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void grantRoleSavesUserRoleAndReturnsUpdatedList() {
|
||||||
|
User user = EntityTestHelper.userOf(userId, "user@mail.ru");
|
||||||
|
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||||
|
when(userRoleRepository.findByUserId(userId))
|
||||||
|
.thenReturn(List.of(EntityTestHelper.userRoleOf(user, Roles.MANAGE_AREA)));
|
||||||
|
|
||||||
|
UserRolesResponse response = service.grantRole(userId, new GrantRoleRequest(Roles.MANAGE_ROLES));
|
||||||
|
|
||||||
|
ArgumentCaptor<UserRole> captor = ArgumentCaptor.forClass(UserRole.class);
|
||||||
|
verify(userRoleRepository).save(captor.capture());
|
||||||
|
assertThat(captor.getValue().getId()).isNotNull();
|
||||||
|
assertThat(captor.getValue().getUser()).isSameAs(user);
|
||||||
|
assertThat(captor.getValue().getRole()).isEqualTo(Roles.MANAGE_ROLES);
|
||||||
|
assertThat(response.userId()).isEqualTo(userId);
|
||||||
|
assertThat(response.email()).isEqualTo("user@mail.ru");
|
||||||
|
assertThat(response.roles()).containsExactly(Roles.MANAGE_AREA, Roles.MANAGE_ROLES);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void grantRoleFailsWhenUserNotFound() {
|
||||||
|
when(userRepository.findById(userId)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
ApiException e = assertThrows(ApiException.class,
|
||||||
|
() -> service.grantRole(userId, new GrantRoleRequest(Roles.MANAGE_AREA)));
|
||||||
|
|
||||||
|
assertEquals(ErrorCode.USER_NOT_FOUND, e.getCode());
|
||||||
|
verify(userRoleRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void grantRoleFailsOnUnknownRole() {
|
||||||
|
User user = EntityTestHelper.userOf(userId, "user@mail.ru");
|
||||||
|
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||||
|
|
||||||
|
ApiException e = assertThrows(ApiException.class,
|
||||||
|
() -> service.grantRole(userId, new GrantRoleRequest("admin")));
|
||||||
|
|
||||||
|
assertEquals(ErrorCode.UNKNOWN_ROLE, e.getCode());
|
||||||
|
verify(userRoleRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void grantRoleFailsWhenAlreadyGranted() {
|
||||||
|
User user = EntityTestHelper.userOf(userId, "user@mail.ru");
|
||||||
|
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||||
|
when(userRoleRepository.findByUserId(userId))
|
||||||
|
.thenReturn(List.of(EntityTestHelper.userRoleOf(user, Roles.MANAGE_AREA)));
|
||||||
|
|
||||||
|
ApiException e = assertThrows(ApiException.class,
|
||||||
|
() -> service.grantRole(userId, new GrantRoleRequest(Roles.MANAGE_AREA)));
|
||||||
|
|
||||||
|
assertEquals(ErrorCode.ROLE_ALREADY_GRANTED, e.getCode());
|
||||||
|
verify(userRoleRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getByEmailNormalizesEmailAndReturnsRoles() {
|
||||||
|
User user = EntityTestHelper.userOf(userId, "user@mail.ru");
|
||||||
|
when(userRepository.findByEmail("user@mail.ru")).thenReturn(Optional.of(user));
|
||||||
|
when(userRoleRepository.findByUserId(userId))
|
||||||
|
.thenReturn(List.of(EntityTestHelper.userRoleOf(user, Roles.MANAGE_ROLES)));
|
||||||
|
|
||||||
|
UserRolesResponse response = service.getByEmail(" User@Mail.RU ");
|
||||||
|
|
||||||
|
assertThat(response.userId()).isEqualTo(userId);
|
||||||
|
assertThat(response.email()).isEqualTo("user@mail.ru");
|
||||||
|
assertThat(response.roles()).containsExactly(Roles.MANAGE_ROLES);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getByEmailFailsWhenUserNotFound() {
|
||||||
|
when(userRepository.findByEmail("nobody@mail.ru")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
ApiException e = assertThrows(ApiException.class, () -> service.getByEmail("nobody@mail.ru"));
|
||||||
|
|
||||||
|
assertEquals(ErrorCode.USER_NOT_FOUND, e.getCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user