From 6d6b29b84e57132a52cb715f5359b5a22255350b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 13 Oct 2023 10:29:49 +0300 Subject: [PATCH 01/34] rename root directory Took 1 hour 34 minutes --- pom.xml | 1 + .../AuthServiceApplication.java | 4 +- .../{auth => cuddly}/config/RedisConfig.java | 2 +- .../config/SecurityConfig.java | 14 +++---- .../{auth => cuddly}/config/TokenConfig.java | 4 +- .../{auth => cuddly}/constants/Constants.java | 2 +- .../constants/RegexpFormat.java | 2 +- .../constants/ValidationMessages.java | 2 +- .../dtos/request/ChangeEmailDto.java | 6 +-- .../dtos/request/ChangePasswordDto.java | 4 +- .../dtos/request/GenerateOtpDto.java | 6 +-- .../controllers/dtos/request/LoginDto.java | 6 +-- .../dtos/request/PermissionDto.java | 7 ++-- .../controllers/dtos/request/RegisterDto.java | 6 +-- .../dtos/request/RestorePasswordDto.java | 8 ++-- .../dtos/request/UpdatePermissionDto.java | 6 +-- .../dtos/response/PermissionsResponse.java | 6 +-- .../dtos/response/ResponseDetails.java | 6 +-- .../dtos/response/StatusResponse.java | 7 ++-- .../dtos/response/TokenResponse.java | 4 +- .../dtos/response/UsersResponse.java | 6 +-- .../endpoints/AccountController.java | 12 +++--- .../endpoints/ManagementController.java | 6 +-- .../endpoints/PermissionController.java | 8 ++-- .../endpoints/TokenController.java | 8 ++-- .../controllers/endpoints/UserController.java | 4 +- .../controllers/exeptions/CredentialEx.java | 6 +-- .../exeptions/GlobalExceptionHandler.java | 17 ++++---- .../entrypoint/AccessDeniedEntryPoint.java | 10 ++--- .../entrypoint/AuthErrorEntryPoint.java | 10 ++--- .../entrypoint/ServerErrorEntryPoint.java | 10 ++--- .../facade/AccountControllerFacade.java | 26 ++++++------- .../facade/ManagementControllerFacade.java | 22 +++++------ .../facade/PermissionControllerFacade.java | 22 +++++------ .../facade/TokenControllerFacade.java | 16 ++++---- .../facade/UserControllerFacade.java | 4 +- .../entities/enums/Permissions.java | 2 +- .../entities/enums/ResponseCode.java | 2 +- .../entities/enums/StatusLevel.java | 2 +- .../entities/enums/TokenType.java | 2 +- .../repositories/PermissionRepository.java | 10 +---- .../entities/repositories/UserRepository.java | 7 +--- .../services/contract/PermissionService.java | 4 +- .../services/contract/RedisOtpService.java | 2 +- .../services/contract/TokenService.java | 6 +-- .../services/contract/UserService.java | 4 +- .../implementation/PermissionServiceImpl.java | 14 +++---- .../implementation/RedisOtpServiceImpl.java | 8 ++-- .../implementation/TokenServiceImpl.java | 12 +++--- .../implementation/UserServiceImpl.java | 12 +++--- .../entities/tables/Permission.java | 3 +- .../entities/tables/User.java | 4 +- .../security/CustomUserDetails.java | 4 +- .../security/CustomUserDetailsService.java | 6 +-- .../{auth => cuddly}/utils/JsonUtils.java | 2 +- .../{auth => cuddly}/utils/RsaProperties.java | 2 +- .../AuthServiceApplicationTests.java | 2 +- .../base/BaseMockMvcTest.java | 39 +++++++++++++------ .../base/BaseValidatorTest.java | 2 +- .../base/ContainersConfig.java | 2 +- .../{auth => cuddly}/base/TestJsonUtils.java | 2 +- .../dtos/request/ChangeEmailDtoTest.java | 6 +-- .../dtos/request/ChangePasswordDtoTest.java | 6 +-- .../dtos/request/GenerateOtpDtoTest.java | 6 +-- .../dtos/request/LoginDtoTest.java | 6 +-- .../dtos/request/PermissionDtoTest.java | 8 ++-- .../dtos/request/RegisterDtoTest.java | 6 +-- .../dtos/request/RestorePasswordDtoTest.java | 6 +-- .../dtos/request/UpdatePermissionDtoTest.java | 6 +-- .../endpoints/PermissionControllerTest.java | 26 +++++++------ .../endpoints/TokenControllerTest.java | 18 ++++----- .../implementation/TokenServiceImplTest.java | 8 ++-- .../{auth => cuddly}/utils/JsonUtilsTest.java | 4 +- ...ication.yml => application-properties.yml} | 10 +++++ 74 files changed, 286 insertions(+), 275 deletions(-) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/AuthServiceApplication.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/config/RedisConfig.java (96%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/config/SecurityConfig.java (85%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/config/TokenConfig.java (92%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/constants/Constants.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/constants/RegexpFormat.java (88%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/constants/ValidationMessages.java (90%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/ChangeEmailDto.java (67%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/ChangePasswordDto.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/GenerateOtpDto.java (67%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/LoginDto.java (72%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/PermissionDto.java (63%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/RegisterDto.java (77%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/RestorePasswordDto.java (75%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/UpdatePermissionDto.java (75%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/response/PermissionsResponse.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/response/ResponseDetails.java (74%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/response/StatusResponse.java (84%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/response/TokenResponse.java (86%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/response/UsersResponse.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/AccountController.java (75%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/ManagementController.java (88%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/PermissionController.java (79%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/TokenController.java (74%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/UserController.java (86%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/exeptions/CredentialEx.java (76%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/exeptions/GlobalExceptionHandler.java (87%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java (78%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java (78%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java (78%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/facade/AccountControllerFacade.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/facade/ManagementControllerFacade.java (77%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/facade/PermissionControllerFacade.java (70%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/facade/TokenControllerFacade.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/controllers/facade/UserControllerFacade.java (81%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/enums/Permissions.java (84%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/enums/ResponseCode.java (99%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/enums/StatusLevel.java (75%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/enums/TokenType.java (67%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/repositories/PermissionRepository.java (55%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/repositories/UserRepository.java (65%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/contract/PermissionService.java (82%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/contract/RedisOtpService.java (87%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/contract/TokenService.java (68%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/contract/UserService.java (86%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/implementation/PermissionServiceImpl.java (79%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/implementation/RedisOtpServiceImpl.java (86%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/implementation/TokenServiceImpl.java (90%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/services/implementation/UserServiceImpl.java (83%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/tables/Permission.java (84%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/entities/tables/User.java (93%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/security/CustomUserDetails.java (94%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/security/CustomUserDetailsService.java (83%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/utils/JsonUtils.java (96%) rename src/main/java/com/github/gribanoveu/{auth => cuddly}/utils/RsaProperties.java (89%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/AuthServiceApplicationTests.java (83%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/base/BaseMockMvcTest.java (57%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/base/BaseValidatorTest.java (93%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/base/ContainersConfig.java (92%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/base/TestJsonUtils.java (97%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/ChangeEmailDtoTest.java (91%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/ChangePasswordDtoTest.java (95%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/GenerateOtpDtoTest.java (91%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/LoginDtoTest.java (94%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/PermissionDtoTest.java (88%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/RegisterDtoTest.java (94%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/RestorePasswordDtoTest.java (96%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/dtos/request/UpdatePermissionDtoTest.java (95%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/PermissionControllerTest.java (95%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/controllers/endpoints/TokenControllerTest.java (92%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/entities/services/implementation/TokenServiceImplTest.java (92%) rename src/test/java/com/github/gribanoveu/{auth => cuddly}/utils/JsonUtilsTest.java (90%) rename src/test/resources/{application.yml => application-properties.yml} (64%) diff --git a/pom.xml b/pom.xml index 99960d2..ab6087c 100644 --- a/pom.xml +++ b/pom.xml @@ -19,6 +19,7 @@ 17 2.0 + 1.0.7 diff --git a/src/main/java/com/github/gribanoveu/auth/AuthServiceApplication.java b/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/AuthServiceApplication.java rename to src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java index 8f34266..6db166a 100644 --- a/src/main/java/com/github/gribanoveu/auth/AuthServiceApplication.java +++ b/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth; +package com.github.gribanoveu.cuddly; -import com.github.gribanoveu.auth.utils.RsaProperties; +import com.github.gribanoveu.cuddly.utils.RsaProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; diff --git a/src/main/java/com/github/gribanoveu/auth/config/RedisConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/RedisConfig.java similarity index 96% rename from src/main/java/com/github/gribanoveu/auth/config/RedisConfig.java rename to src/main/java/com/github/gribanoveu/cuddly/config/RedisConfig.java index 5f71333..d9997b1 100644 --- a/src/main/java/com/github/gribanoveu/auth/config/RedisConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/RedisConfig.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.config; +package com.github.gribanoveu.cuddly.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/com/github/gribanoveu/auth/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java similarity index 85% rename from src/main/java/com/github/gribanoveu/auth/config/SecurityConfig.java rename to src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index 27b5ae7..502642a 100644 --- a/src/main/java/com/github/gribanoveu/auth/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.config; +package com.github.gribanoveu.cuddly.config; -import com.github.gribanoveu.auth.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; -import com.github.gribanoveu.auth.controllers.exeptions.entrypoint.AuthErrorEntryPoint; -import com.github.gribanoveu.auth.controllers.exeptions.entrypoint.ServerErrorEntryPoint; -import com.github.gribanoveu.auth.security.CustomUserDetailsService; +import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; +import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AuthErrorEntryPoint; +import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.ServerErrorEntryPoint; +import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,8 +20,8 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; -import static com.github.gribanoveu.auth.entities.enums.Permissions.AU_PERMISSIONS_MANAGEMENT; -import static com.github.gribanoveu.auth.entities.enums.Permissions.AU_USERS_MANAGEMENT; +import static com.github.gribanoveu.cuddly.entities.enums.Permissions.AU_PERMISSIONS_MANAGEMENT; +import static com.github.gribanoveu.cuddly.entities.enums.Permissions.AU_USERS_MANAGEMENT; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/config/TokenConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java similarity index 92% rename from src/main/java/com/github/gribanoveu/auth/config/TokenConfig.java rename to src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java index 417a2a1..334f014 100644 --- a/src/main/java/com/github/gribanoveu/auth/config/TokenConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.config; +package com.github.gribanoveu.cuddly.config; -import com.github.gribanoveu.auth.utils.RsaProperties; +import com.github.gribanoveu.cuddly.utils.RsaProperties; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; diff --git a/src/main/java/com/github/gribanoveu/auth/constants/Constants.java b/src/main/java/com/github/gribanoveu/cuddly/constants/Constants.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/constants/Constants.java rename to src/main/java/com/github/gribanoveu/cuddly/constants/Constants.java index af1c8b8..bad31ca 100644 --- a/src/main/java/com/github/gribanoveu/auth/constants/Constants.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/Constants.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.constants; +package com.github.gribanoveu.cuddly.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/constants/RegexpFormat.java b/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java similarity index 88% rename from src/main/java/com/github/gribanoveu/auth/constants/RegexpFormat.java rename to src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java index 5d1963c..6ab9ba7 100644 --- a/src/main/java/com/github/gribanoveu/auth/constants/RegexpFormat.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.constants; +package com.github.gribanoveu.cuddly.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/constants/ValidationMessages.java b/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java similarity index 90% rename from src/main/java/com/github/gribanoveu/auth/constants/ValidationMessages.java rename to src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java index bc4039a..1237158 100644 --- a/src/main/java/com/github/gribanoveu/auth/constants/ValidationMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.constants; +package com.github.gribanoveu.cuddly.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangeEmailDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDto.java similarity index 67% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangeEmailDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDto.java index 717bca0..0efe193 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangeEmailDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDto.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDto.java index be4c349..90eb023 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDto.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/GenerateOtpDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDto.java similarity index 67% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/GenerateOtpDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDto.java index 584d7c2..8b4f2d5 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/GenerateOtpDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDto.java similarity index 72% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/LoginDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDto.java index a953019..40637f1 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/PermissionDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDto.java similarity index 63% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/PermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDto.java index 214c267..1843f26 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/PermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDto.java @@ -1,12 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.PERMISSION_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.PERMISSION_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDto.java similarity index 77% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/RegisterDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDto.java index 57cef50..0a34902 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/RestorePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDto.java similarity index 75% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/RestorePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDto.java index b2e0f49..6ef2e2e 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/RestorePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDto.java @@ -1,12 +1,12 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.auth.constants.RegexpFormat.OTP_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.OTP_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/UpdatePermissionDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDto.java similarity index 75% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/UpdatePermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDto.java index f367b80..0f41c57 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/request/UpdatePermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.auth.constants.RegexpFormat.PERMISSION_PATTERN; -import static com.github.gribanoveu.auth.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddly.constants.RegexpFormat.PERMISSION_PATTERN; +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/PermissionsResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/PermissionsResponse.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/PermissionsResponse.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/PermissionsResponse.java index 82f3f49..92fb556 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/PermissionsResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/PermissionsResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.entities.tables.Permission; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.tables.Permission; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/ResponseDetails.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java similarity index 74% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/ResponseDetails.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java index 1418ad9..7f07054 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/ResponseDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java @@ -1,9 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/StatusResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java similarity index 84% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/StatusResponse.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java index 689e1d8..d3fd42b 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/StatusResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java @@ -1,12 +1,11 @@ -package com.github.gribanoveu.auth.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.http.HttpStatus; import java.time.LocalDateTime; import java.util.Collection; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java similarity index 86% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/TokenResponse.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java index 6522d6b..f72c8ec 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/TokenResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/UsersResponse.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/UsersResponse.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/UsersResponse.java index b570de2..c719ebc 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/dtos/response/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/UsersResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.tables.User; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/AccountController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/AccountController.java similarity index 75% rename from src/main/java/com/github/gribanoveu/auth/controllers/endpoints/AccountController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/AccountController.java index 5d3d0ab..3f01716 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/AccountController.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.auth.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints; -import com.github.gribanoveu.auth.controllers.dtos.request.ChangeEmailDto; -import com.github.gribanoveu.auth.controllers.dtos.request.ChangePasswordDto; -import com.github.gribanoveu.auth.controllers.dtos.request.GenerateOtpDto; -import com.github.gribanoveu.auth.controllers.dtos.request.RestorePasswordDto; -import com.github.gribanoveu.auth.controllers.facade.AccountControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangeEmailDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.GenerateOtpDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.RestorePasswordDto; +import com.github.gribanoveu.cuddly.controllers.facade.AccountControllerFacade; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/ManagementController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java similarity index 88% rename from src/main/java/com/github/gribanoveu/auth/controllers/endpoints/ManagementController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java index 19b8a1a..316d420 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/ManagementController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints; -import com.github.gribanoveu.auth.controllers.dtos.request.RegisterDto; -import com.github.gribanoveu.auth.controllers.facade.ManagementControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.RegisterDto; +import com.github.gribanoveu.cuddly.controllers.facade.ManagementControllerFacade; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/PermissionController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java similarity index 79% rename from src/main/java/com/github/gribanoveu/auth/controllers/endpoints/PermissionController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java index 1c5ffcb..736ed9c 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/PermissionController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.auth.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints; -import com.github.gribanoveu.auth.controllers.dtos.request.PermissionDto; -import com.github.gribanoveu.auth.controllers.dtos.request.UpdatePermissionDto; -import com.github.gribanoveu.auth.controllers.facade.PermissionControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.PermissionDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.UpdatePermissionDto; +import com.github.gribanoveu.cuddly.controllers.facade.PermissionControllerFacade; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/TokenController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenController.java similarity index 74% rename from src/main/java/com/github/gribanoveu/auth/controllers/endpoints/TokenController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenController.java index d15c79e..ed90de1 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/TokenController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenController.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.auth.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints; -import com.github.gribanoveu.auth.controllers.dtos.request.LoginDto; -import com.github.gribanoveu.auth.controllers.dtos.response.TokenResponse; -import com.github.gribanoveu.auth.controllers.facade.TokenControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.TokenResponse; +import com.github.gribanoveu.cuddly.controllers.facade.TokenControllerFacade; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/UserController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/UserController.java similarity index 86% rename from src/main/java/com/github/gribanoveu/auth/controllers/endpoints/UserController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/UserController.java index d63493c..212382f 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/endpoints/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/UserController.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints; -import com.github.gribanoveu.auth.controllers.facade.UserControllerFacade; +import com.github.gribanoveu.cuddly.controllers.facade.UserControllerFacade; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/CredentialEx.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/CredentialEx.java similarity index 76% rename from src/main/java/com/github/gribanoveu/auth/controllers/exeptions/CredentialEx.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/CredentialEx.java index 192a05a..50bad4a 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/CredentialEx.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/CredentialEx.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.exeptions; +package com.github.gribanoveu.cuddly.controllers.exeptions; -import com.github.gribanoveu.auth.controllers.dtos.response.ResponseDetails; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.controllers.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import lombok.Getter; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.BadCredentialsException; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java similarity index 87% rename from src/main/java/com/github/gribanoveu/auth/controllers/exeptions/GlobalExceptionHandler.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java index 5acdeef..9db072f 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.auth.controllers.exeptions; +package com.github.gribanoveu.cuddly.controllers.exeptions; -import com.github.gribanoveu.auth.constants.ValidationMessages; -import com.github.gribanoveu.auth.controllers.dtos.response.ResponseDetails; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.controllers.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; import jakarta.validation.ConstraintViolationException; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; @@ -16,9 +16,6 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - /** * @author Evgeny Gribanov * @version 07.07.2023 @@ -65,7 +62,7 @@ public ResponseEntity handleValidAnnotationException(MethodArgumentNotValidEx String.format(ResponseCode.VALIDATION_ERROR_DETAIL.getMessage(), fieldError.getField(), fieldError.getDefaultMessage()))).toList(); - var details = StatusResponse.create( errors, StatusLevel.ERROR); + var details = StatusResponse.create(errors, StatusLevel.WARNING); return ResponseEntity.status(e.getStatusCode()).body(details); } diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java similarity index 78% rename from src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java index 829b95b..0ab1541 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.utils.JsonUtils; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.utils.JsonUtils; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java similarity index 78% rename from src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java index 7e95be7..e5236c0 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.utils.JsonUtils; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java similarity index 78% rename from src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java index d7a7818..cc609a6 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.auth.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.utils.JsonUtils; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/facade/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/AccountControllerFacade.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/controllers/facade/AccountControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/AccountControllerFacade.java index 0e03d03..927befb 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/facade/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/AccountControllerFacade.java @@ -1,16 +1,16 @@ -package com.github.gribanoveu.auth.controllers.facade; +package com.github.gribanoveu.cuddly.controllers.facade; -import com.github.gribanoveu.auth.controllers.dtos.request.ChangeEmailDto; -import com.github.gribanoveu.auth.controllers.dtos.request.ChangePasswordDto; -import com.github.gribanoveu.auth.controllers.dtos.request.GenerateOtpDto; -import com.github.gribanoveu.auth.controllers.dtos.request.RestorePasswordDto; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.entities.services.contract.RedisOtpService; -import com.github.gribanoveu.auth.entities.services.contract.UserService; -import com.github.gribanoveu.auth.utils.JsonUtils; +import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangeEmailDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.GenerateOtpDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.RestorePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.services.contract.RedisOtpService; +import com.github.gribanoveu.cuddly.entities.services.contract.UserService; +import com.github.gribanoveu.cuddly.utils.JsonUtils; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; @@ -72,7 +72,7 @@ public ResponseEntity generateOtpCode(GenerateOtpDto request) { if (!userExist) throw new CredentialEx(ResponseCode.USER_NOT_EXIST); var otpCode = jsonUtils.generateRandomOtpCode().toString(); redisOtpService.saveOptCode(request.email(), otpCode, otpCodeLifeTime); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.OTP_CODE_CREATED, StatusLevel.ERROR)); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.OTP_CODE_CREATED, StatusLevel.SUCCESS)); } // next screen user enter otp code and new password and re-enter password again diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/facade/ManagementControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/ManagementControllerFacade.java similarity index 77% rename from src/main/java/com/github/gribanoveu/auth/controllers/facade/ManagementControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/ManagementControllerFacade.java index d7ef6c7..486e649 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/facade/ManagementControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/ManagementControllerFacade.java @@ -1,15 +1,15 @@ -package com.github.gribanoveu.auth.controllers.facade; +package com.github.gribanoveu.cuddly.controllers.facade; -import com.github.gribanoveu.auth.constants.Constants; -import com.github.gribanoveu.auth.controllers.dtos.request.RegisterDto; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.controllers.dtos.response.UsersResponse; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.entities.services.contract.PermissionService; -import com.github.gribanoveu.auth.entities.services.contract.UserService; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.constants.Constants; +import com.github.gribanoveu.cuddly.controllers.dtos.request.RegisterDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.controllers.dtos.response.UsersResponse; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; +import com.github.gribanoveu.cuddly.entities.services.contract.UserService; +import com.github.gribanoveu.cuddly.entities.tables.User; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/facade/PermissionControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java similarity index 70% rename from src/main/java/com/github/gribanoveu/auth/controllers/facade/PermissionControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java index 057e406..60c54e8 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/facade/PermissionControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java @@ -1,14 +1,14 @@ -package com.github.gribanoveu.auth.controllers.facade; - -import com.github.gribanoveu.auth.controllers.dtos.request.PermissionDto; -import com.github.gribanoveu.auth.controllers.dtos.request.UpdatePermissionDto; -import com.github.gribanoveu.auth.controllers.dtos.response.PermissionsResponse; -import com.github.gribanoveu.auth.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.StatusLevel; -import com.github.gribanoveu.auth.entities.services.contract.PermissionService; -import com.github.gribanoveu.auth.entities.tables.Permission; +package com.github.gribanoveu.cuddly.controllers.facade; + +import com.github.gribanoveu.cuddly.controllers.dtos.request.PermissionDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.UpdatePermissionDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.PermissionsResponse; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; +import com.github.gribanoveu.cuddly.entities.tables.Permission; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/facade/TokenControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/TokenControllerFacade.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/controllers/facade/TokenControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/TokenControllerFacade.java index 33dcb41..30b1bd6 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/facade/TokenControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/TokenControllerFacade.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.controllers.facade; - -import com.github.gribanoveu.auth.controllers.dtos.request.LoginDto; -import com.github.gribanoveu.auth.controllers.dtos.response.TokenResponse; -import com.github.gribanoveu.auth.entities.enums.TokenType; -import com.github.gribanoveu.auth.entities.services.contract.TokenService; -import com.github.gribanoveu.auth.security.CustomUserDetails; -import com.github.gribanoveu.auth.security.CustomUserDetailsService; +package com.github.gribanoveu.cuddly.controllers.facade; + +import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.TokenResponse; +import com.github.gribanoveu.cuddly.entities.enums.TokenType; +import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.security.CustomUserDetails; +import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/com/github/gribanoveu/auth/controllers/facade/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java similarity index 81% rename from src/main/java/com/github/gribanoveu/auth/controllers/facade/UserControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java index 913d7f8..e522440 100644 --- a/src/main/java/com/github/gribanoveu/auth/controllers/facade/UserControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.controllers.facade; +package com.github.gribanoveu.cuddly.controllers.facade; -import com.github.gribanoveu.auth.entities.services.contract.UserService; +import com.github.gribanoveu.cuddly.entities.services.contract.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/enums/Permissions.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Permissions.java similarity index 84% rename from src/main/java/com/github/gribanoveu/auth/entities/enums/Permissions.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/enums/Permissions.java index 3012f57..cb50f88 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/enums/Permissions.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Permissions.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.entities.enums; +package com.github.gribanoveu.cuddly.entities.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/entities/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java similarity index 99% rename from src/main/java/com/github/gribanoveu/auth/entities/enums/ResponseCode.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java index 2441b27..04ac95c 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.entities.enums; +package com.github.gribanoveu.cuddly.entities.enums; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/enums/StatusLevel.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/StatusLevel.java similarity index 75% rename from src/main/java/com/github/gribanoveu/auth/entities/enums/StatusLevel.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/enums/StatusLevel.java index 3173a66..e322a9b 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/enums/StatusLevel.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/StatusLevel.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.entities.enums; +package com.github.gribanoveu.cuddly.entities.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/entities/enums/TokenType.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/TokenType.java similarity index 67% rename from src/main/java/com/github/gribanoveu/auth/entities/enums/TokenType.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/enums/TokenType.java index ee304d3..649f346 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/enums/TokenType.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/TokenType.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.entities.enums; +package com.github.gribanoveu.cuddly.entities.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/auth/entities/repositories/PermissionRepository.java b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java similarity index 55% rename from src/main/java/com/github/gribanoveu/auth/entities/repositories/PermissionRepository.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java index 3afdf8a..16f65db 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/repositories/PermissionRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java @@ -1,14 +1,8 @@ -package com.github.gribanoveu.auth.entities.repositories; +package com.github.gribanoveu.cuddly.entities.repositories; -import com.github.gribanoveu.auth.entities.tables.Permission; -import jakarta.persistence.LockModeType; -import jakarta.transaction.Transactional; +import com.github.gribanoveu.cuddly.entities.tables.Permission; import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.Lock; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/repositories/UserRepository.java b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java similarity index 65% rename from src/main/java/com/github/gribanoveu/auth/entities/repositories/UserRepository.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java index 00698c4..197a02a 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/repositories/UserRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java @@ -1,11 +1,8 @@ -package com.github.gribanoveu.auth.entities.repositories; +package com.github.gribanoveu.cuddly.entities.repositories; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.entities.tables.User; import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/PermissionService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java similarity index 82% rename from src/main/java/com/github/gribanoveu/auth/entities/services/contract/PermissionService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java index c43d1ad..3c25502 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/PermissionService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.contract; -import com.github.gribanoveu.auth.entities.tables.Permission; +import com.github.gribanoveu.cuddly.entities.tables.Permission; import org.springframework.transaction.annotation.Transactional; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/RedisOtpService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/RedisOtpService.java similarity index 87% rename from src/main/java/com/github/gribanoveu/auth/entities/services/contract/RedisOtpService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/RedisOtpService.java index 64399bb..3091f87 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/RedisOtpService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/RedisOtpService.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.contract; import java.time.Duration; import java.util.Optional; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/TokenService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/TokenService.java similarity index 68% rename from src/main/java/com/github/gribanoveu/auth/entities/services/contract/TokenService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/TokenService.java index 8db53ac..bf9bbab 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/TokenService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/TokenService.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.contract; -import com.github.gribanoveu.auth.entities.enums.TokenType; -import com.github.gribanoveu.auth.security.CustomUserDetails; +import com.github.gribanoveu.cuddly.entities.enums.TokenType; +import com.github.gribanoveu.cuddly.security.CustomUserDetails; import java.util.Date; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/UserService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/UserService.java similarity index 86% rename from src/main/java/com/github/gribanoveu/auth/entities/services/contract/UserService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/UserService.java index 9a8ae57..3d713c8 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/contract/UserService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/UserService.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.contract; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.entities.tables.User; import org.springframework.transaction.annotation.Transactional; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/PermissionServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java similarity index 79% rename from src/main/java/com/github/gribanoveu/auth/entities/services/implementation/PermissionServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java index 92e7102..b8a7d18 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/PermissionServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.auth.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.implementation; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.Permissions; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.repositories.PermissionRepository; -import com.github.gribanoveu.auth.entities.services.contract.PermissionService; -import com.github.gribanoveu.auth.entities.tables.Permission; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.Permissions; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.repositories.PermissionRepository; +import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; +import com.github.gribanoveu.cuddly.entities.tables.Permission; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/RedisOtpServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/RedisOtpServiceImpl.java similarity index 86% rename from src/main/java/com/github/gribanoveu/auth/entities/services/implementation/RedisOtpServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/RedisOtpServiceImpl.java index 048e4be..cc8cd61 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/RedisOtpServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/RedisOtpServiceImpl.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.auth.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.implementation; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.services.contract.RedisOtpService; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.services.contract.RedisOtpService; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/TokenServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImpl.java similarity index 90% rename from src/main/java/com/github/gribanoveu/auth/entities/services/implementation/TokenServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImpl.java index 05ebd61..274cb54 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/TokenServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImpl.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.auth.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.implementation; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.TokenType; -import com.github.gribanoveu.auth.entities.services.contract.TokenService; -import com.github.gribanoveu.auth.security.CustomUserDetails; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.TokenType; +import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.security.CustomUserDetails; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import lombok.Getter; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/UserServiceImpl.java similarity index 83% rename from src/main/java/com/github/gribanoveu/auth/entities/services/implementation/UserServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/UserServiceImpl.java index 1f73462..58e2022 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/services/implementation/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/UserServiceImpl.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.auth.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.implementation; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.repositories.UserRepository; -import com.github.gribanoveu.auth.entities.services.contract.UserService; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.repositories.UserRepository; +import com.github.gribanoveu.cuddly.entities.services.contract.UserService; +import com.github.gribanoveu.cuddly.entities.tables.User; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/tables/Permission.java b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java similarity index 84% rename from src/main/java/com/github/gribanoveu/auth/entities/tables/Permission.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java index 7463d40..7373269 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/tables/Permission.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java @@ -1,6 +1,5 @@ -package com.github.gribanoveu.auth.entities.tables; +package com.github.gribanoveu.cuddly.entities.tables; -import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/auth/entities/tables/User.java b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java similarity index 93% rename from src/main/java/com/github/gribanoveu/auth/entities/tables/User.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java index 693417e..b88f8db 100644 --- a/src/main/java/com/github/gribanoveu/auth/entities/tables/User.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.auth.entities.tables; +package com.github.gribanoveu.cuddly.entities.tables; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.github.gribanoveu.auth.constants.Constants; +import com.github.gribanoveu.cuddly.constants.Constants; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/auth/security/CustomUserDetails.java b/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java similarity index 94% rename from src/main/java/com/github/gribanoveu/auth/security/CustomUserDetails.java rename to src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java index d860631..74bc5a9 100644 --- a/src/main/java/com/github/gribanoveu/auth/security/CustomUserDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.security; +package com.github.gribanoveu.cuddly.security; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.entities.tables.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/src/main/java/com/github/gribanoveu/auth/security/CustomUserDetailsService.java b/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetailsService.java similarity index 83% rename from src/main/java/com/github/gribanoveu/auth/security/CustomUserDetailsService.java rename to src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetailsService.java index 62b1cfd..4f50424 100644 --- a/src/main/java/com/github/gribanoveu/auth/security/CustomUserDetailsService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetailsService.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.security; +package com.github.gribanoveu.cuddly.security; -import com.github.gribanoveu.auth.entities.repositories.UserRepository; -import com.github.gribanoveu.auth.entities.tables.User; +import com.github.gribanoveu.cuddly.entities.repositories.UserRepository; +import com.github.gribanoveu.cuddly.entities.tables.User; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; diff --git a/src/main/java/com/github/gribanoveu/auth/utils/JsonUtils.java b/src/main/java/com/github/gribanoveu/cuddly/utils/JsonUtils.java similarity index 96% rename from src/main/java/com/github/gribanoveu/auth/utils/JsonUtils.java rename to src/main/java/com/github/gribanoveu/cuddly/utils/JsonUtils.java index 26e0312..25b5e04 100644 --- a/src/main/java/com/github/gribanoveu/auth/utils/JsonUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/JsonUtils.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.utils; +package com.github.gribanoveu.cuddly.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/main/java/com/github/gribanoveu/auth/utils/RsaProperties.java b/src/main/java/com/github/gribanoveu/cuddly/utils/RsaProperties.java similarity index 89% rename from src/main/java/com/github/gribanoveu/auth/utils/RsaProperties.java rename to src/main/java/com/github/gribanoveu/cuddly/utils/RsaProperties.java index a8e4d12..758c25b 100644 --- a/src/main/java/com/github/gribanoveu/auth/utils/RsaProperties.java +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/RsaProperties.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.utils; +package com.github.gribanoveu.cuddly.utils; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/test/java/com/github/gribanoveu/auth/AuthServiceApplicationTests.java b/src/test/java/com/github/gribanoveu/cuddly/AuthServiceApplicationTests.java similarity index 83% rename from src/test/java/com/github/gribanoveu/auth/AuthServiceApplicationTests.java rename to src/test/java/com/github/gribanoveu/cuddly/AuthServiceApplicationTests.java index b7f9710..3f5f137 100644 --- a/src/test/java/com/github/gribanoveu/auth/AuthServiceApplicationTests.java +++ b/src/test/java/com/github/gribanoveu/cuddly/AuthServiceApplicationTests.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth; +package com.github.gribanoveu.cuddly; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; diff --git a/src/test/java/com/github/gribanoveu/auth/base/BaseMockMvcTest.java b/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java similarity index 57% rename from src/test/java/com/github/gribanoveu/auth/base/BaseMockMvcTest.java rename to src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java index a7d1fbe..dcc3a79 100644 --- a/src/test/java/com/github/gribanoveu/auth/base/BaseMockMvcTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java @@ -1,14 +1,17 @@ -package com.github.gribanoveu.auth.base; +package com.github.gribanoveu.cuddly.base; -import com.github.gribanoveu.auth.entities.enums.TokenType; -import com.github.gribanoveu.auth.entities.services.contract.TokenService; -import com.github.gribanoveu.auth.security.CustomUserDetails; -import com.github.gribanoveu.auth.security.CustomUserDetailsService; +import com.github.gribanoveu.cuddly.entities.enums.TokenType; +import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.security.CustomUserDetails; +import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -18,9 +21,10 @@ * @author Evgeny Gribanov * @version 11.09.2023 */ -@AutoConfigureMockMvc +@SpringBootTest @Testcontainers -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@TestPropertySource(properties = {"spring.config.location=classpath:application-properties.yml"}) public abstract class BaseMockMvcTest { @Autowired protected MockMvc mockMvc; @Autowired protected TestJsonUtils testJsonUtils; @@ -30,6 +34,22 @@ public abstract class BaseMockMvcTest { protected String adminToken; protected String userToken; + private static final String DATABASE_NAME = "auth_service_db"; + + @Container + @ServiceConnection + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:15.4-alpine") + .withReuse(true) + .withDatabaseName(DATABASE_NAME); + + @DynamicPropertySource + static void dataSources(DynamicPropertyRegistry registry) { + registry.add("CONTAINER.URL", postgres::getJdbcUrl); + registry.add("CONTAINER.USERNAME", postgres::getUsername); + registry.add("CONTAINER.PASSWORD", postgres::getPassword); + } + @BeforeEach public void setUp() { // fixme why @WithUserDetails is not working var admin = (CustomUserDetails) usrDetailsService.loadUserByUsername("admin@email.com"); @@ -39,9 +59,4 @@ public void setUp() { // fixme why @WithUserDetails is not working userToken = "Bearer " + tokenService.generateToken(user, TokenType.ACCESS); } - @Container - @ServiceConnection - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>("postgres:15.4-alpine"); - } diff --git a/src/test/java/com/github/gribanoveu/auth/base/BaseValidatorTest.java b/src/test/java/com/github/gribanoveu/cuddly/base/BaseValidatorTest.java similarity index 93% rename from src/test/java/com/github/gribanoveu/auth/base/BaseValidatorTest.java rename to src/test/java/com/github/gribanoveu/cuddly/base/BaseValidatorTest.java index dd6d90e..46459fa 100644 --- a/src/test/java/com/github/gribanoveu/auth/base/BaseValidatorTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/base/BaseValidatorTest.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.base; +package com.github.gribanoveu.cuddly.base; import jakarta.validation.Validation; import jakarta.validation.Validator; diff --git a/src/test/java/com/github/gribanoveu/auth/base/ContainersConfig.java b/src/test/java/com/github/gribanoveu/cuddly/base/ContainersConfig.java similarity index 92% rename from src/test/java/com/github/gribanoveu/auth/base/ContainersConfig.java rename to src/test/java/com/github/gribanoveu/cuddly/base/ContainersConfig.java index e9d8ded..f8e9bea 100644 --- a/src/test/java/com/github/gribanoveu/auth/base/ContainersConfig.java +++ b/src/test/java/com/github/gribanoveu/cuddly/base/ContainersConfig.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.base; +package com.github.gribanoveu.cuddly.base; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; diff --git a/src/test/java/com/github/gribanoveu/auth/base/TestJsonUtils.java b/src/test/java/com/github/gribanoveu/cuddly/base/TestJsonUtils.java similarity index 97% rename from src/test/java/com/github/gribanoveu/auth/base/TestJsonUtils.java rename to src/test/java/com/github/gribanoveu/cuddly/base/TestJsonUtils.java index 0bca9a9..9312ece 100644 --- a/src/test/java/com/github/gribanoveu/auth/base/TestJsonUtils.java +++ b/src/test/java/com/github/gribanoveu/cuddly/base/TestJsonUtils.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.auth.base; +package com.github.gribanoveu.cuddly.base; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangeEmailDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java similarity index 91% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangeEmailDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java index d54f8bd..683e151 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangeEmailDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangePasswordDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java similarity index 95% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangePasswordDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java index b1b443b..c9cdb88 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/ChangePasswordDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/GenerateOtpDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java similarity index 91% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/GenerateOtpDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java index dcaa516..5fa8437 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/GenerateOtpDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/LoginDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java similarity index 94% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/LoginDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java index 8b865d3..2ef582c 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/LoginDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/PermissionDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java similarity index 88% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/PermissionDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java index 0d91cc4..83296ca 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/PermissionDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; @@ -36,7 +36,7 @@ void testInvalidPermissionDtoWithLongPermissionName() { PermissionDto permissionDto = new PermissionDto(longPermissionName); Set> violations = validator.validate(permissionDto); Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .containsAll(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE, ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); + .containsAll(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE, ValidationMessages.SIZE_EXCEPTION_MESSAGE)); } @Test diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/RegisterDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java similarity index 94% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/RegisterDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java index dcd3171..295df97 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/RegisterDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/RestorePasswordDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java similarity index 96% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/RestorePasswordDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java index 62c2e64..db9b8fc 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/RestorePasswordDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/UpdatePermissionDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java similarity index 95% rename from src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/UpdatePermissionDtoTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java index 235760e..16903d6 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/dtos/request/UpdatePermissionDtoTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.auth.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request; -import com.github.gribanoveu.auth.base.BaseValidatorTest; -import com.github.gribanoveu.auth.constants.ValidationMessages; +import com.github.gribanoveu.cuddly.base.BaseValidatorTest; +import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.ConstraintViolation; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/endpoints/PermissionControllerTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java similarity index 95% rename from src/test/java/com/github/gribanoveu/auth/controllers/endpoints/PermissionControllerTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java index 2f1e67f..ad77121 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/endpoints/PermissionControllerTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java @@ -1,12 +1,12 @@ -package com.github.gribanoveu.auth.controllers.endpoints; - -import com.github.gribanoveu.auth.base.BaseMockMvcTest; -import com.github.gribanoveu.auth.controllers.dtos.request.PermissionDto; -import com.github.gribanoveu.auth.controllers.dtos.request.UpdatePermissionDto; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.services.contract.PermissionService; -import com.github.gribanoveu.auth.entities.tables.Permission; +package com.github.gribanoveu.cuddly.controllers.endpoints; + +import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; +import com.github.gribanoveu.cuddly.controllers.dtos.request.PermissionDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.UpdatePermissionDto; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; +import com.github.gribanoveu.cuddly.entities.tables.Permission; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -171,10 +171,12 @@ void testGetAllPermissions_withoutPagination_throwsException() throws Exception @Test void testGetAllPermissions_asUser_throwsException() throws Exception { this.mockMvc.perform(get("/v1/permission") - .header("Authorization", userToken)) + .param("pageNumber", "0") + .param("pageSize", "1")) + // .header("Authorization", "userToken")) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.ACCESS_DENIED.getMessage())); + .andExpect(jsonPath("$..details[0].message").value("Full authentication is required to access this resource")); } @Test @@ -259,8 +261,8 @@ void updatePermission_asUser_throwsException() throws Exception { var updatePermissionDto = new UpdatePermissionDto(permissionName, "BE_NOT_UPDATED_UPD"); - this.mockMvc.perform(put("/v1/permission") + .contentType(MediaType.APPLICATION_JSON) .content(testJsonUtils.convertDtoToJson(updatePermissionDto)) .header("Authorization", userToken)) .andExpect(status().isUnauthorized()) diff --git a/src/test/java/com/github/gribanoveu/auth/controllers/endpoints/TokenControllerTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java similarity index 92% rename from src/test/java/com/github/gribanoveu/auth/controllers/endpoints/TokenControllerTest.java rename to src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java index 9b271d1..3149938 100644 --- a/src/test/java/com/github/gribanoveu/auth/controllers/endpoints/TokenControllerTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java @@ -1,12 +1,12 @@ -package com.github.gribanoveu.auth.controllers.endpoints; - -import com.github.gribanoveu.auth.base.BaseMockMvcTest; -import com.github.gribanoveu.auth.controllers.dtos.request.LoginDto; -import com.github.gribanoveu.auth.entities.enums.ResponseCode; -import com.github.gribanoveu.auth.entities.enums.TokenType; -import com.github.gribanoveu.auth.entities.services.implementation.TokenServiceImpl; -import com.github.gribanoveu.auth.security.CustomUserDetails; -import com.github.gribanoveu.auth.security.CustomUserDetailsService; +package com.github.gribanoveu.cuddly.controllers.endpoints; + +import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; +import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.TokenType; +import com.github.gribanoveu.cuddly.entities.services.implementation.TokenServiceImpl; +import com.github.gribanoveu.cuddly.security.CustomUserDetails; +import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/github/gribanoveu/auth/entities/services/implementation/TokenServiceImplTest.java b/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java similarity index 92% rename from src/test/java/com/github/gribanoveu/auth/entities/services/implementation/TokenServiceImplTest.java rename to src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java index 67874a8..11a4ee4 100644 --- a/src/test/java/com/github/gribanoveu/auth/entities/services/implementation/TokenServiceImplTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.auth.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.implementation; -import com.github.gribanoveu.auth.base.BaseMockMvcTest; -import com.github.gribanoveu.auth.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.auth.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/github/gribanoveu/auth/utils/JsonUtilsTest.java b/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java similarity index 90% rename from src/test/java/com/github/gribanoveu/auth/utils/JsonUtilsTest.java rename to src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java index 22c3860..97c2d84 100644 --- a/src/test/java/com/github/gribanoveu/auth/utils/JsonUtilsTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.auth.utils; +package com.github.gribanoveu.cuddly.utils; -import com.github.gribanoveu.auth.controllers.dtos.request.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/resources/application.yml b/src/test/resources/application-properties.yml similarity index 64% rename from src/test/resources/application.yml rename to src/test/resources/application-properties.yml index 1f6ebfa..2e5ccde 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application-properties.yml @@ -10,6 +10,16 @@ rsa: private-key: classpath:certs/test-private.pem public-key: classpath:certs/test-public.pem spring: + datasource: + url: ${CONTAINER.URL} + username: ${CONTAINER.USERNAME} + password: ${CONTAINER.PASSWORD} + driver-class-name: org.postgresql.Driver + flyway: + driver-class-name: org.postgresql.Driver + url: ${CONTAINER.URL} + user: ${CONTAINER.USERNAME} + password: ${CONTAINER.PASSWORD} mvc: throw-exception-if-no-handler-found: true web: From cea9c468a9fb493282020b7fb7ad341e5794ecff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 24 Oct 2023 14:19:22 +0300 Subject: [PATCH 02/34] refactor code Took 8 hours 46 minutes --- mvnw.cmd | 2 +- .../cuddly/config/SecurityConfig.java | 10 +- .../cuddly/constants/RegexpFormat.java | 1 + .../cuddly/constants/ValidationMessages.java | 1 + .../request/{ => admin}/PermissionDto.java | 2 +- .../{ => admin}/UpdatePermissionDto.java | 2 +- .../request/{ => auth}/ChangeEmailDto.java | 2 +- .../request/{ => auth}/ChangePasswordDto.java | 2 +- .../request/{ => auth}/GenerateOtpDto.java | 2 +- .../dtos/request/{ => auth}/LoginDto.java | 2 +- .../dtos/request/{ => auth}/RegisterDto.java | 10 +- .../{ => auth}/RestorePasswordDto.java | 2 +- .../dtos/response/TokenResponse.java | 29 -- .../{ => auth}/PermissionsResponse.java | 8 +- .../dtos/response/auth/TokenResponse.java | 34 ++ .../response/{ => auth}/UsersResponse.java | 5 +- .../endpoints/ManagementController.java | 49 --- .../endpoints/PermissionController.java | 40 --- .../endpoints/admin/AdminController.java | 49 +++ .../{ => auth}/AccountController.java | 12 +- .../endpoints/{ => auth}/TokenController.java | 8 +- .../endpoints/{ => auth}/UserController.java | 20 +- .../exeptions/GlobalExceptionHandler.java | 2 + .../entrypoint/AccessDeniedEntryPoint.java | 1 + .../AuthenticationFailureEntryPoint.java | 37 ++ .../entrypoint/ServerErrorEntryPoint.java | 16 +- .../facade/PermissionControllerFacade.java | 52 --- .../facade/UserControllerFacade.java | 23 -- .../AdminControllerFacade.java} | 42 +-- .../{ => auth}/AccountControllerFacade.java | 14 +- .../{ => auth}/TokenControllerFacade.java | 15 +- .../facade/auth/UserControllerFacade.java | 62 ++++ .../cuddly/entities/enums/ResponseCode.java | 33 +- .../enums/{Permissions.java => Role.java} | 15 +- .../repositories/PermissionRepository.java | 8 +- .../entities/repositories/UserRepository.java | 1 + .../services/contract/PermissionService.java | 20 -- .../implementation/PermissionServiceImpl.java | 68 ---- .../{contract => otp}/RedisOtpService.java | 2 +- .../RedisOtpServiceImpl.java | 6 +- .../permission/PermissionService.java | 21 ++ .../{contract => token}/TokenService.java | 2 +- .../TokenServiceImpl.java | 10 +- .../{contract => user}/UserService.java | 4 +- .../UserServiceImpl.java | 16 +- .../cuddly/entities/tables/Permission.java | 31 -- .../cuddly/entities/tables/User.java | 30 +- .../cuddly/security/CustomUserDetails.java | 18 +- .../cuddly/utils/validators/MinimalAge.java | 26 ++ .../utils/validators/MinimalAgeValidator.java | 34 ++ .../db/migration/V1_0__create_users_table.sql | 36 +- .../db/migration/V2_0__add_users_data.sql | 28 +- .../cuddly/base/BaseMockMvcTest.java | 2 +- .../dtos/request/ChangeEmailDtoTest.java | 49 --- .../dtos/request/ChangePasswordDtoTest.java | 76 ---- .../dtos/request/GenerateOtpDtoTest.java | 50 --- .../dtos/request/LoginDtoTest.java | 83 ----- .../dtos/request/PermissionDtoTest.java | 49 --- .../dtos/request/RegisterDtoTest.java | 76 ---- .../dtos/request/RestorePasswordDtoTest.java | 91 ----- .../dtos/request/UpdatePermissionDtoTest.java | 74 ---- .../endpoints/PermissionControllerTest.java | 337 ------------------ .../endpoints/TokenControllerTest.java | 137 ------- .../implementation/TokenServiceImplTest.java | 2 +- .../cuddly/utils/JsonUtilsTest.java | 2 +- 65 files changed, 479 insertions(+), 1514 deletions(-) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => admin}/PermissionDto.java (90%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => admin}/UpdatePermissionDto.java (92%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => auth}/ChangeEmailDto.java (89%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => auth}/ChangePasswordDto.java (91%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => auth}/GenerateOtpDto.java (89%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => auth}/LoginDto.java (91%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => auth}/RegisterDto.java (72%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/{ => auth}/RestorePasswordDto.java (94%) delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/{ => auth}/PermissionsResponse.java (79%) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java rename src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/{ => auth}/UsersResponse.java (83%) delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java rename src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/{ => auth}/AccountController.java (73%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/{ => auth}/TokenController.java (72%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/{ => auth}/UserController.java (52%) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java rename src/main/java/com/github/gribanoveu/cuddly/controllers/facade/{ManagementControllerFacade.java => admin/AdminControllerFacade.java} (53%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/facade/{ => auth}/AccountControllerFacade.java (88%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/facade/{ => auth}/TokenControllerFacade.java (76%) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java rename src/main/java/com/github/gribanoveu/cuddly/entities/enums/{Permissions.java => Role.java} (52%) delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java rename src/main/java/com/github/gribanoveu/cuddly/entities/services/{contract => otp}/RedisOtpService.java (87%) rename src/main/java/com/github/gribanoveu/cuddly/entities/services/{implementation => otp}/RedisOtpServiceImpl.java (91%) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java rename src/main/java/com/github/gribanoveu/cuddly/entities/services/{contract => token}/TokenService.java (89%) rename src/main/java/com/github/gribanoveu/cuddly/entities/services/{implementation => token}/TokenServiceImpl.java (92%) rename src/main/java/com/github/gribanoveu/cuddly/entities/services/{contract => user}/UserService.java (81%) rename src/main/java/com/github/gribanoveu/cuddly/entities/services/{implementation => user}/UserServiceImpl.java (81%) delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java delete mode 100644 src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java diff --git a/mvnw.cmd b/mvnw.cmd index 95ba6f5..4640c15 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -13,7 +13,7 @@ @REM software distributed under the License is distributed on an @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations +@REM specific language governing roles and limitations @REM under the License. @REM ---------------------------------------------------------------------------- diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index 502642a..f702535 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -3,10 +3,12 @@ import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AuthErrorEntryPoint; import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.ServerErrorEntryPoint; +import com.github.gribanoveu.cuddly.entities.enums.Role; import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; @@ -20,8 +22,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; -import static com.github.gribanoveu.cuddly.entities.enums.Permissions.AU_PERMISSIONS_MANAGEMENT; -import static com.github.gribanoveu.cuddly.entities.enums.Permissions.AU_USERS_MANAGEMENT; +import static com.github.gribanoveu.cuddly.entities.enums.Role.*; /** * @author Evgeny Gribanov @@ -43,8 +44,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(CsrfConfigurer::disable) .cors(CorsConfigurer::disable) .authorizeHttpRequests(req -> req - .requestMatchers("*/permission").hasAuthority(AU_PERMISSIONS_MANAGEMENT.scope()) - .requestMatchers("*/user-manage/**").hasAuthority(AU_USERS_MANAGEMENT.scope()) + .requestMatchers(HttpMethod.POST, "*/user").anonymous() // register + .requestMatchers("*/role").hasAuthority(ADMIN.scope()) + .requestMatchers("*/users/**").hasAuthority(MODERATOR.scope()) .requestMatchers("*/token/**").permitAll() // allow auth and anonymous users .requestMatchers("*/account/generate-code").anonymous() // allow only anonymous .requestMatchers("*/account/restore-password").anonymous() diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java b/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java index 6ab9ba7..ada6e50 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java @@ -8,4 +8,5 @@ public class RegexpFormat { public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; public static final String PERMISSION_PATTERN = "^[A-Z]{2}_[A-Z_]+$"; public static final String OTP_PATTERN = "^\\d{6}$"; + public static final String BIRTHDAY_PATTERN = "^(19\\d{2}|20\\d{2}|2100)-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$"; } diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java b/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java index 1237158..90e3a60 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java @@ -9,4 +9,5 @@ public class ValidationMessages { public static final String NOT_BLANK_EXCEPTION_MESSAGE = "cannot be empty"; public static final String PATTERN_EXCEPTION_MESSAGE = "must match the expected format"; public static final String SIZE_EXCEPTION_MESSAGE = "size should be no larger than expected"; + public static final String MINIMAL_AGE_EXCEPTION_MESSAGE = "must be at least 18 years old, or have expected format"; } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/PermissionDto.java similarity index 90% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/PermissionDto.java index 1843f26..1632291 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/PermissionDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.admin; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/UpdatePermissionDto.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/UpdatePermissionDto.java index 0f41c57..d09841a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/UpdatePermissionDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.admin; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java index 0efe193..c3ddc51 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java similarity index 91% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java index 90eb023..11842db 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java index 8b4f2d5..f9935f0 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java similarity index 91% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java index 40637f1..6c0768b 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java similarity index 72% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java index 0a34902..1dc3364 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java @@ -1,8 +1,7 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.Pattern; -import jakarta.validation.constraints.Size; +import com.github.gribanoveu.cuddly.utils.validators.MinimalAge; +import jakarta.validation.constraints.*; import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; @@ -17,6 +16,9 @@ public record RegisterDto( @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) String email, + @MinimalAge(message = MINIMAL_AGE_EXCEPTION_MESSAGE) + String birthDate, // todo write tests + @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String password, diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java similarity index 94% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java index 6ef2e2e..250b2ba 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java deleted file mode 100644 index f72c8ec..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/TokenResponse.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.springframework.http.HttpStatus; - -import java.time.LocalDateTime; - -/** - * @author Evgeny Gribanov - * @version 25.09.2023 - */ -@Data -@AllArgsConstructor -@JsonInclude(JsonInclude.Include.NON_NULL) -public class TokenResponse { - private LocalDateTime timestamp; - private StatusLevel status; - private Long tokenLifetimeMin; - private String accessToken; - private String refreshToken; - - public static TokenResponse create(HttpStatus status, Long accessTokenLifetime, String accessToken, String refreshToken) { - return new TokenResponse(LocalDateTime.now(), StatusLevel.SUCCESS, - accessTokenLifetime, accessToken, refreshToken); - } -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/PermissionsResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/PermissionsResponse.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java index 92fb556..25cfb62 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/PermissionsResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; +import com.github.gribanoveu.cuddly.entities.enums.Role; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.tables.Permission; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; @@ -22,9 +22,9 @@ public class PermissionsResponse { @JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Europe/Moscow") private LocalDateTime timestamp; private StatusLevel status; - private Collection permissions; + private Collection permissions; - public static PermissionsResponse create(HttpStatus status, Collection permissions) { + public static PermissionsResponse create(HttpStatus status, Collection permissions) { return new PermissionsResponse(LocalDateTime.now(), StatusLevel.SUCCESS, permissions); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java new file mode 100644 index 0000000..12d5485 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java @@ -0,0 +1,34 @@ +package com.github.gribanoveu.cuddly.controllers.dtos.response.auth; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.springframework.http.HttpStatus; + +import java.time.LocalDateTime; + +/** + * @author Evgeny Gribanov + * @version 25.09.2023 + */ +@Data +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class TokenResponse { + private LocalDateTime timestamp; + @JsonProperty("access_token") private String accessToken; + @JsonProperty("token_type") private String type; + @JsonProperty("expires_in") private Long accessLifetimeMin; + @JsonProperty("refresh_token") private String refreshToken; + + public static TokenResponse create( + Long accessTokenLifetime, + String accessToken, + String refreshToken + ) { + return new TokenResponse(LocalDateTime.now(), accessToken, "Bearer", + accessTokenLifetime, refreshToken); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java similarity index 83% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/UsersResponse.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java index c719ebc..0cdb474 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response; +package com.github.gribanoveu.cuddly.controllers.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; @@ -25,7 +25,6 @@ public class UsersResponse { private Collection users; public static UsersResponse create(HttpStatus status, Collection users) { - return new UsersResponse( - LocalDateTime.now(), StatusLevel.SUCCESS, users); + return new UsersResponse(LocalDateTime.now(), StatusLevel.SUCCESS, users); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java deleted file mode 100644 index 316d420..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/ManagementController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; - -import com.github.gribanoveu.cuddly.controllers.dtos.request.RegisterDto; -import com.github.gribanoveu.cuddly.controllers.facade.ManagementControllerFacade; -import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -/** - * @author Evgeny Gribanov - * @version 22.09.2023 - */ -@RestController -@RequiredArgsConstructor -@RequestMapping("/v1/user-manage") -public class ManagementController { - private final ManagementControllerFacade managementControllerFacade; - - @GetMapping("/all") - public ResponseEntity getAllUsersList(@RequestParam int pageNumber, @RequestParam int pageSize) { - return managementControllerFacade.getAllUsersList(pageNumber, pageSize); - } - - @PostMapping("/add") // only admin can add new users - public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { - return managementControllerFacade.registerUser(request); - } - - @DeleteMapping("/{userId}") // only admin can delete user - public ResponseEntity deleteUser(@PathVariable Long userId) { - return managementControllerFacade.deleteUser(userId); - } - - @PatchMapping("/{userId}/disable") - public ResponseEntity disableUser(@PathVariable Long userId) { - return managementControllerFacade.disableUser(userId); - } - - @PatchMapping("/{userId}/enable") - public ResponseEntity enableUser(@PathVariable Long userId) { - return managementControllerFacade.enabledUser(userId); - } - - @PatchMapping("/{userId}/reset-password") - public ResponseEntity resetUserPasswordToDefault(@PathVariable Long userId) { - return managementControllerFacade.resetUserPasswordToDefault(userId); - } -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java deleted file mode 100644 index 736ed9c..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionController.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; - -import com.github.gribanoveu.cuddly.controllers.dtos.request.PermissionDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.UpdatePermissionDto; -import com.github.gribanoveu.cuddly.controllers.facade.PermissionControllerFacade; -import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -/** - * @author Evgeny Gribanov - * @version 08.09.2023 - */ -@RestController -@RequiredArgsConstructor -@RequestMapping("/v1/permission") -public class PermissionController { - private final PermissionControllerFacade permissionControllerFacade; - - @GetMapping() - public ResponseEntity getPermission(@RequestParam int pageNumber, @RequestParam int pageSize) { - return permissionControllerFacade.getAllPermissions(pageNumber, pageSize); - } - - @PostMapping - public ResponseEntity addPermission(@Valid @RequestBody PermissionDto request) { - return permissionControllerFacade.addPermission(request); - } - - @PutMapping - public ResponseEntity updatePermission(@Valid @RequestBody UpdatePermissionDto request) { - return permissionControllerFacade.updatePermission(request); - } - - @DeleteMapping - public ResponseEntity deletePermission(@RequestParam String permissionName) { - return permissionControllerFacade.deletePermission(permissionName); - } -} \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java new file mode 100644 index 0000000..53b394d --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java @@ -0,0 +1,49 @@ +package com.github.gribanoveu.cuddly.controllers.endpoints.admin; + +import com.github.gribanoveu.cuddly.controllers.facade.admin.AdminControllerFacade; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.*; + +/** + * @author Evgeny Gribanov + * @version 22.09.2023 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/v1/users") +public class AdminController { + private final AdminControllerFacade adminControllerFacade; + + @GetMapping + public ResponseEntity getAllUsersList(@RequestParam int pageNumber, @RequestParam int pageSize) { + return adminControllerFacade.getAllUsersList(pageNumber, pageSize); + } + + @DeleteMapping("/{userId}") // only admin can delete user + public ResponseEntity deleteUser(@PathVariable Long userId) { + return adminControllerFacade.deleteUser(userId); + } + + @PatchMapping("/{userId}/disable") + public ResponseEntity disableUser(@PathVariable Long userId) { + return adminControllerFacade.disableUser(userId); + } + + @PatchMapping("/{userId}/enable") + public ResponseEntity enableUser(@PathVariable Long userId) { + return adminControllerFacade.enabledUser(userId); + } + + @PatchMapping("/{userId}/ban") + public ResponseEntity banUser(@PathVariable Long userId) { + return adminControllerFacade.banUser(userId); + } + + @PatchMapping("/{userId}/mercy") + public ResponseEntity mercyUser(@PathVariable Long userId) { + return adminControllerFacade.mercyUser(userId); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/AccountController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java similarity index 73% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/AccountController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java index 3f01716..9030cb7 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangeEmailDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangePasswordDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.GenerateOtpDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.RestorePasswordDto; -import com.github.gribanoveu.cuddly.controllers.facade.AccountControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RestorePasswordDto; +import com.github.gribanoveu.cuddly.controllers.facade.auth.AccountControllerFacade; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/TokenController.java similarity index 72% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/TokenController.java index ed90de1..0aec4b0 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/TokenController.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.TokenResponse; -import com.github.gribanoveu.cuddly.controllers.facade.TokenControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddly.controllers.facade.auth.TokenControllerFacade; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/UserController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java similarity index 52% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/UserController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java index 212382f..13572e0 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java @@ -1,12 +1,12 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; +package com.github.gribanoveu.cuddly.controllers.endpoints.auth; -import com.github.gribanoveu.cuddly.controllers.facade.UserControllerFacade; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddly.controllers.facade.auth.UserControllerFacade; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; /** * @author Evgeny Gribanov @@ -25,4 +25,14 @@ public class UserController { public ResponseEntity getUserData(Authentication authentication) { return userControllerFacade.getUserData(authentication); } + + @PostMapping + public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { + return userControllerFacade.registerUser(request); + } + + @DeleteMapping + public ResponseEntity deleteUser(Authentication authentication) { + return userControllerFacade.deleteUser(authentication); + } } \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java index 9db072f..0602ed3 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java @@ -16,6 +16,8 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; +import java.time.DateTimeException; + /** * @author Evgeny Gribanov * @version 07.07.2023 diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java index 0ab1541..2648033 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java @@ -9,6 +9,7 @@ import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.DisabledException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java new file mode 100644 index 0000000..89d5a74 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java @@ -0,0 +1,37 @@ +package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; + +import com.github.gribanoveu.cuddly.utils.JsonUtils; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.DisabledException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * @author Evgeny Gribanov + * @version 20.10.2023 + */ +@Component +@RequiredArgsConstructor +public class AuthenticationFailureEntryPoint implements AuthenticationFailureHandler { + private final JsonUtils jsonUtils; + + @Override + public void onAuthenticationFailure( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException exception + ) throws IOException, ServletException { + if (exception instanceof DisabledException) { + response.sendError(HttpStatus.UNAUTHORIZED.value(), "User is disabled"); + } else { + response.sendError(HttpStatus.UNAUTHORIZED.value(), exception.getMessage()); + } + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java index cc609a6..68db77a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -7,12 +7,17 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.DisabledException; +import org.springframework.security.authentication.LockedException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import java.io.IOException; +import static com.github.gribanoveu.cuddly.entities.enums.ResponseCode.*; + /** * @author Evgeny Gribanov * @version 06.09.2023 @@ -28,8 +33,15 @@ public void commence( HttpServletResponse response, AuthenticationException authException ) throws IOException { - var error = StatusResponse.create( - ResponseCode.ACCESS_DENIED, authException.getMessage(), StatusLevel.ERROR); + StatusResponse error = null; + + if (authException instanceof DisabledException) { + error = StatusResponse.create(ACCOUNT_DISABLED, ACCOUNT_DISABLED.getMessage(), StatusLevel.ERROR); + + } else if (authException instanceof LockedException) { + error = StatusResponse.create(ACCOUNT_BANNED, ACCOUNT_BANNED.getMessage(), StatusLevel.ERROR); + + } else error = StatusResponse.create(ACCESS_DENIED, authException.getMessage(), StatusLevel.ERROR); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java deleted file mode 100644 index 60c54e8..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/PermissionControllerFacade.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.facade; - -import com.github.gribanoveu.cuddly.controllers.dtos.request.PermissionDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.UpdatePermissionDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.PermissionsResponse; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; -import com.github.gribanoveu.cuddly.entities.tables.Permission; -import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -/** - * @author Evgeny Gribanov - * @version 25.09.2023 - */ -@Service -@RequiredArgsConstructor -public class PermissionControllerFacade { - private final PermissionService permissionService; - - public ResponseEntity getAllPermissions(int pageNumber, int pageSize) { - return ResponseEntity.ok(PermissionsResponse.create( - HttpStatus.OK, permissionService.getAllPermissions(pageNumber, pageSize))); - } - - public ResponseEntity addPermission(PermissionDto request) { - var permissionName = request.permissionName().toUpperCase(); - if (permissionService.permissionExistByName(permissionName)) - throw new CredentialEx(ResponseCode.PERMISSION_EXIST); - - var permission = new Permission(); - permission.setName(permissionName); - - permissionService.save(permission); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.PERMISSION_CREATED, StatusLevel.SUCCESS)); - } - - public ResponseEntity deletePermission(String permissionName) { - permissionService.deletePermissionByName(permissionName); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.PERMISSION_DELETED, StatusLevel.SUCCESS)); - } - - public ResponseEntity updatePermission(UpdatePermissionDto request) { - permissionService.updatePermissionName(request.permissionName(), request.newName()); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.PERMISSION_UPDATED, StatusLevel.SUCCESS)); - } -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java deleted file mode 100644 index e522440..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/UserControllerFacade.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.facade; - -import com.github.gribanoveu.cuddly.entities.services.contract.UserService; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Service; - -/** - * @author Evgeny Gribanov - * @version 29.08.2023 - */ -@Service -@RequiredArgsConstructor -public class UserControllerFacade { - private final UserService userService; - - public ResponseEntity getUserData(Authentication authentication) { - var userData = userService.findUserByEmail(authentication.getName()); - return ResponseEntity.ok(userData); - } -} - diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/ManagementControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/AdminControllerFacade.java similarity index 53% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/ManagementControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/AdminControllerFacade.java index 486e649..e277789 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/ManagementControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/AdminControllerFacade.java @@ -1,22 +1,15 @@ -package com.github.gribanoveu.cuddly.controllers.facade; +package com.github.gribanoveu.cuddly.controllers.facade.admin; -import com.github.gribanoveu.cuddly.constants.Constants; -import com.github.gribanoveu.cuddly.controllers.dtos.request.RegisterDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.dtos.response.UsersResponse; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.UsersResponse; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; -import com.github.gribanoveu.cuddly.entities.services.contract.UserService; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddly.entities.services.user.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; -import java.util.Set; - import static org.springframework.http.HttpStatus.OK; /** @@ -25,28 +18,14 @@ */ @Service @RequiredArgsConstructor -public class ManagementControllerFacade { +public class AdminControllerFacade { private final UserService userService; - private final PermissionService permissionService; private final PasswordEncoder passwordEncoder; public ResponseEntity getAllUsersList(int pageNumber, int pageSize) { return ResponseEntity.ok(UsersResponse.create(OK, userService.getAllUsers(pageNumber, pageSize))); } - public ResponseEntity registerUser(RegisterDto request) { - if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); - if (userService.userExistByEmail(request.email())) throw new CredentialEx(ResponseCode.USER_ALREADY_EXIST); - - var user = new User(); - user.setEmail(request.email()); - user.setPassword(passwordEncoder.encode(request.password())); - user.setPermissionCollection(Set.of(permissionService.getDefaultUserPermission())); - - userService.saveUser(user); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_CREATED, StatusLevel.SUCCESS)); - } - public ResponseEntity deleteUser(Long userId) { userService.deleteUserById(userId); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS)); @@ -64,10 +43,15 @@ public ResponseEntity enabledUser(Long userId) { return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_ENABLED, StatusLevel.SUCCESS)); } - public ResponseEntity resetUserPasswordToDefault(Long userId) { + public ResponseEntity banUser(Long userId) { + var user = userService.findUserById(userId); + userService.updateLocked(user, true); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_BANNED, StatusLevel.SUCCESS)); + } + + public ResponseEntity mercyUser(Long userId) { var user = userService.findUserById(userId); - userService.updateUserPasswordAndCredentialsExpiredById(user, - passwordEncoder.encode(Constants.DEFAULT_PASSWORD)); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DEFAULT_PASSWORD, StatusLevel.SUCCESS)); + userService.updateLocked(user, false); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UN_BANNED, StatusLevel.SUCCESS)); } } \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/AccountControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java index 927befb..9ca603c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java @@ -1,15 +1,15 @@ -package com.github.gribanoveu.cuddly.controllers.facade; +package com.github.gribanoveu.cuddly.controllers.facade.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangeEmailDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.ChangePasswordDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.GenerateOtpDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.RestorePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RestorePasswordDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.services.contract.RedisOtpService; -import com.github.gribanoveu.cuddly.entities.services.contract.UserService; +import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; +import com.github.gribanoveu.cuddly.entities.services.user.UserService; import com.github.gribanoveu.cuddly.utils.JsonUtils; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/TokenControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/TokenControllerFacade.java similarity index 76% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/TokenControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/TokenControllerFacade.java index 30b1bd6..126e216 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/TokenControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/TokenControllerFacade.java @@ -1,15 +1,14 @@ -package com.github.gribanoveu.cuddly.controllers.facade; +package com.github.gribanoveu.cuddly.controllers.facade.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.TokenResponse; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.entities.services.token.TokenService; import com.github.gribanoveu.cuddly.security.CustomUserDetails; import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -36,8 +35,7 @@ public ResponseEntity authenticateUser(LoginDto request) { var accessToken = tokenService.generateToken(user, TokenType.ACCESS); var refreshToken = tokenService.generateToken(user, TokenType.REFRESH); - return ResponseEntity.ok(TokenResponse.create( - HttpStatus.OK, accessTokenLifetime.toMinutes(), accessToken, refreshToken)); + return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, refreshToken)); } public ResponseEntity refreshToken(HttpServletRequest request) { @@ -48,8 +46,7 @@ public ResponseEntity refreshToken(HttpServletRequest request) { var accessToken = tokenService.generateToken(user, TokenType.ACCESS); var refreshToken = tokenService.generateToken(user, TokenType.REFRESH); - return ResponseEntity.ok(TokenResponse.create( - HttpStatus.OK, accessTokenLifetime.toMinutes(), accessToken, refreshToken)); + return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, refreshToken)); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java new file mode 100644 index 0000000..b754fac --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java @@ -0,0 +1,62 @@ +package com.github.gribanoveu.cuddly.controllers.facade.auth; + +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.Role; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.services.user.UserService; +import com.github.gribanoveu.cuddly.entities.tables.User; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.time.LocalDate; +import java.time.Month; +import java.time.format.DateTimeFormatter; +import java.util.Set; + +/** + * @author Evgeny Gribanov + * @version 29.08.2023 + */ +@Service +@RequiredArgsConstructor +public class UserControllerFacade { + private final UserService userService; + private final PasswordEncoder passwordEncoder; + + public ResponseEntity getUserData(Authentication authentication) { + var userData = userService.findUserByEmail(authentication.getName()); + return ResponseEntity.ok(userData); + } + + public ResponseEntity registerUser(RegisterDto request) { + if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); + if (userService.userExistByEmail(request.email())) throw new CredentialEx(ResponseCode.USER_ALREADY_EXIST); + + var user = new User(); + user.setEmail(request.email()); + user.setBirthDate(LocalDate.parse(request.birthDate(), DateTimeFormatter.ISO_LOCAL_DATE)); // yyyy-MM-dd + user.setPassword(passwordEncoder.encode(request.password())); + user.setRole(Role.USER); + userService.saveUser(user); + + var location = ServletUriComponentsBuilder + .fromCurrentContextPath().path("/v1/user/{id}") + .buildAndExpand(user.getId()).toUri(); + + return ResponseEntity.created (location).body(StatusResponse.create( + ResponseCode.USER_CREATED, StatusLevel.SUCCESS)); + } + + public ResponseEntity deleteUser(Authentication authentication) { + userService.deleteUserByEmail(authentication.getName()); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS)); + } +} + diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java index 04ac95c..dec051b 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java @@ -2,6 +2,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; /** @@ -60,11 +61,29 @@ public enum ResponseCode { HttpStatus.BAD_REQUEST ), RESOURCE_NOT_FOUND( - "AUT-107", + "AUT-108", "Resource not found", "The requested resource could not be found. Please verify that the information entered is correct and try again.", HttpStatus.NOT_FOUND ), + ACCOUNT_BANNED( + "AUT-109", + "Account banned", + "Your account has been banned due to a violation of the Terms of Use Policy", + HttpStatus.UNAUTHORIZED + ), + ACCOUNT_DISABLED( + "AUT-110", + "Account disabled", + "Your account has been disabled contact support to find out why", + HttpStatus.UNAUTHORIZED + ), + AGE_NOT_VALID( + "AUT-111", + "Age not valid", + "Age must be at least 18 years old, or have expected format", + HttpStatus.BAD_REQUEST + ), PASSWORD_UPDATED( "AUT-200", "Password updated", @@ -155,6 +174,18 @@ public enum ResponseCode { "User already exists. Please make sure you have entered the correct email and try again.", HttpStatus.CONFLICT ), + USER_BANNED( + "AUT-408", + "User banned", + "User has been successfully banned.", + HttpStatus.OK + ), + USER_UN_BANNED( + "AUT-409", + "User unbanned", + "User has been successfully unbanned.", + HttpStatus.OK + ), PERMISSION_CREATED( "AUT-500", "Permission created", diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Permissions.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Role.java similarity index 52% rename from src/main/java/com/github/gribanoveu/cuddly/entities/enums/Permissions.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/enums/Role.java index cb50f88..f656abb 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Permissions.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Role.java @@ -1,16 +1,23 @@ package com.github.gribanoveu.cuddly.entities.enums; +import org.springframework.security.core.GrantedAuthority; + /** * @author Evgeny Gribanov * @version 26.09.2023 * default permissions, need to be in database by default */ -public enum Permissions { - AU_PERMISSIONS_MANAGEMENT, - AU_USERS_MANAGEMENT, - AU_MAIN_INFO_VIEW; +public enum Role implements GrantedAuthority { + USER, + MODERATOR, + ADMIN; public String scope() { return "SCOPE_" + name(); } + + @Override + public String getAuthority() { + return name(); + } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java index 16f65db..0c4e19b 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddly.entities.repositories; -import com.github.gribanoveu.cuddly.entities.tables.Permission; +import com.github.gribanoveu.cuddly.entities.enums.Role; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @@ -13,9 +13,9 @@ * @version 21.09.2023 */ @Repository -public interface PermissionRepository extends CrudRepository { - Optional findByName(String name); - List findAll(Pageable pageable); +public interface PermissionRepository extends CrudRepository { + Optional findByName(String name); + List findAll(Pageable pageable); Boolean existsByName(String name); void deleteByName(String name); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java index 197a02a..7e710ea 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java @@ -18,4 +18,5 @@ public interface UserRepository extends CrudRepository { Optional findByEmail(String email); Optional findUserById(Long id); List findAll(Pageable pageable); + void deleteByEmail(String email); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java deleted file mode 100644 index 3c25502..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/PermissionService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.github.gribanoveu.cuddly.entities.services.contract; - -import com.github.gribanoveu.cuddly.entities.tables.Permission; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author Evgeny Gribanov - * @version 21.09.2023 - */ -public interface PermissionService { - Permission getDefaultUserPermission(); - List getAllPermissions(int pageNumber, int pageSize); - Permission findPermissionByName(String name); - boolean permissionExistByName(String name); - @Transactional void save(Permission permission); - @Transactional void deletePermissionByName(String permissionName); - @Transactional Permission updatePermissionName(String permissionName, String newName); -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java deleted file mode 100644 index b8a7d18..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/PermissionServiceImpl.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.github.gribanoveu.cuddly.entities.services.implementation; - -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.Permissions; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.repositories.PermissionRepository; -import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; -import com.github.gribanoveu.cuddly.entities.tables.Permission; -import lombok.RequiredArgsConstructor; -import org.springframework.data.domain.PageRequest; -import org.springframework.stereotype.Service; - -import java.util.List; - - -/** - * @author Evgeny Gribanov - * @version 21.09.2023 - */ -@Service -@RequiredArgsConstructor -public class PermissionServiceImpl implements PermissionService { - private final PermissionRepository permissionRepository; - - @Override - public Permission getDefaultUserPermission() { - return permissionRepository.findByName(Permissions.AU_MAIN_INFO_VIEW.name()) - .orElseGet(() -> permissionRepository.save( - new Permission(Permissions.AU_USERS_MANAGEMENT.name()))); - } - - @Override - public List getAllPermissions(int pageNumber, int pageSize) { - var pageable = PageRequest.of(pageNumber, pageSize); - return permissionRepository.findAll(pageable); - } - - @Override - public Permission findPermissionByName(String name) { - return permissionRepository.findByName(name).orElseThrow(() -> - new CredentialEx(ResponseCode.PERMISSION_NOT_EXIST)); - } - - @Override - public void deletePermissionByName(String permissionName) { - var permission = permissionName.toUpperCase(); - if (permissionRepository.existsByName(permission)) permissionRepository.deleteByName(permission); - else throw new CredentialEx(ResponseCode.PERMISSION_NOT_EXIST); - } - - @Override - public Permission updatePermissionName(String permissionName, String newName) { - var permission = findPermissionByName(permissionName); - permission.setName(newName); - return permissionRepository.save(permission); - } - - @Override - public boolean permissionExistByName(String name) { - return permissionRepository.existsByName(name); - } - - @Override - public void save(Permission permission) { - permissionRepository.save(permission); - } -} - diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/RedisOtpService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpService.java similarity index 87% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/RedisOtpService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpService.java index 3091f87..de5c1a3 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/RedisOtpService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpService.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.otp; import java.time.Duration; import java.util.Optional; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/RedisOtpServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java similarity index 91% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/RedisOtpServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java index cc8cd61..886e624 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/RedisOtpServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddly.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.otp; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.services.contract.RedisOtpService; +import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -24,7 +24,7 @@ public class RedisOtpServiceImpl implements RedisOtpService { public void saveOptCode(String email, String code, Duration codeDuration) { var otpCode = getOtpCode(email); if (otpCode.isPresent()) { - var codeDurationInMinutes = getOtpExpire(email, TimeUnit.MINUTES); + var codeDurationInMinutes = getOtpExpire(email, TimeUnit.MINUTES); // fixme throw new CredentialEx(ResponseCode.OTP_CODE_EXIST); } redisTemplate.opsForValue().set(email, code, codeDuration); diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java new file mode 100644 index 0000000..bd23926 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java @@ -0,0 +1,21 @@ +package com.github.gribanoveu.cuddly.entities.services.permission; + +import com.github.gribanoveu.cuddly.entities.enums.Role; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * @author Evgeny Gribanov + * @version 21.09.2023 + */ +public interface PermissionService { + Role getDefaultUserPermission(); + List getAllPermissions(int pageNumber, int pageSize); + Role findPermissionByName(String name); + boolean permissionExistByName(String name); + @Transactional void save(Role permission); + @Transactional void deletePermissionByName(String roleName); + @Transactional + void updatePermissionName(String roleName, String newName); +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/TokenService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenService.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/TokenService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenService.java index bf9bbab..163f7f7 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/TokenService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenService.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.token; import com.github.gribanoveu.cuddly.entities.enums.TokenType; import com.github.gribanoveu.cuddly.security.CustomUserDetails; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenServiceImpl.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenServiceImpl.java index 274cb54..a4118cc 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenServiceImpl.java @@ -1,10 +1,11 @@ -package com.github.gribanoveu.cuddly.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.token; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.entities.services.token.TokenService; import com.github.gribanoveu.cuddly.security.CustomUserDetails; +import com.nimbusds.jose.Header; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import lombok.Getter; @@ -42,14 +43,13 @@ public class TokenServiceImpl implements TokenService { @Override public String generateToken(CustomUserDetails usrDetails, TokenType tokenType) { var now = Instant.now(); - var permissions = usrDetails.getAuthorities().stream() + var roles = usrDetails.getAuthorities().stream() .map(GrantedAuthority::getAuthority).toList(); var builder = JwtClaimsSet.builder() .issuedAt(now) .subject(usrDetails.getUsername()) - .claim("position", usrDetails.getUserPosition()) - .claim("scope", permissions); + .claim("scope", roles); // !! if change 'scope' to another name, authorities will be null // all authorities have 'SCOPE_' prefix by default diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/UserService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserService.java similarity index 81% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/UserService.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserService.java index 3d713c8..ead69ad 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/contract/UserService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserService.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.services.contract; +package com.github.gribanoveu.cuddly.entities.services.user; import com.github.gribanoveu.cuddly.entities.tables.User; import org.springframework.transaction.annotation.Transactional; @@ -12,10 +12,12 @@ public interface UserService { @Transactional void saveUser(User user); @Transactional void deleteUserById(Long userId); + @Transactional void deleteUserByEmail(String userEmail); @Transactional void updatePasswordByEmail(User user, String password); @Transactional void updateUserPasswordAndCredentialsExpiredById(User user, String password); @Transactional void updateEmail(User user, String newEmail); @Transactional void updateEnabled(User user, Boolean enabled); + @Transactional void updateLocked(User user, Boolean locked); User findUserByEmail(String email); User findUserById(Long id); Boolean userExistByEmail(String email); diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserServiceImpl.java similarity index 81% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/UserServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserServiceImpl.java index 58e2022..c50284a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/implementation/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserServiceImpl.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.entities.services.implementation; +package com.github.gribanoveu.cuddly.entities.services.user; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.repositories.UserRepository; -import com.github.gribanoveu.cuddly.entities.services.contract.UserService; +import com.github.gribanoveu.cuddly.entities.services.user.UserService; import com.github.gribanoveu.cuddly.entities.tables.User; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; @@ -43,6 +43,12 @@ public void deleteUserById(Long userId) { else throw new CredentialEx(ResponseCode.USER_NOT_EXIST); } + @Override + public void deleteUserByEmail(String userEmail) { + if (userRepository.existsByEmail(userEmail)) userRepository.deleteByEmail(userEmail); + else throw new CredentialEx(ResponseCode.USER_NOT_EXIST); + } + @Override public Boolean userExistByEmail(String email) { return userRepository.existsByEmail(email); @@ -79,4 +85,10 @@ public void updateEnabled(User user, Boolean enabled) { userRepository.save(user); } + @Override + public void updateLocked(User user, Boolean locked) { + user.setAccountNonLocked(locked); + userRepository.save(user); + } + } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java deleted file mode 100644 index 7373269..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/tables/Permission.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.github.gribanoveu.cuddly.entities.tables; - -import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author Evgeny Gribanov - * @version 21.09.2023 - */ -@Entity -@Table(name = "permission") -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Permission { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Version - private Long version; - - @Column(name = "name", unique = true) - private String name; - - public Permission(String name) { - this.name = name; - } -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java index b88f8db..c9e0105 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java @@ -2,14 +2,17 @@ import com.fasterxml.jackson.annotation.JsonIgnore; -import com.github.gribanoveu.cuddly.constants.Constants; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.gribanoveu.cuddly.entities.enums.Role; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.time.LocalDate; import java.time.LocalDateTime; -import java.util.Collection; + +import static com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY; @Data @Entity @@ -24,27 +27,25 @@ public class User { @Version private Long version; - @Column(name = "email") + @Column(name = "email", unique = true) private String email; - @JsonIgnore + @JsonProperty(access = WRITE_ONLY) @Column(name = "password") private String password; - @Column(name = "position") - private String position; - @Temporal(TemporalType.TIMESTAMP) @Column(name = "registration_date") private LocalDateTime registrationDate; - @OneToMany(fetch = FetchType.EAGER) - @JoinTable( - name = "users_permissions", - joinColumns = @JoinColumn(name = "user_id"), - inverseJoinColumns = @JoinColumn(name = "role_id") - ) - private Collection permissionCollection; + @Column(name = "birth_date") + private LocalDate birthDate; + + @JsonIgnore + @Enumerated(EnumType.STRING) + @Column(name = "role") + private Role role; + @Column(name = "account_non_expired") private Boolean accountNonExpired = true; @@ -61,7 +62,6 @@ public class User { @PrePersist private void setDefaultAccountStatus() { this.registrationDate = LocalDateTime.now(); - this.position = Constants.DEFAULT_USER_POSITION; } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java b/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java index 74bc5a9..6ff0795 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java @@ -2,14 +2,10 @@ import com.github.gribanoveu.cuddly.entities.tables.User; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.io.Serial; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; +import java.util.*; /** * @author Evgeny Gribanov @@ -23,7 +19,7 @@ public class CustomUserDetails implements UserDetails { public CustomUserDetails(User user) { this.user = user; this.authorities = new HashSet<>(); - this.authorities.addAll(getPermissions()); + this.authorities.addAll(getRole()); } @Override @@ -31,14 +27,8 @@ public Collection getAuthorities() { return authorities; } - public Collection getPermissions() { - return this.user.getPermissionCollection().stream() - .map(permission -> new SimpleGrantedAuthority(permission.getName())) - .collect(Collectors.toSet()); - } - - public String getUserPosition() { - return this.user.getPosition(); + public Collection getRole() { + return Collections.singletonList(this.user.getRole()); } @Override diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java b/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java new file mode 100644 index 0000000..ced326e --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java @@ -0,0 +1,26 @@ +package com.github.gribanoveu.cuddly.utils.validators; + +import com.github.gribanoveu.cuddly.constants.ValidationMessages; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author Evgeny Gribanov + * @version 23.10.2023 + */ +@Target({TYPE, FIELD, ANNOTATION_TYPE}) +@Retention(RUNTIME) +@Constraint(validatedBy = MinimalAgeValidator.class) +@Documented +public @interface MinimalAge { + String message() default ""; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java b/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java new file mode 100644 index 0000000..797f870 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java @@ -0,0 +1,34 @@ +package com.github.gribanoveu.cuddly.utils.validators; + +import com.github.gribanoveu.cuddly.constants.RegexpFormat; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.time.LocalDate; + +/** + * @author Evgeny Gribanov + * @version 23.10.2023 + */ +public class MinimalAgeValidator implements ConstraintValidator { + private static final int MIN_AGE = 18; + + @Override + public void initialize(MinimalAge constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(String birthDate, ConstraintValidatorContext constraintValidatorContext) { + if (birthDate == null) return false; + if (!birthDate.matches(RegexpFormat.BIRTHDAY_PATTERN)) return false; + var now = LocalDate.now(); + var date = LocalDate.parse(birthDate); + var age = now.minusYears(date.getYear()) + .minusMonths(date.getMonthValue()) + .minusDays(date.getDayOfMonth()) + .getYear(); + + return age >= MIN_AGE; + } +} diff --git a/src/main/resources/db/migration/V1_0__create_users_table.sql b/src/main/resources/db/migration/V1_0__create_users_table.sql index 8ba0add..30c6229 100644 --- a/src/main/resources/db/migration/V1_0__create_users_table.sql +++ b/src/main/resources/db/migration/V1_0__create_users_table.sql @@ -1,28 +1,14 @@ CREATE TABLE users ( - id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, - version BIGINT NOT NULL, - email VARCHAR(30) NOT NULL UNIQUE, - password VARCHAR(80) NOT NULL, - position VARCHAR(30) NOT NULL, - registration_date TIMESTAMP(6) NOT NULL, - account_non_expired BOOLEAN NOT NULL, - account_non_locked BOOLEAN NOT NULL, - credentials_non_expired BOOLEAN NOT NULL, - enabled BOOLEAN NOT NULL + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + version BIGINT NOT NULL, + email VARCHAR(30) NOT NULL UNIQUE, + password VARCHAR(80) NOT NULL, + birth_date DATE NOT NULL, + registration_date TIMESTAMP NOT NULL, + role VARCHAR(15) NOT NULL, + account_non_expired BOOLEAN NOT NULL, + account_non_locked BOOLEAN NOT NULL, + credentials_non_expired BOOLEAN NOT NULL, + enabled BOOLEAN NOT NULL ); - -CREATE TABLE permission -( - id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, - version BIGINT NOT NULL, - name VARCHAR(30) UNIQUE -); - -create table users_permissions -( - role_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - FOREIGN KEY (role_id) REFERENCES permission, - FOREIGN KEY (user_id) REFERENCES users -); \ No newline at end of file diff --git a/src/main/resources/db/migration/V2_0__add_users_data.sql b/src/main/resources/db/migration/V2_0__add_users_data.sql index 3489273..6fdda44 100644 --- a/src/main/resources/db/migration/V2_0__add_users_data.sql +++ b/src/main/resources/db/migration/V2_0__add_users_data.sql @@ -1,20 +1,16 @@ INSERT INTO users -(version, email, password, registration_date, position, +(version, email, password, birth_date, registration_date, role, account_non_expired, account_non_locked, credentials_non_expired, enabled) -VALUES (0, 'admin@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', - '2023-01-01 00:00:00.000000', 'ADMIN', - true, true, true, true), - (0, 'user@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', - '2023-01-01 00:00:00.000000', 'USER', - true, true, true, true); -INSERT INTO permission(version, name) -VALUES (0, 'AU_MAIN_INFO_VIEW'), - (0, 'AU_PERMISSIONS_MANAGEMENT'), - (0, 'AU_USERS_MANAGEMENT'); +VALUES + (0, 'admin@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', + '2001-01-01', '2023-01-01 00:00:00.000000', + 'ADMIN', true, true, true, true), -INSERT INTO users_permissions(role_id, user_id) -VALUES (1, 1), - (2, 1), - (3, 1), - (1, 2); + (0, 'moderator@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', + '2001-01-01', '2023-01-01 00:00:00.000000', + 'MODERATOR', true, true, true, true), + + (0, 'user@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', + '2001-01-01', '2023-01-01 00:00:00.000000', + 'USER', true, true, true, true); diff --git a/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java b/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java index dcc3a79..85ef6d0 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddly.base; import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.entities.services.token.TokenService; import com.github.gribanoveu.cuddly.security.CustomUserDetails; import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import org.junit.jupiter.api.BeforeEach; diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java deleted file mode 100644 index 683e151..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangeEmailDtoTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class ChangeEmailDtoTest extends BaseValidatorTest { - - @Test - void testValidChangeEmailDto() { - ChangeEmailDto changeEmailDto = new ChangeEmailDto("newemail@example.com"); - Set> violations = validator.validate(changeEmailDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidChangeEmailDtoWithIncorrectEmailFormat() { - ChangeEmailDto changeEmailDto = new ChangeEmailDto("newemailexample.com"); - Set> violations = validator.validate(changeEmailDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangeEmailDtoWithLongEmail() { - ChangeEmailDto changeEmailDto = new ChangeEmailDto(StringUtils.repeat("a", 254) + "@example.com"); - Set> violations = validator.validate(changeEmailDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangeEmailDtoWithNullEmail() { - ChangeEmailDto changeEmailDto = new ChangeEmailDto(null); - Set> violations = validator.validate(changeEmailDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java deleted file mode 100644 index c9cdb88..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/ChangePasswordDtoTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class ChangePasswordDtoTest extends BaseValidatorTest { - - @Test - void testValidChangePasswordDto() { - ChangePasswordDto changePasswordDto = new ChangePasswordDto("oldPassword", "newPassword", "newPassword"); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidChangePasswordDtoWithEmptyOldPassword() { - ChangePasswordDto changePasswordDto = new ChangePasswordDto("", "newPassword", "newPassword"); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangePasswordDtoWithEmptyPassword() { - ChangePasswordDto changePasswordDto = new ChangePasswordDto("oldPassword", "", "newPassword"); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangePasswordDtoWithEmptyConfirmPassword() { - ChangePasswordDto changePasswordDto = new ChangePasswordDto("oldPassword", "newPassword", ""); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangePasswordDtoWithLongOldPassword() { - String longOldPassword = StringUtils.repeat("a", 81); - ChangePasswordDto changePasswordDto = new ChangePasswordDto(longOldPassword, "newPassword", "newPassword"); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangePasswordDtoWithLongPassword() { - String longPassword = StringUtils.repeat("a", 81); - ChangePasswordDto changePasswordDto = new ChangePasswordDto("oldPassword", longPassword, "newPassword"); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidChangePasswordDtoWithLongConfirmPassword() { - String longConfirmPassword = StringUtils.repeat("a", 81); - ChangePasswordDto changePasswordDto = new ChangePasswordDto("oldPassword", "newPassword", longConfirmPassword); - Set> violations = validator.validate(changePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java deleted file mode 100644 index 5fa8437..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/GenerateOtpDtoTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class GenerateOtpDtoTest extends BaseValidatorTest { - - @Test - void testValidGenerateOtpDto() { - GenerateOtpDto generateOtpDto = new GenerateOtpDto("test@example.com"); - Set> violations = validator.validate(generateOtpDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidGenerateOtpDtoWithIncorrectEmailFormat() { - GenerateOtpDto generateOtpDto = new GenerateOtpDto("testexample.com"); - Set> violations = validator.validate(generateOtpDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidGenerateOtpDtoWithLongEmail() { - String longEmail = StringUtils.repeat("a", 31) + "@example.com"; - GenerateOtpDto generateOtpDto = new GenerateOtpDto(longEmail); - Set> violations = validator.validate(generateOtpDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidGenerateOtpDtoWithNullEmail() { - GenerateOtpDto generateOtpDto = new GenerateOtpDto(null); - Set> violations = validator.validate(generateOtpDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java deleted file mode 100644 index 2ef582c..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/LoginDtoTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 04.10.2023 - */ -class LoginDtoTest extends BaseValidatorTest { - - @Test - void testValidLoginDto() { - LoginDto loginDto = new LoginDto("test@example.com", "password"); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidLoginDtoWithIncorrectEmailFormat() { - LoginDto loginDto = new LoginDto("testexample.com", "password"); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidLoginDtoWithEmptyEmail() { - LoginDto loginDto = new LoginDto("", "password"); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .containsAll(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE, ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidLoginDtoWithEmptyPassword() { - LoginDto loginDto = new LoginDto("test@example.com", ""); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidLoginDtoWithLongEmail() { - LoginDto loginDto = new LoginDto(StringUtils.repeat("a", 254) + "@example.com", "password"); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidLoginDtoWithLongPassword() { - LoginDto loginDto = new LoginDto("test@example.com", StringUtils.repeat("a", 254)); - - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidLoginDtoWithNullEmail() { - LoginDto loginDto = new LoginDto(null, "password"); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidLoginDtoWithNullPassword() { - LoginDto loginDto = new LoginDto("test@example.com", null); - Set> violations = validator.validate(loginDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java deleted file mode 100644 index 83296ca..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/PermissionDtoTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class PermissionDtoTest extends BaseValidatorTest { - @Test - void testValidPermissionDto() { - PermissionDto permissionDto = new PermissionDto("TT_PERMISSION"); - Set> violations = validator.validate(permissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidPermissionDtoWithIncorrectPermissionFormat() { - PermissionDto permissionDto = new PermissionDto("read-write"); - Set> violations = validator.validate(permissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidPermissionDtoWithLongPermissionName() { - String longPermissionName = StringUtils.repeat("a", 31); - PermissionDto permissionDto = new PermissionDto(longPermissionName); - Set> violations = validator.validate(permissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .containsAll(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE, ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidPermissionDtoWithNullPermissionName() { - PermissionDto permissionDto = new PermissionDto(null); - Set> violations = validator.validate(permissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java deleted file mode 100644 index 295df97..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RegisterDtoTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class RegisterDtoTest extends BaseValidatorTest { - - @Test - void testValidRegisterDto() { - RegisterDto registerDto = new RegisterDto("test@example.com", "password", "password"); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidRegisterDtoWithIncorrectEmailFormat() { - RegisterDto registerDto = new RegisterDto("testexample.com", "password", "password"); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRegisterDtoWithLongEmail() { - String longEmail = StringUtils.repeat("a", 31) + "@example.com"; - RegisterDto registerDto = new RegisterDto(longEmail, "password", "password"); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRegisterDtoWithEmptyPassword() { - RegisterDto registerDto = new RegisterDto("test@example.com", "", "password"); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRegisterDtoWithLongPassword() { - String longPassword = StringUtils.repeat("a", 81); - RegisterDto registerDto = new RegisterDto("test@example.com", longPassword, "password"); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRegisterDtoWithEmptyConfirmPassword() { - RegisterDto registerDto = new RegisterDto("test@example.com", "password", ""); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRegisterDtoWithLongConfirmPassword() { - String longConfirmPassword = StringUtils.repeat("a", 81); - RegisterDto registerDto = new RegisterDto("test@example.com", "password", longConfirmPassword); - Set> violations = validator.validate(registerDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java deleted file mode 100644 index db9b8fc..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/RestorePasswordDtoTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class RestorePasswordDtoTest extends BaseValidatorTest { - @Test - void testValidRestorePasswordDto() { - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "123456", "password", "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidRestorePasswordDtoWithIncorrectEmailFormat() { - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("testexample.com", "123456", "password", "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithLongEmail() { - String longEmail = StringUtils.repeat("a", 31) + "@example.com"; - RestorePasswordDto restorePasswordDto = new RestorePasswordDto(longEmail, "123456", "password", "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithEmptyOtpCode() { - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "", "password", "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .containsAll(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE, ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithIncorrectOtpCodeFormat() { - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "1234567", "password", "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithEmptyPassword() { - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "123456", "", "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithLongPassword() { - String longPassword = StringUtils.repeat("a", 81); - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "123456", longPassword, "password"); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithEmptyConfirmPassword() { - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "123456", "password", ""); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidRestorePasswordDtoWithLongConfirmPassword() { - String longConfirmPassword = StringUtils.repeat("a", 81); - RestorePasswordDto restorePasswordDto = new RestorePasswordDto("test@example.com", "123456", "password", longConfirmPassword); - Set> violations = validator.validate(restorePasswordDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java deleted file mode 100644 index 16903d6..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/dtos/request/UpdatePermissionDtoTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request; - -import com.github.gribanoveu.cuddly.base.BaseValidatorTest; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import jakarta.validation.ConstraintViolation; -import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Set; - -/** - * @author Evgeny Gribanov - * @version 05.10.2023 - */ -class UpdatePermissionDtoTest extends BaseValidatorTest { - @Test - void testValidUpdatePermissionDto() { - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("TT_PERMISSION", "TT_PERMISSION_NEW"); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage).hasSize(0); - } - - @Test - void testInvalidUpdatePermissionDtoWithEmptyPermissionName() { - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("", "TT_PERMISSION"); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .containsAll(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE, ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidUpdatePermissionDtoWithIncorrectPermissionNameFormat() { - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("invalid_permission", "TT_PERMISSION"); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidUpdatePermissionDtoWithLongPermissionName() { - String longPermissionName = StringUtils.repeat("a", 31).toUpperCase(); - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("TT_" + longPermissionName, "TT_PERMISSION"); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidUpdatePermissionDtoWithEmptyNewName() { - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("TT_PERMISSION", ""); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .containsAll(List.of(ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE, ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidUpdatePermissionDtoWithIncorrectNewNameFormat() { - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("TT_PERMISSION", "invalid_new_permission"); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.PATTERN_EXCEPTION_MESSAGE)); - } - - @Test - void testInvalidUpdatePermissionDtoWithLongNewName() { - String longNewName = StringUtils.repeat("a", 31).toUpperCase(); - UpdatePermissionDto updatePermissionDto = new UpdatePermissionDto("TT_PERMISSION", "TT_" + longNewName); - Set> violations = validator.validate(updatePermissionDto); - Assertions.assertThat(violations).extracting(ConstraintViolation::getMessage) - .isEqualTo(List.of(ValidationMessages.SIZE_EXCEPTION_MESSAGE)); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java deleted file mode 100644 index ad77121..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/PermissionControllerTest.java +++ /dev/null @@ -1,337 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; - -import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; -import com.github.gribanoveu.cuddly.controllers.dtos.request.PermissionDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.UpdatePermissionDto; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.services.contract.PermissionService; -import com.github.gribanoveu.cuddly.entities.tables.Permission; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Evgeny Gribanov - * @version 03.10.2023 - */ -class PermissionControllerTest extends BaseMockMvcTest { - @Autowired private PermissionService permissionService; - - - @Test - void testCreatePermission_validData_createPermission() throws Exception { - var permissionName = "TT_PERMISSION"; - - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", adminToken) - .content(testJsonUtils.convertDtoToJson(new PermissionDto(permissionName)))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.PERMISSION_CREATED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.PERMISSION_CREATED.getMessage())); - - var savedPermission = permissionService.findPermissionByName(permissionName); - Assertions.assertThat(savedPermission).isNotNull(); - Assertions.assertThat(savedPermission.getName()).isEqualTo(permissionName); - } - - @Test - void testCreatePermission_withoutPermissionToCreate_throwsException() throws Exception { - var request = new PermissionDto("TT_PERMISSION"); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", userToken) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.ACCESS_DENIED.getMessage())); - } - - @Test - void testCreatePermission_existName_throwsException() throws Exception { - var request = new PermissionDto("AU_MAIN_INFO_VIEW"); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", adminToken) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().is(ResponseCode.PERMISSION_EXIST.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.PERMISSION_EXIST.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.PERMISSION_EXIST.getMessage())); - } - - @Test - void testCreatePermission_invalidName_throwsException() throws Exception { - var request = new PermissionDto("TT"); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", adminToken) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.VALIDATION_ERROR_DETAIL.getCode())) - .andExpect(jsonPath("$..details[0].message").value("Field 'permissionName' - must match the expected format")); - } - - @Test - void testCreatePermission_emptyName_throwsException() throws Exception { - var request = new PermissionDto(""); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", adminToken) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().is(ResponseCode.VALIDATION_ERROR_DETAIL.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.VALIDATION_ERROR_DETAIL.getCode())) - .andExpect(jsonPath("$..details[0].message").isNotEmpty()); - } - - @Test - void testCreatePermission_nullName_throwsException() throws Exception { - var request = new PermissionDto(null); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", adminToken) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.VALIDATION_ERROR_DETAIL.getCode())) - .andExpect(jsonPath("$..details[0].message").value("Field 'permissionName' - cannot be empty")); - } - - @Test - void testCreatePermission_withoutAuthorization_throwsException() throws Exception { - var request = new PermissionDto("TT_PERMISSION"); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())); - } - - @Test - void testCreatePermission_asUser_throwsException() throws Exception { - var request = new PermissionDto("TT_PERMISSION"); - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", userToken) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.ACCESS_DENIED.getMessage())); - } - - @Test - void testCreatePermission_invalidJson_throwsException() throws Exception { - this.mockMvc.perform(post("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", adminToken) - .content(String.valueOf(123))) - .andExpect(status().is(ResponseCode.VALIDATION_ERROR.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.VALIDATION_ERROR.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.VALIDATION_ERROR.getMessage())); - } - - @Test - void testGetAllPermissions_withPaginationTwoPageSize_returnTwoPermission() throws Exception { - this.mockMvc.perform(get("/v1/permission") - .param("pageNumber", "0") - .param("pageSize", "2") - .header("Authorization", adminToken)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$..permissions[0].id").value(1)) - .andExpect(jsonPath("$..permissions[0].name").value("AU_MAIN_INFO_VIEW")) - .andExpect(jsonPath("$..permissions[1].id").value(2)) - .andExpect(jsonPath("$..permissions[1].name").value("AU_PERMISSIONS_MANAGEMENT")); - } - - @Test - void testGetAllPermissions_withPaginationOnePageSize_returnOnePermission() throws Exception { - this.mockMvc.perform(get("/v1/permission") - .param("pageNumber", "0") - .param("pageSize", "1") - .header("Authorization", adminToken)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$..permissions[0].id").value(1)) - .andExpect(jsonPath("$..permissions[0].name").value("AU_MAIN_INFO_VIEW")); - } - - @Test - void testGetAllPermissions_withoutPagination_throwsException() throws Exception { - this.mockMvc.perform(get("/v1/permission") - .header("Authorization", adminToken)) - .andExpect(status().is(ResponseCode.MISSING_PARAM.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.MISSING_PARAM.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.MISSING_PARAM.getMessage())); - } - - @Test - void testGetAllPermissions_asUser_throwsException() throws Exception { - this.mockMvc.perform(get("/v1/permission") - .param("pageNumber", "0") - .param("pageSize", "1")) - // .header("Authorization", "userToken")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value("Full authentication is required to access this resource")); - } - - @Test - void testGetAllPermissions_withoutAuthorization_throwsException() throws Exception { - this.mockMvc.perform(get("/v1/permission") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())); - } - - @Test - void testDeletePermission_asAdmin_permissionDeleted() throws Exception { - var permissionName = "BE_DELETED"; - permissionService.save(new Permission(permissionName)); - - var savedPermission = permissionService.findPermissionByName(permissionName); - Assertions.assertThat(savedPermission.getName()).isEqualTo(permissionName); - - this.mockMvc.perform(delete("/v1/permission") - .param("permissionName", permissionName) - .header("Authorization", adminToken)) - .andExpect(status().is(ResponseCode.PERMISSION_DELETED.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.PERMISSION_DELETED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.PERMISSION_DELETED.getMessage())); - - assertThrows(CredentialEx.class, - () -> permissionService.findPermissionByName(permissionName)); - } - - @Test - void testDeletePermission_asUser_throwsException() throws Exception { - var permissionName = "BE_NOT_DELETED"; - permissionService.save(new Permission(permissionName)); - - var savedPermission = permissionService.findPermissionByName(permissionName); - Assertions.assertThat(savedPermission.getName()).isEqualTo(permissionName); - - this.mockMvc.perform(delete("/v1/permission") - .param("permissionName", permissionName) - .header("Authorization", userToken)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.ACCESS_DENIED.getMessage())); - } - - @Test - void testDeletePermission_notExist_throwsException() throws Exception { - this.mockMvc.perform(delete("/v1/permission") - .param("permissionName", "NOT_EXIST_PERMISSION") - .header("Authorization", adminToken)) - .andExpect(status().is(ResponseCode.PERMISSION_NOT_EXIST.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.PERMISSION_NOT_EXIST.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.PERMISSION_NOT_EXIST.getMessage())); - } - - @Test - void updatePermission_asAdmin_permissionUpdated() throws Exception { - var permissionName = "BE_DELETED"; - var updatedPermissionName = "BE_UPDATED_SUCCESS"; - var updatePermissionDto = new UpdatePermissionDto(permissionName, updatedPermissionName); - - permissionService.save(new Permission(permissionName)); - var savedPermission = permissionService.findPermissionByName(permissionName); - Assertions.assertThat(savedPermission.getName()).isEqualTo(permissionName); - - this.mockMvc.perform(put("/v1/permission") - .header("Authorization", adminToken) - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(updatePermissionDto))) - .andExpect(status().is(ResponseCode.PERMISSION_UPDATED.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.PERMISSION_UPDATED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.PERMISSION_UPDATED.getMessage())); - - var updatedPermission = permissionService.findPermissionByName(updatedPermissionName); - Assertions.assertThat(updatedPermission.getName()).isEqualTo(updatedPermissionName); - } - - @Test - void updatePermission_asUser_throwsException() throws Exception { - var permissionName = "BE_NOT_UPDATED"; - permissionService.save(new Permission(permissionName)); - - var updatePermissionDto = new UpdatePermissionDto(permissionName, "BE_NOT_UPDATED_UPD"); - - this.mockMvc.perform(put("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(updatePermissionDto)) - .header("Authorization", userToken)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.ACCESS_DENIED.getMessage())); - } - - @Test - void updatePermission_notExist_throwsException() throws Exception { - var permissionName = "BE_NOT_EXIST"; - var updatePermissionDto = new UpdatePermissionDto(permissionName, "BE_NOT_EXIST_UPD"); - - assertThrows(CredentialEx.class, - () -> permissionService.findPermissionByName(permissionName)); - - this.mockMvc.perform(put("/v1/permission") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(updatePermissionDto)) - .header("Authorization", adminToken)) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.PERMISSION_NOT_EXIST.getCode())) - .andExpect(jsonPath("$..details[0].message").value(ResponseCode.PERMISSION_NOT_EXIST.getMessage())); - } - - @Test - void testUpdatePermission_withoutAuthorization_throwsException() throws Exception { - var updatePermissionDto = new UpdatePermissionDto("AU_PERMISSIONS_MANAGEMENT", "AU_PERMISSIONS_MANAGEMENT_NP"); - - this.mockMvc.perform(put("/v1/permission") - .param("permissionName", "BE_NOT_UPDATED")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.ACCESS_DENIED.getCode())) - .andExpect(jsonPath("$..details[0].message").value("Full authentication is required to access this resource")); - - } - - @Test - void testUpdatePermission_withoutNewPermissionName_throwsException() throws Exception { - var permissionName = "AU_PERMISSIONS_MANAGEMENT"; - var updatePermissionDto = new UpdatePermissionDto(permissionName, ""); - - this.mockMvc.perform(put("/v1/permission") - .header("Authorization", adminToken) - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(updatePermissionDto))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$..details[0].code").isNotEmpty()) - .andExpect(jsonPath("$..details[0].message").isNotEmpty()) - .andExpect(jsonPath("$..details[1].code").isNotEmpty()) - .andExpect(jsonPath("$..details[1].message").isNotEmpty()); - - var updatedPermission = permissionService.findPermissionByName(permissionName); - Assertions.assertThat(updatedPermission.getName()).isEqualTo(permissionName); - } - - @Test - void testUpdatePermission_withNull_throwsException() throws Exception { - var permissionName = "AU_PERMISSIONS_MANAGEMENT"; - var updatePermissionDto = new UpdatePermissionDto(permissionName, null); - - this.mockMvc.perform(put("/v1/permission") - .header("Authorization", adminToken) - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(updatePermissionDto))) - .andExpect(status().is(ResponseCode.VALIDATION_ERROR_DETAIL.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].code").value(ResponseCode.VALIDATION_ERROR_DETAIL.getCode())) - .andExpect(jsonPath("$..details[0].message").value("Field 'newName' - cannot be empty")); - - var updatedPermission = permissionService.findPermissionByName(permissionName); - Assertions.assertThat(updatedPermission.getName()).isEqualTo(permissionName); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java b/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java deleted file mode 100644 index 3149938..0000000 --- a/src/test/java/com/github/gribanoveu/cuddly/controllers/endpoints/TokenControllerTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints; - -import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; -import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.implementation.TokenServiceImpl; -import com.github.gribanoveu.cuddly.security.CustomUserDetails; -import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; - -import java.time.LocalDateTime; -import java.util.List; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Evgeny Gribanov - * @version 12.09.2023 - */ -class TokenControllerTest extends BaseMockMvcTest { - @Autowired private TokenServiceImpl tokenService; - @Autowired private CustomUserDetailsService usrDetailsService; - - @Test - public void testCreateAuthToken_validData_createToken() throws Exception { - var request = new LoginDto("admin@email.com", "Qwerty123"); - - this.mockMvc.perform(post("/v1/token/issue") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.accessToken").isNotEmpty()) - .andExpect(jsonPath("$.refreshToken").isNotEmpty()); - } - - @Test - public void testCreateAuthToken_adminData_extractRolesAndPermissions() throws Exception { - var request = new LoginDto("admin@email.com", "Qwerty123"); - - var result = this.mockMvc.perform(post("/v1/token/issue") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.accessToken").isNotEmpty()) - .andExpect(jsonPath("$.refreshToken").isNotEmpty()) - .andReturn(); - - var accessToken = testJsonUtils.getJsonValueFromMvcResult(result, "accessToken"); - var position = tokenService.extractClaim(accessToken,"position"); - var permissions = tokenService.extractClaimsAsList(accessToken, "scope"); - - Assertions.assertThat(position).isEqualTo("ADMIN"); - Assertions.assertThat(permissions).isEqualTo( - List.of("AU_USERS_MANAGEMENT", "AU_MAIN_INFO_VIEW", "AU_PERMISSIONS_MANAGEMENT")); - } - - @Test - public void testCreateAuthToken_userData_extractRolesAndPermissions() throws Exception { - var request = new LoginDto("user@email.com", "Qwerty123"); - - var result = this.mockMvc.perform(post("/v1/token/issue") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.accessToken").isNotEmpty()) - .andExpect(jsonPath("$.refreshToken").isNotEmpty()) - .andReturn(); - - var accessToken = testJsonUtils.getJsonValueFromMvcResult(result, "accessToken"); - var position = tokenService.extractClaim(accessToken,"position"); - var permissions = tokenService.extractClaimsAsList(accessToken, "scope"); - - Assertions.assertThat(permissions).isEqualTo(List.of("AU_MAIN_INFO_VIEW")); - Assertions.assertThat(position).isEqualTo("USER"); - } - - @Test - void testAuthToken_credentialsBadUser_throwException() throws Exception { - var request = new LoginDto("some@mail.com", "password"); - - this.mockMvc.perform(post("/v1/token/issue") - .contentType(MediaType.APPLICATION_JSON) - .content(testJsonUtils.convertDtoToJson(request))) - .andExpect(status().is(ResponseCode.BAD_CREDENTIAL.getHttpCode().value())) - .andExpect(jsonPath("$..details[0].message").value("Bad credentials")); - } - - @Test - public void testCreateRefreshToken_adminData_extractRolesAndPermissions() throws Exception { - var user = (CustomUserDetails) usrDetailsService.loadUserByUsername("admin@email.com"); - var refreshToken = tokenService.generateToken(user, TokenType.REFRESH); - - var result = this.mockMvc.perform(get("/v1/token/refresh") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + refreshToken)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.accessToken").isNotEmpty()) - .andExpect(jsonPath("$.refreshToken").isNotEmpty()) - .andReturn(); - - var accessToken = testJsonUtils.getJsonValueFromMvcResult(result, "accessToken"); - var position = tokenService.extractClaim(accessToken,"position"); - var permissions = tokenService.extractClaimsAsList(accessToken, "scope"); - - Assertions.assertThat(position).isEqualTo("ADMIN"); - Assertions.assertThat(permissions).isEqualTo( - List.of("AU_USERS_MANAGEMENT", "AU_MAIN_INFO_VIEW", "AU_PERMISSIONS_MANAGEMENT")); - } - - @Test - public void testCreateRefreshToken_adminData_extractRefreshTokenTime() throws Exception { - var user = (CustomUserDetails) usrDetailsService.loadUserByUsername("admin@email.com"); - var refreshToken = tokenService.generateToken(user, TokenType.REFRESH); - - var result = this.mockMvc.perform(get("/v1/token/refresh") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + refreshToken)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.accessToken").isNotEmpty()) - .andExpect(jsonPath("$.refreshToken").isNotEmpty()) - .andReturn(); - - var accessToken = testJsonUtils.getJsonValueFromMvcResult(result, "accessToken"); - var exp = tokenService.extractExpire(accessToken); - var tokenLifetime = tokenService.getRefreshTokenLifetime(); - - var refreshDateTime = testJsonUtils.calculateTokenDateTimeFromDate(exp, tokenLifetime); - Assertions.assertThat(refreshDateTime).isAfter(LocalDateTime.now()); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java b/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java index 11a4ee4..fe00a8f 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java @@ -2,7 +2,7 @@ import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.services.contract.TokenService; +import com.github.gribanoveu.cuddly.entities.services.token.TokenService; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java b/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java index 97c2d84..8fcd377 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java +++ b/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddly.utils; -import com.github.gribanoveu.cuddly.controllers.dtos.request.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; From 54b1eda187d8171cfc8f0f7a86c1239ece7485c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 24 Oct 2023 15:51:41 +0300 Subject: [PATCH 03/34] refresh token new logic Took 1 hour 17 minutes --- .../cuddly/AuthServiceApplication.java | 2 +- .../{utils => config}/RsaProperties.java | 2 +- .../cuddly/config/SecurityConfig.java | 4 +- .../gribanoveu/cuddly/config/TokenConfig.java | 1 - .../dtos/request/auth/RefreshTokenDto.java | 14 ++++++ ...kenController.java => AuthController.java} | 19 ++++---- ...rFacade.java => AuthControllerFacade.java} | 43 ++++++++++++++---- .../cuddly/utils/RSAEncryption.java | 44 +++++++++++++++++++ src/main/resources/application.yml | 2 +- 9 files changed, 108 insertions(+), 23 deletions(-) rename src/main/java/com/github/gribanoveu/cuddly/{utils => config}/RsaProperties.java (89%) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java rename src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/{TokenController.java => AuthController.java} (54%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/{TokenControllerFacade.java => AuthControllerFacade.java} (58%) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java diff --git a/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java b/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java index 6db166a..6ff9c0a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java +++ b/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddly; -import com.github.gribanoveu.cuddly.utils.RsaProperties; +import com.github.gribanoveu.cuddly.config.RsaProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/RsaProperties.java b/src/main/java/com/github/gribanoveu/cuddly/config/RsaProperties.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/utils/RsaProperties.java rename to src/main/java/com/github/gribanoveu/cuddly/config/RsaProperties.java index 758c25b..7381e62 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/RsaProperties.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/RsaProperties.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.utils; +package com.github.gribanoveu.cuddly.config; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index f702535..78018ac 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -46,8 +46,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .authorizeHttpRequests(req -> req .requestMatchers(HttpMethod.POST, "*/user").anonymous() // register .requestMatchers("*/role").hasAuthority(ADMIN.scope()) - .requestMatchers("*/users/**").hasAuthority(MODERATOR.scope()) - .requestMatchers("*/token/**").permitAll() // allow auth and anonymous users + .requestMatchers("*/users/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) + .requestMatchers("*/auth").permitAll() // allow auth and anonymous users .requestMatchers("*/account/generate-code").anonymous() // allow only anonymous .requestMatchers("*/account/restore-password").anonymous() .anyRequest().authenticated() diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java index 334f014..0605c1c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java @@ -1,6 +1,5 @@ package com.github.gribanoveu.cuddly.config; -import com.github.gribanoveu.cuddly.utils.RsaProperties; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java new file mode 100644 index 0000000..1a9467c --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java @@ -0,0 +1,14 @@ +package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; + +import jakarta.validation.constraints.NotBlank; + +import static com.github.gribanoveu.cuddly.constants.ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE; + +/** + * @author Evgeny Gribanov + * @version 24.10.2023 + */ +public record RefreshTokenDto( + @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) + String refreshToken +) {} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/TokenController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java similarity index 54% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/TokenController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java index 0aec4b0..4638730 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/TokenController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java @@ -1,8 +1,9 @@ package com.github.gribanoveu.cuddly.controllers.endpoints.auth; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddly.controllers.facade.auth.TokenControllerFacade; +import com.github.gribanoveu.cuddly.controllers.facade.auth.AuthControllerFacade; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -15,17 +16,17 @@ */ @RestController @RequiredArgsConstructor -@RequestMapping("/v1/token") -public class TokenController { - private final TokenControllerFacade tokenControllerFacade; +@RequestMapping("/v1/auth") +public class AuthController { + private final AuthControllerFacade authControllerFacade; - @PostMapping("/issue") + @PostMapping public ResponseEntity authenticateUser(@Valid @RequestBody LoginDto request) { - return tokenControllerFacade.authenticateUser(request); + return authControllerFacade.authenticateUser(request); } - @GetMapping("/refresh") - public ResponseEntity refreshToken(HttpServletRequest request) { - return tokenControllerFacade.refreshToken(request); + @PatchMapping + public ResponseEntity refreshToken(@Valid @RequestBody RefreshTokenDto request) { + return authControllerFacade.refreshToken(request); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/TokenControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java similarity index 58% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/TokenControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java index 126e216..10466da 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/TokenControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java @@ -1,31 +1,42 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.TokenType; import com.github.gribanoveu.cuddly.entities.services.token.TokenService; import com.github.gribanoveu.cuddly.security.CustomUserDetails; import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; -import jakarta.servlet.http.HttpServletRequest; +import com.github.gribanoveu.cuddly.utils.RSAEncryption; +import com.github.gribanoveu.cuddly.config.RsaProperties; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.stereotype.Service; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; import java.time.Duration; /** * @author Evgeny Gribanov * @version 29.08.2023 */ +@Slf4j @Service @RequiredArgsConstructor -public class TokenControllerFacade { +public class AuthControllerFacade { private final TokenService tokenService; private final AuthenticationManager authManager; private final CustomUserDetailsService usrDetailsService; + private final RsaProperties rsaKeys; + private final RSAEncryption rsaEncryption; + @Value("${time-variable.accessTokenLifetime}") private Duration accessTokenLifetime; public ResponseEntity authenticateUser(LoginDto request) { @@ -33,20 +44,36 @@ public ResponseEntity authenticateUser(LoginDto request) { var auth = authManager.authenticate(authenticationToken); var user = (CustomUserDetails) auth.getPrincipal(); var accessToken = tokenService.generateToken(user, TokenType.ACCESS); - var refreshToken = tokenService.generateToken(user, TokenType.REFRESH); + var refreshToken = generateRefreshToken(request.email()); return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, refreshToken)); } - public ResponseEntity refreshToken(HttpServletRequest request) { - var headerAuth = request.getHeader("Authorization"); - var bearerTokenFromHeader = headerAuth.substring(7); - var email = tokenService.extractSubject(bearerTokenFromHeader); + public ResponseEntity refreshToken(RefreshTokenDto request) { + var email = encryptRefreshToken(request.refreshToken()); var user = (CustomUserDetails) usrDetailsService.loadUserByUsername(email); var accessToken = tokenService.generateToken(user, TokenType.ACCESS); - var refreshToken = tokenService.generateToken(user, TokenType.REFRESH); + var refreshToken = generateRefreshToken(email); return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, refreshToken)); } + private String generateRefreshToken(String email) { + RSAPublicKey publicKey = rsaKeys.publicKey(); + try { + return rsaEncryption.encrypt(email, publicKey); + } catch (Exception e) { + throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); + } + } + + private String encryptRefreshToken(String token) { + RSAPrivateKey privateKey = rsaKeys.privateKey(); + try { + return rsaEncryption.decrypt(token, privateKey); + } catch (Exception e) { + throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); + } + } + } diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java b/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java new file mode 100644 index 0000000..0869670 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java @@ -0,0 +1,44 @@ +package com.github.gribanoveu.cuddly.utils; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.Cipher; +import java.security.*; +import java.security.spec.EncodedKeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +/** + * @author Evgeny Gribanov + * @version 24.10.2023 + */ +@Component +@RequiredArgsConstructor +public class RSAEncryption { + private static final String ALGORITHM = "RSA"; + + public String encrypt(String data, PublicKey publicKey) throws Exception { + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] encryptedBytes = cipher.doFinal(data.getBytes()); + return bytesToBase64String(encryptedBytes); + } + + public String decrypt(String encryptedData, PrivateKey privateKey) throws Exception { + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, privateKey); + byte[] encryptedBytes = base64StringToBytes(encryptedData); + byte[] decryptedBytes = cipher.doFinal(encryptedBytes); + return new String(decryptedBytes); + } + + private String bytesToBase64String(byte[] bytes) { + return java.util.Base64.getEncoder().encodeToString(bytes); + } + + private byte[] base64StringToBytes(String base64String) { + return java.util.Base64.getDecoder().decode(base64String); + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 9513be0..b85396c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,7 +1,7 @@ server: port: 8189 servlet: - context-path: /api/secure + context-path: /api/private time-variable: accessTokenLifetime: 15m refreshTokenLifetime: 7d From cf07d37e5bf463e3b5dc01993756878333acb915 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 24 Oct 2023 16:25:17 +0300 Subject: [PATCH 04/34] refactor moderator controller Took 15 minutes --- .../cuddly/config/SecurityConfig.java | 6 +++-- ...ntroller.java => ModeratorController.java} | 24 +++++++++---------- ...de.java => ModeratorControllerFacade.java} | 2 +- 3 files changed, 16 insertions(+), 16 deletions(-) rename src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/{AdminController.java => ModeratorController.java} (58%) rename src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/{AdminControllerFacade.java => ModeratorControllerFacade.java} (98%) diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index 78018ac..2dd3825 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -38,6 +38,8 @@ public class SecurityConfig { private final ServerErrorEntryPoint serverErrorEntryPoint; private final AccessDeniedEntryPoint accessDeniedHandler; + // permitAll - allow auth and anonymous users + // anonymous - allow only anonymous @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // to make API available for requests from other domains - enable cors @@ -45,9 +47,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .cors(CorsConfigurer::disable) .authorizeHttpRequests(req -> req .requestMatchers(HttpMethod.POST, "*/user").anonymous() // register - .requestMatchers("*/role").hasAuthority(ADMIN.scope()) + .requestMatchers("*/auth").anonymous() .requestMatchers("*/users/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) - .requestMatchers("*/auth").permitAll() // allow auth and anonymous users + .requestMatchers("*/moderator/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) .requestMatchers("*/account/generate-code").anonymous() // allow only anonymous .requestMatchers("*/account/restore-password").anonymous() .anyRequest().authenticated() diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java similarity index 58% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java index 53b394d..a2fdbea 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/AdminController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java @@ -1,10 +1,8 @@ package com.github.gribanoveu.cuddly.controllers.endpoints.admin; -import com.github.gribanoveu.cuddly.controllers.facade.admin.AdminControllerFacade; +import com.github.gribanoveu.cuddly.controllers.facade.admin.ModeratorControllerFacade; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; /** @@ -13,37 +11,37 @@ */ @RestController @RequiredArgsConstructor -@RequestMapping("/v1/users") -public class AdminController { - private final AdminControllerFacade adminControllerFacade; +@RequestMapping("/v1/moderator") +public class ModeratorController { + private final ModeratorControllerFacade moderatorControllerFacade; - @GetMapping + @GetMapping("/users-list") public ResponseEntity getAllUsersList(@RequestParam int pageNumber, @RequestParam int pageSize) { - return adminControllerFacade.getAllUsersList(pageNumber, pageSize); + return moderatorControllerFacade.getAllUsersList(pageNumber, pageSize); } @DeleteMapping("/{userId}") // only admin can delete user public ResponseEntity deleteUser(@PathVariable Long userId) { - return adminControllerFacade.deleteUser(userId); + return moderatorControllerFacade.deleteUser(userId); } @PatchMapping("/{userId}/disable") public ResponseEntity disableUser(@PathVariable Long userId) { - return adminControllerFacade.disableUser(userId); + return moderatorControllerFacade.disableUser(userId); } @PatchMapping("/{userId}/enable") public ResponseEntity enableUser(@PathVariable Long userId) { - return adminControllerFacade.enabledUser(userId); + return moderatorControllerFacade.enabledUser(userId); } @PatchMapping("/{userId}/ban") public ResponseEntity banUser(@PathVariable Long userId) { - return adminControllerFacade.banUser(userId); + return moderatorControllerFacade.banUser(userId); } @PatchMapping("/{userId}/mercy") public ResponseEntity mercyUser(@PathVariable Long userId) { - return adminControllerFacade.mercyUser(userId); + return moderatorControllerFacade.mercyUser(userId); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/AdminControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/ModeratorControllerFacade.java similarity index 98% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/AdminControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/ModeratorControllerFacade.java index e277789..e7b1326 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/AdminControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/ModeratorControllerFacade.java @@ -18,7 +18,7 @@ */ @Service @RequiredArgsConstructor -public class AdminControllerFacade { +public class ModeratorControllerFacade { private final UserService userService; private final PasswordEncoder passwordEncoder; From 769cb3d03a9bd24e4d9ecc878fa03c437a335c48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 26 Oct 2023 14:41:42 +0300 Subject: [PATCH 05/34] change email length to 80 symbols Took 5 hours 17 minutes --- .../cuddly/controllers/dtos/request/auth/LoginDto.java | 2 +- .../cuddly/controllers/dtos/request/auth/RegisterDto.java | 2 +- src/main/resources/db/migration/V1_0__create_users_table.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java index 6c0768b..b5681f3 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java @@ -14,7 +14,7 @@ public record LoginDto( @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) - @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) + @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String email, @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java index 1dc3364..ec88ac5 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java @@ -13,7 +13,7 @@ public record RegisterDto( @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) - @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) + @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String email, @MinimalAge(message = MINIMAL_AGE_EXCEPTION_MESSAGE) diff --git a/src/main/resources/db/migration/V1_0__create_users_table.sql b/src/main/resources/db/migration/V1_0__create_users_table.sql index 30c6229..a13ec29 100644 --- a/src/main/resources/db/migration/V1_0__create_users_table.sql +++ b/src/main/resources/db/migration/V1_0__create_users_table.sql @@ -2,7 +2,7 @@ CREATE TABLE users ( id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, version BIGINT NOT NULL, - email VARCHAR(30) NOT NULL UNIQUE, + email VARCHAR(80) NOT NULL UNIQUE, password VARCHAR(80) NOT NULL, birth_date DATE NOT NULL, registration_date TIMESTAMP NOT NULL, From fc9f3bc0420393209e1063d33f88d32491a94ba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 26 Oct 2023 14:42:36 +0300 Subject: [PATCH 06/34] add utils to log request and response Took 55 seconds --- .../cuddly/utils/aspects/LogRequest.java | 15 +++++ .../cuddly/utils/aspects/LogResponse.java | 15 +++++ .../utils/aspects/RequestLoggingAspect.java | 64 +++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java new file mode 100644 index 0000000..f8eecc4 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java @@ -0,0 +1,15 @@ +package com.github.gribanoveu.cuddly.utils.aspects; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Evgeny Gribanov + * @version 26.10.2023 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface LogRequest { +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java new file mode 100644 index 0000000..efd6264 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java @@ -0,0 +1,15 @@ +package com.github.gribanoveu.cuddly.utils.aspects; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Evgeny Gribanov + * @version 26.10.2023 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface LogResponse { +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java new file mode 100644 index 0000000..c92026e --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java @@ -0,0 +1,64 @@ +package com.github.gribanoveu.cuddly.utils.aspects; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.gribanoveu.cuddly.utils.JsonUtils; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.Arrays; +import java.util.Map; + +@Aspect +@Component +@Slf4j +@RequiredArgsConstructor +public class RequestLoggingAspect { + private final JsonUtils jsonUtils; + + @Around("@annotation(LogRequest)") + public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + + log.info(""" + Incoming request to server: + { + "Method":"%1$s", + "URI":"%3$s", + "RequestId":"%2$s", + "Details":[%4$s] + } + """.formatted(request.getMethod(), request.getRequestId(), request.getRequestURI(), + jsonUtils.convertDtoToJson(joinPoint.getArgs()[0])) + ); + + return joinPoint.proceed(); + } + + @AfterReturning(pointcut = "@annotation(LogResponse)", returning = "result") + public void logResponse(Object result) { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + + log.info(""" + Outgoing server response: + { + "Method":"%1$s", + "URI":"%3$s", + "RequestId":"%2$s", + "Details":[%4$s] + } + """.formatted(request.getMethod(), request.getRequestId(),request.getRequestURI(), + jsonUtils.convertDtoToJson(result))); + } +} From b93a639f39b171292f5439c9e9011631439f38c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 26 Oct 2023 14:44:03 +0300 Subject: [PATCH 07/34] change status level to warning in CredentialEx Took 1 minute --- .../cuddly/controllers/exeptions/GlobalExceptionHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java index 0602ed3..1ab1b4e 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java @@ -52,7 +52,7 @@ public ResponseEntity handleBadCredentialsException(BadCredentia @ExceptionHandler(CredentialEx.class) public ResponseEntity handleCredentialsException(CredentialEx e) { - var details = StatusResponse.create(e.getError(), StatusLevel.ERROR); + var details = StatusResponse.create(e.getError(), StatusLevel.WARNING); return ResponseEntity.status(e.getStatus()).body(details); } From a64a2ea8d31d3ee3ea81d8460001bac880b5ddb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 26 Oct 2023 14:45:05 +0300 Subject: [PATCH 08/34] refactor refresh token logic Took 1 minute --- .../cuddly/constants/RegexpFormat.java | 2 + .../facade/auth/AuthControllerFacade.java | 41 ++++------- .../cuddly/utils/RefreshTokenUtils.java | 72 +++++++++++++++++++ 3 files changed, 89 insertions(+), 26 deletions(-) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java b/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java index ada6e50..b1a9701 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java @@ -9,4 +9,6 @@ public class RegexpFormat { public static final String PERMISSION_PATTERN = "^[A-Z]{2}_[A-Z_]+$"; public static final String OTP_PATTERN = "^\\d{6}$"; public static final String BIRTHDAY_PATTERN = "^(19\\d{2}|20\\d{2}|2100)-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$"; + public static final String UNIX_DATE_TOKEN_PATTERN = "\\|(\\d+)"; + public static final String EMAIL_TOKEN_PATTERN = "^([^|]+)"; } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java index 10466da..07805a5 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; +import com.github.gribanoveu.cuddly.constants.RegexpFormat; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; @@ -11,6 +12,7 @@ import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import com.github.gribanoveu.cuddly.utils.RSAEncryption; import com.github.gribanoveu.cuddly.config.RsaProperties; +import com.github.gribanoveu.cuddly.utils.RefreshTokenUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -22,6 +24,9 @@ import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.time.Duration; +import java.time.Instant; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * @author Evgeny Gribanov @@ -31,49 +36,33 @@ @Service @RequiredArgsConstructor public class AuthControllerFacade { + @Value("${time-variable.accessTokenLifetime}") + private Duration accessTokenLifetime; private final TokenService tokenService; private final AuthenticationManager authManager; private final CustomUserDetailsService usrDetailsService; - private final RsaProperties rsaKeys; - private final RSAEncryption rsaEncryption; - - @Value("${time-variable.accessTokenLifetime}") private Duration accessTokenLifetime; + private final RefreshTokenUtils refreshTokenUtils; public ResponseEntity authenticateUser(LoginDto request) { var authenticationToken = new UsernamePasswordAuthenticationToken(request.email(), request.password()); var auth = authManager.authenticate(authenticationToken); var user = (CustomUserDetails) auth.getPrincipal(); var accessToken = tokenService.generateToken(user, TokenType.ACCESS); - var refreshToken = generateRefreshToken(request.email()); + var encryptedRefreshToken = refreshTokenUtils.generateEncryptedRefreshToken(request.email()); - return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, refreshToken)); + return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), + accessToken, encryptedRefreshToken)); // encrypted token so that it is not used as a main token } public ResponseEntity refreshToken(RefreshTokenDto request) { - var email = encryptRefreshToken(request.refreshToken()); + var email = refreshTokenUtils.validateRefreshTokenAndExtractEmail(request.refreshToken()); var user = (CustomUserDetails) usrDetailsService.loadUserByUsername(email); var accessToken = tokenService.generateToken(user, TokenType.ACCESS); - var refreshToken = generateRefreshToken(email); - - return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, refreshToken)); - } + var encryptedRefreshToken = refreshTokenUtils.generateEncryptedRefreshToken(email); - private String generateRefreshToken(String email) { - RSAPublicKey publicKey = rsaKeys.publicKey(); - try { - return rsaEncryption.encrypt(email, publicKey); - } catch (Exception e) { - throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); - } + return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), + accessToken, encryptedRefreshToken)); } - private String encryptRefreshToken(String token) { - RSAPrivateKey privateKey = rsaKeys.privateKey(); - try { - return rsaEncryption.decrypt(token, privateKey); - } catch (Exception e) { - throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); - } - } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java b/src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java new file mode 100644 index 0000000..0c2fa48 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java @@ -0,0 +1,72 @@ +package com.github.gribanoveu.cuddly.utils; + +import com.github.gribanoveu.cuddly.config.RsaProperties; +import com.github.gribanoveu.cuddly.constants.RegexpFormat; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Duration; +import java.time.Instant; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Evgeny Gribanov + * @version 24.10.2023 + */ +@Component +@RequiredArgsConstructor +public class RefreshTokenUtils { + @Value("${time-variable.refreshTokenLifetime}") + private Duration refreshTokenLifetime; + private final RsaProperties rsaKeys; + private final RSAEncryption rsaEncryption; + + public String generateEncryptedRefreshToken(String email) { + RSAPublicKey publicKey = rsaKeys.publicKey(); + try { + final String TOKEN_SEPARATOR = "|"; // admin@email.com|1698159942361 + var refreshTokenExpire = Instant.now().plus(refreshTokenLifetime).toEpochMilli(); + var refreshToken = email + TOKEN_SEPARATOR + refreshTokenExpire; + return rsaEncryption.encrypt(refreshToken, publicKey); + } catch (Exception e) { + throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); + } + } + + public String validateRefreshTokenAndExtractEmail(String token) { + RSAPrivateKey privateKey = rsaKeys.privateKey(); + try { + var tokenValue = rsaEncryption.decrypt(token, privateKey); + checkTokenValidity(tokenValue); + return extractEmailFromToken(tokenValue); + } catch (Exception e) { + throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); + } + } + + private void checkTokenValidity(String tokenValue) { + Pattern datePattern = Pattern.compile(RegexpFormat.UNIX_DATE_TOKEN_PATTERN); + Matcher dateMatcher = datePattern.matcher(tokenValue); + if (dateMatcher.find()) { // todo добавить отображение даты в лог + var refreshTokenDateInMillis = Long.parseLong(dateMatcher.group(1)); + if (Instant.now().toEpochMilli() > refreshTokenDateInMillis) { + throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); + } + } + } + + private String extractEmailFromToken(String tokenValue) { + Pattern emailPattern = Pattern.compile(RegexpFormat.EMAIL_TOKEN_PATTERN); + Matcher emailMatcher = emailPattern.matcher(tokenValue); + if (emailMatcher.find()) { + return emailMatcher.group(1); + } + throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); + } +} From 8ebf44ab36964e15d65e413c43147e484f6155d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 27 Nov 2023 11:46:55 +0300 Subject: [PATCH 09/34] refactor response log, add graylog Took 2 hours 10 minutes --- pom.xml | 6 +++- .../cuddly/config/SecurityConfig.java | 10 ++++-- .../endpoints/auth/AccountController.java | 17 +++++---- .../endpoints/auth/AuthController.java | 2 ++ .../endpoints/auth/UserController.java | 14 ++++++-- .../exeptions/GlobalExceptionHandler.java | 10 +++++- .../facade/auth/AccountControllerFacade.java | 8 ++--- .../facade/auth/UserControllerFacade.java | 6 ++-- .../services/otp/RedisOtpServiceImpl.java | 5 +-- .../cuddly/utils/aspects/LogResponse.java | 1 + .../utils/aspects/RequestLoggingAspect.java | 22 ++++++------ src/main/resources/application.yml | 2 ++ src/main/resources/logback.xml | 35 +++++++++++++++++++ 13 files changed, 103 insertions(+), 35 deletions(-) create mode 100644 src/main/resources/logback.xml diff --git a/pom.xml b/pom.xml index ab6087c..c51dc84 100644 --- a/pom.xml +++ b/pom.xml @@ -80,7 +80,11 @@ com.fasterxml.jackson.datatype jackson-datatype-jsr310 - + + de.siegmar + logback-gelf + 1.1.0 + diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index 2dd3825..ba60ed9 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -46,12 +46,16 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(CsrfConfigurer::disable) .cors(CorsConfigurer::disable) .authorizeHttpRequests(req -> req + // anonymous scope + .requestMatchers( HttpMethod.POST, "*/auth").anonymous() // issue token + .requestMatchers( HttpMethod.PATCH, "*/auth").anonymous() // refresh token .requestMatchers(HttpMethod.POST, "*/user").anonymous() // register - .requestMatchers("*/auth").anonymous() + .requestMatchers(HttpMethod.POST, "*/generate-code").anonymous() + .requestMatchers(HttpMethod.POST, "*/restore-password").anonymous() + + // authenticated scope .requestMatchers("*/users/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) .requestMatchers("*/moderator/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) - .requestMatchers("*/account/generate-code").anonymous() // allow only anonymous - .requestMatchers("*/account/restore-password").anonymous() .anyRequest().authenticated() ) .sessionManagement(manager -> manager diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java index 9030cb7..74d5b6f 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java @@ -4,7 +4,10 @@ import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RestorePasswordDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; import com.github.gribanoveu.cuddly.controllers.facade.auth.AccountControllerFacade; +import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; +import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -21,23 +24,25 @@ public class AccountController { private final AccountControllerFacade userControllerFacade; + @LogRequest + @LogResponse @PatchMapping("/change-email") - public ResponseEntity changeEmail(@Valid @RequestBody ChangeEmailDto request, Authentication authentication) { - return userControllerFacade.changeEmail(request, authentication); + public ResponseEntity changeEmail(@Valid @RequestBody ChangeEmailDto request, Authentication auth) { + return userControllerFacade.changeEmail(request, auth); } @PatchMapping("/change-password") - public ResponseEntity changePassword(@Valid @RequestBody ChangePasswordDto request, Authentication authentication) { - return userControllerFacade.changePassword(request, authentication); + public ResponseEntity changePassword(@Valid @RequestBody ChangePasswordDto request, Authentication auth) { + return userControllerFacade.changePassword(request, auth); } @PostMapping("/generate-code") // anonymous access - public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request) { + public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request) { return userControllerFacade.generateOtpCode(request); } @PostMapping("/restore-password") // anonymous access - public ResponseEntity restorePassword(@Valid @RequestBody RestorePasswordDto request) { + public ResponseEntity restorePassword(@Valid @RequestBody RestorePasswordDto request) { return userControllerFacade.restorePasswordByOtp(request); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java index 4638730..0b90359 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java @@ -4,6 +4,8 @@ import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; import com.github.gribanoveu.cuddly.controllers.facade.auth.AuthControllerFacade; +import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; +import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java index 13572e0..5723c4b 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java @@ -1,7 +1,11 @@ package com.github.gribanoveu.cuddly.controllers.endpoints.auth; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; import com.github.gribanoveu.cuddly.controllers.facade.auth.UserControllerFacade; +import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; +import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -21,18 +25,22 @@ public class UserController { private final UserControllerFacade userControllerFacade; + @LogRequest + @LogResponse @GetMapping - public ResponseEntity getUserData(Authentication authentication) { + public ResponseEntity getUserData(Authentication authentication) { return userControllerFacade.getUserData(authentication); } + @LogRequest + @LogResponse @PostMapping - public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { + public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { return userControllerFacade.registerUser(request); } @DeleteMapping - public ResponseEntity deleteUser(Authentication authentication) { + public ResponseEntity deleteUser(Authentication authentication) { return userControllerFacade.deleteUser(authentication); } } \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java index 1ab1b4e..8cb8b9c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java @@ -5,6 +5,7 @@ import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; import jakarta.validation.ConstraintViolationException; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; @@ -25,24 +26,28 @@ @RestControllerAdvice public class GlobalExceptionHandler { + @LogResponse @ExceptionHandler(HttpMediaTypeNotSupportedException.class) public ResponseEntity handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) { var details = StatusResponse.create(ResponseCode.VALIDATION_ERROR, StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.VALIDATION_ERROR.getHttpCode()).body(details); } + @LogResponse @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { var details = StatusResponse.create(ResponseCode.VALIDATION_ERROR, StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.VALIDATION_ERROR.getHttpCode()).body(details); } + @LogResponse @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException e) { var details = StatusResponse.create(ResponseCode.RESOURCE_NOT_FOUND, StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.RESOURCE_NOT_FOUND.getHttpCode()).body(details); } + @LogResponse @ExceptionHandler(BadCredentialsException.class) public ResponseEntity handleBadCredentialsException(BadCredentialsException e) { var details = StatusResponse.create( @@ -50,12 +55,14 @@ public ResponseEntity handleBadCredentialsException(BadCredentia return ResponseEntity.status(ResponseCode.BAD_CREDENTIAL.getHttpCode()).body(details); } + @LogResponse @ExceptionHandler(CredentialEx.class) public ResponseEntity handleCredentialsException(CredentialEx e) { var details = StatusResponse.create(e.getError(), StatusLevel.WARNING); return ResponseEntity.status(e.getStatus()).body(details); } + @LogResponse(message = "Validation error") @ExceptionHandler(MethodArgumentNotValidException.class) // @Valid handler public ResponseEntity handleValidAnnotationException(MethodArgumentNotValidException e) { var errors = e.getBindingResult().getFieldErrors().stream() @@ -68,7 +75,7 @@ public ResponseEntity handleValidAnnotationException(MethodArgumentNotValidEx return ResponseEntity.status(e.getStatusCode()).body(details); } - + @LogResponse @ExceptionHandler(ConstraintViolationException.class) // database entity handler public ResponseEntity handleDatabaseValidationException(ConstraintViolationException e) { var errors = e.getConstraintViolations().stream() @@ -80,6 +87,7 @@ public ResponseEntity handleDatabaseValidationException(ConstraintViolationEx } + @LogResponse @ExceptionHandler(MissingServletRequestParameterException.class) // query param handler public ResponseEntity handleMissingParamException(MissingServletRequestParameterException e) { var details = StatusResponse.create(ResponseCode.MISSING_PARAM, StatusLevel.ERROR); diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java index 9ca603c..01fefaf 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java @@ -35,7 +35,7 @@ public class AccountControllerFacade { private final JsonUtils jsonUtils; // user change email from app, authenticated - public ResponseEntity changeEmail(ChangeEmailDto request, Authentication authentication) { + public ResponseEntity changeEmail(ChangeEmailDto request, Authentication authentication) { var user = userService.findUserByEmail(authentication.getName()); userService.updateEmail(user, request.email()); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UPDATED, StatusLevel.SUCCESS)); @@ -46,7 +46,7 @@ public ResponseEntity changeEmail(ChangeEmailDto request, Authentication auth // verify that the old password matches, if not -> error // check that old password not equals new password, else -> error // change password - public ResponseEntity changePassword(ChangePasswordDto request, Authentication authentication) { + public ResponseEntity changePassword(ChangePasswordDto request, Authentication authentication) { if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); var user = userService.findUserByEmail(authentication.getName()); @@ -67,7 +67,7 @@ public ResponseEntity changePassword(ChangePasswordDto request, Authenticatio // else create new code // save otp code to db (with lifetime) // todo send email with code - public ResponseEntity generateOtpCode(GenerateOtpDto request) { + public ResponseEntity generateOtpCode(GenerateOtpDto request) { var userExist = userService.userExistByEmail(request.email()); if (!userExist) throw new CredentialEx(ResponseCode.USER_NOT_EXIST); var otpCode = jsonUtils.generateRandomOtpCode().toString(); @@ -79,7 +79,7 @@ public ResponseEntity generateOtpCode(GenerateOtpDto request) { // service check that code exist and have valid lifetime // service find userId by otp code and change password in db // send successful email - public ResponseEntity restorePasswordByOtp(RestorePasswordDto request) { + public ResponseEntity restorePasswordByOtp(RestorePasswordDto request) { if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); if (!redisOtpService.otpCodeValid(request.email(), request.otpCode())) throw new CredentialEx(ResponseCode.OTP_CODE_NOT_FOUND); diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java index b754fac..4b75738 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java @@ -30,12 +30,12 @@ public class UserControllerFacade { private final UserService userService; private final PasswordEncoder passwordEncoder; - public ResponseEntity getUserData(Authentication authentication) { + public ResponseEntity getUserData(Authentication authentication) { var userData = userService.findUserByEmail(authentication.getName()); return ResponseEntity.ok(userData); } - public ResponseEntity registerUser(RegisterDto request) { + public ResponseEntity registerUser(RegisterDto request) { if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); if (userService.userExistByEmail(request.email())) throw new CredentialEx(ResponseCode.USER_ALREADY_EXIST); @@ -54,7 +54,7 @@ public ResponseEntity registerUser(RegisterDto request) { ResponseCode.USER_CREATED, StatusLevel.SUCCESS)); } - public ResponseEntity deleteUser(Authentication authentication) { + public ResponseEntity deleteUser(Authentication authentication) { userService.deleteUserByEmail(authentication.getName()); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS)); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java index 886e624..3546fa2 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java @@ -23,10 +23,7 @@ public class RedisOtpServiceImpl implements RedisOtpService { @Override public void saveOptCode(String email, String code, Duration codeDuration) { var otpCode = getOtpCode(email); - if (otpCode.isPresent()) { - var codeDurationInMinutes = getOtpExpire(email, TimeUnit.MINUTES); // fixme - throw new CredentialEx(ResponseCode.OTP_CODE_EXIST); - } + if (otpCode.isPresent()) throw new CredentialEx(ResponseCode.OTP_CODE_EXIST); redisTemplate.opsForValue().set(email, code, codeDuration); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java index efd6264..ee4200a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java @@ -12,4 +12,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LogResponse { + String message() default ""; } diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java index c92026e..986c654 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java @@ -11,6 +11,7 @@ import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -27,11 +28,10 @@ public class RequestLoggingAspect { @Around("@annotation(LogRequest)") public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = attributes.getRequest(); - + var attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + var request = attributes.getRequest(); log.info(""" - Incoming request to server: + [REQUEST] Incoming request to server: { "Method":"%1$s", "URI":"%3$s", @@ -46,12 +46,11 @@ public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable { } @AfterReturning(pointcut = "@annotation(LogResponse)", returning = "result") - public void logResponse(Object result) { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = attributes.getRequest(); - - log.info(""" - Outgoing server response: + public void logResponse(JoinPoint joinPoint, Object result) { + var attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + var annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(LogResponse.class); + var request = attributes.getRequest(); + var message = (""" { "Method":"%1$s", "URI":"%3$s", @@ -60,5 +59,8 @@ public void logResponse(Object result) { } """.formatted(request.getMethod(), request.getRequestId(),request.getRequestURI(), jsonUtils.convertDtoToJson(result))); + + if (annotation.message().isBlank()) log.info("[RESPONSE] Outgoing server response:\n {}", message); + else log.info("[RESPONSE] {}\n {}", annotation.message(), message); } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b85396c..b70a057 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -37,3 +37,5 @@ spring: redis: host: localhost port: 6379 + application: + name: auth-service diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..7e0651c --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,35 @@ + + + + + localhost + 12201 + 508 + true + + localhost + false + true + true + false + false + true + + %m%nopex + + + %m + + app_name:backend + os_arch:${os.arch} + os_name:${os.name} + os_version:${os.version} + + + + + + + + + \ No newline at end of file From dd5eba03c420a37763fc407f6feff57b7ab9cc4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 27 Nov 2023 17:22:31 +0300 Subject: [PATCH 10/34] fix anonymous account endpoint Took 26 minutes --- .../com/github/gribanoveu/cuddly/config/SecurityConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index ba60ed9..57c359c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -50,8 +50,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .requestMatchers( HttpMethod.POST, "*/auth").anonymous() // issue token .requestMatchers( HttpMethod.PATCH, "*/auth").anonymous() // refresh token .requestMatchers(HttpMethod.POST, "*/user").anonymous() // register - .requestMatchers(HttpMethod.POST, "*/generate-code").anonymous() - .requestMatchers(HttpMethod.POST, "*/restore-password").anonymous() + .requestMatchers(HttpMethod.POST, "*/account/generate-code").anonymous() + .requestMatchers(HttpMethod.POST, "*/account/restore-password").anonymous() // authenticated scope .requestMatchers("*/users/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) From 71ae1a8c5e7308aa39179dbf666c11209f8083b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 28 Nov 2023 15:07:39 +0300 Subject: [PATCH 11/34] clean response messages Took 3 hours 41 minutes --- .../cuddly/entities/enums/ResponseCode.java | 64 ++++++++++--------- 1 file changed, 35 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java index dec051b..aeaec3d 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java @@ -15,43 +15,43 @@ public enum ResponseCode { SERVER_ERROR( "AUT-100", "Internal server error", - "Server Error. Try refreshing the page or returning later. Contact your administrator if the problem still exists.", + "Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR ), ACCESS_DENIED( "AUT-101", "Access denied", - "Access denied. Please check your credentials and make sure you have the required access rights.", + "Access denied. Please check your credentials and make sure you have the required access rights", HttpStatus.FORBIDDEN ), UNAUTHORIZED( "AUT-102", "Unauthorized access", - "Authorization required. Log in to your account to access this page. If you have forgotten your credentials, please use the password recovery feature.", + "Authorization required. Log in to your account to access this page. If you have forgotten your credentials, please use the password recovery feature", HttpStatus.UNAUTHORIZED ), BAD_CREDENTIAL( "AUT-103", "Invalid credentials", - "Incorrect credentials. Please verify that the information entered is correct and try again. If you have forgotten your credentials, please use the password recovery feature.", + "Incorrect credentials. Please verify that the information entered is correct and try again. If you have forgotten your credentials, please use the password recovery feature", HttpStatus.BAD_REQUEST ), MISSING_PARAM( "AUT-104", "Missing required query parameter", - "Required query parameter is missing. Please make sure you have entered all required parameters and try again.", + "Required query parameter is missing. Please make sure you have entered all required parameters and try again", HttpStatus.BAD_REQUEST ), TOKEN_NOT_VALID( "AUT-105", "Invalid token", - "Invalid token. Please make sure you are using a valid token and try again.", + "Invalid token. Please make sure you are using a valid token and try again", HttpStatus.UNAUTHORIZED ), VALIDATION_ERROR( "AUT-106", "Validation error", - "Validation Error. Please check that the data is in the correct format and try again.", + "Validation Error. Please check that the data is in the correct format and try again", HttpStatus.BAD_REQUEST ), VALIDATION_ERROR_DETAIL( @@ -63,7 +63,7 @@ public enum ResponseCode { RESOURCE_NOT_FOUND( "AUT-108", "Resource not found", - "The requested resource could not be found. Please verify that the information entered is correct and try again.", + "The requested resource could not be found. Please verify that the information entered is correct and try again", HttpStatus.NOT_FOUND ), ACCOUNT_BANNED( @@ -93,127 +93,133 @@ public enum ResponseCode { PASSWORD_NOT_EQUALS( "AUT-201", "Passwords do not match", - "The passwords do not match. Please make sure you have entered the same passwords and try again.", + "The passwords do not match. Please make sure you have entered the same passwords and try again", HttpStatus.BAD_REQUEST ), PASSWORD_EQUALS( "AUT-202", "Password equals", - "The new password must be different from the old one. Please enter a different password and try again.", + "The new password must be different from the old one. Please enter a different password and try again", HttpStatus.BAD_REQUEST ), OLD_PASSWORD_NOT_MATCH( "AUT-203", "Passwords do not match", - "The old password does not match the current password. Please make sure you have entered the correct old password and try again.", + "The old password does not match the current password. Please make sure you have entered the correct old password and try again", HttpStatus.BAD_REQUEST ), OTP_CODE_CREATED( "AUT-300", "OTP code created", - "The one-time access code (OTP) has been successfully created. Please check your e-mail ", + "The one-time access code (OTP) has been successfully created. Please check your e-mail", HttpStatus.OK ), OTP_CODE_NOT_FOUND( "AUT-301", "OTP code not found", - "The One-Time Access (OTP) code was not found. Please make sure you have entered the correct code and try again. If you do not have a valid code, please create a new code.", + "The One-Time Access (OTP) code was not found. Please make sure you have entered the correct code and try again. If you do not have a valid code, please create a new code", HttpStatus.NOT_FOUND ), OTP_CODE_EXIST( "AUT-302", "OTP code exist", - "The one-time access code (OTP) has already been created. Please check your email. If you have not received the code, please wait before creating a new code.", + "The one-time access code (OTP) has already been created. Please check your email. If you have not received the code, please wait before creating a new code", + HttpStatus.TOO_MANY_REQUESTS + ), + EMAIL_NOT_SEND( + "AUT-303", + "Error when send email", + "An error occurred when sending an email to this email account", HttpStatus.TOO_MANY_REQUESTS ), USER_CREATED( "AUT-400", "User created", - "User has been successfully created.", + "User has been successfully created", HttpStatus.OK ), USER_DELETED( "AUT-401", "User deleted", - "User has been successfully deleted.", + "User has been successfully deleted", HttpStatus.OK ), USER_DISABLED( "AUT-402", "User disabled", - "User has been successfully disabled.", + "User has been successfully disabled", HttpStatus.OK ), USER_ENABLED( "AUT-403", "User enabled", - "User has been successfully enabled.", + "User has been successfully enabled", HttpStatus.OK ), USER_NOT_EXIST( "AUT-404", "User not found", - "User not found. Please make sure you have entered the correct email and try again.", + "User not found. Please make sure you have entered the correct email and try again", HttpStatus.NOT_FOUND ), USER_DEFAULT_PASSWORD( "AUT-405", "Set default password", - "Default password has been successfully set for the user.", + "Default password has been successfully set for the user", HttpStatus.OK ), USER_UPDATED( "AUT-406", "User updated successfully", - "User has been successfully updated.", + "User has been successfully updated", HttpStatus.OK ), USER_ALREADY_EXIST( "AUT-407", "User already exists", - "User already exists. Please make sure you have entered the correct email and try again.", + "User already exists. Please make sure you have entered the correct email and try again", HttpStatus.CONFLICT ), USER_BANNED( "AUT-408", "User banned", - "User has been successfully banned.", + "User has been successfully banned", HttpStatus.OK ), USER_UN_BANNED( "AUT-409", "User unbanned", - "User has been successfully unbanned.", + "User has been successfully unbanned", HttpStatus.OK ), PERMISSION_CREATED( "AUT-500", "Permission created", - "Permission has been successfully created.", + "Permission has been successfully created", HttpStatus.OK ), PERMISSION_DELETED( "AUT-501", "Permission deleted", - "Permission has been successfully deleted.", + "Permission has been successfully deleted", HttpStatus.OK ), PERMISSION_UPDATED( "AUT-502", "Permission updated", - "Permission has been successfully updated.", + "Permission has been successfully updated", HttpStatus.OK ), PERMISSION_EXIST( "AUT-504", "Permission already exists", - "Permission already exists. Please make sure you have entered the correct permission name and try again.", + "Permission already exists. Please make sure you have entered the correct permission name and try again", HttpStatus.CONFLICT ), PERMISSION_NOT_EXIST( "AUT-505", "Permission not found", - "Permission not found. Please make sure you have entered the correct permission name and try again.", + "Permission not found. Please make sure you have entered the correct permission name and try again", HttpStatus.NOT_FOUND ); From 7c858b0e0055430c99c4e5c8ddfe481594a7eebf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 28 Nov 2023 15:08:26 +0300 Subject: [PATCH 12/34] fix server error message Took 47 seconds --- .../controllers/exeptions/entrypoint/ServerErrorEntryPoint.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java index 68db77a..2dd6764 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -41,7 +41,7 @@ public void commence( } else if (authException instanceof LockedException) { error = StatusResponse.create(ACCOUNT_BANNED, ACCOUNT_BANNED.getMessage(), StatusLevel.ERROR); - } else error = StatusResponse.create(ACCESS_DENIED, authException.getMessage(), StatusLevel.ERROR); + } else error = StatusResponse.create(SERVER_ERROR, StatusLevel.ERROR); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); From 444c5602773bff025b349c6c3a6b3ffc5aa552e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Tue, 28 Nov 2023 15:08:43 +0300 Subject: [PATCH 13/34] create service to send email, add email when restore password Took 17 seconds --- pom.xml | 8 +++ .../cuddly/config/ThymeleafConfig.java | 45 ++++++++++++ .../cuddly/constants/EmailMessages.java | 11 +++ .../dtos/data/AbstractEmailContext.java | 18 +++++ .../controllers/dtos/data/OtpCodeEmail.java | 8 +++ .../endpoints/auth/AccountController.java | 5 +- .../facade/auth/AccountControllerFacade.java | 42 +++++++++-- .../entities/services/email/EmailService.java | 13 ++++ .../services/email/EmailServiceImpl.java | 65 +++++++++++++++++ src/main/resources/application.yml | 13 +++- .../resources/template/otp-code-template.html | 69 +++++++++++++++++++ 11 files changed, 288 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java create mode 100644 src/main/resources/template/otp-code-template.html diff --git a/pom.xml b/pom.xml index c51dc84..cc552a1 100644 --- a/pom.xml +++ b/pom.xml @@ -55,6 +55,14 @@ org.springframework.boot spring-boot-starter-oauth2-resource-server + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-thymeleaf + diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java new file mode 100644 index 0000000..be2fc05 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java @@ -0,0 +1,45 @@ +package com.github.gribanoveu.cuddly.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.ViewResolver; +import org.thymeleaf.spring6.SpringTemplateEngine; +import org.thymeleaf.spring6.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; + +/** + * @author Evgeny Gribanov + * @version 28.11.2023 + */ +@Configuration +public class ThymeleafConfig { + + @Bean + public ClassLoaderTemplateResolver templateResolver() { + var templateResolver = new ClassLoaderTemplateResolver(); + templateResolver.setPrefix("template/"); + templateResolver.setCacheable(false); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + templateResolver.setCharacterEncoding("UTF-8"); + return templateResolver; + } + + @Bean + public SpringTemplateEngine templateEngine() { + var templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } + + @Bean + public ViewResolver viewResolver() { + var viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setCharacterEncoding("UTF-8"); + return viewResolver; + } + +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java b/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java new file mode 100644 index 0000000..25979db --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java @@ -0,0 +1,11 @@ +package com.github.gribanoveu.cuddly.constants; + +/** + * @author Evgeny Gribanov + * @version 27.11.2023 + */ +public class EmailMessages { + public static final String sendFrom = "robot@codecow.pw"; + public static final String emailSubjectRestorePassword = "Восстановление пароля"; + public static final String restorePasswordTemplateName = "otp-code-template"; +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java new file mode 100644 index 0000000..3c8ca04 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java @@ -0,0 +1,18 @@ +package com.github.gribanoveu.cuddly.controllers.dtos.data; + +import lombok.Data; + +import java.util.Map; + +/** + * @author Evgeny Gribanov + * @version 28.11.2023 + */ +@Data +public abstract class AbstractEmailContext { + private String from; + private String to; + private String subject; + private String templateLocation; + private Map context; +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java new file mode 100644 index 0000000..767302e --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java @@ -0,0 +1,8 @@ +package com.github.gribanoveu.cuddly.controllers.dtos.data; + +/** + * @author Evgeny Gribanov + * @version 28.11.2023 + */ +public class OtpCodeEmail extends AbstractEmailContext { +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java index 74d5b6f..1b84041 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java @@ -8,6 +8,7 @@ import com.github.gribanoveu.cuddly.controllers.facade.auth.AccountControllerFacade; import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -37,8 +38,8 @@ public ResponseEntity changePassword(@Valid @RequestBody ChangeP } @PostMapping("/generate-code") // anonymous access - public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request) { - return userControllerFacade.generateOtpCode(request); + public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request, HttpServletRequest http) { + return userControllerFacade.generateOtpCode(request, http); } @PostMapping("/restore-password") // anonymous access diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java index 01fefaf..3a6bdaa 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java @@ -1,5 +1,8 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; +import com.github.gribanoveu.cuddly.constants.EmailMessages; +import com.github.gribanoveu.cuddly.controllers.dtos.data.AbstractEmailContext; +import com.github.gribanoveu.cuddly.controllers.dtos.data.OtpCodeEmail; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; @@ -8,10 +11,13 @@ import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.services.email.EmailService; import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; import com.github.gribanoveu.cuddly.entities.services.user.UserService; import com.github.gribanoveu.cuddly.utils.JsonUtils; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; @@ -19,11 +25,14 @@ import org.springframework.stereotype.Service; import java.time.Duration; +import java.time.LocalDateTime; +import java.util.Map; /** * @author Evgeny Gribanov * @version 22.09.2023 */ +@Slf4j @Service @RequiredArgsConstructor public class AccountControllerFacade { @@ -32,6 +41,7 @@ public class AccountControllerFacade { private final UserService userService; private final RedisOtpService redisOtpService; private final PasswordEncoder passwordEncoder; + private final EmailService emailService; private final JsonUtils jsonUtils; // user change email from app, authenticated @@ -60,18 +70,23 @@ public ResponseEntity changePassword(ChangePasswordDto request, } // user open restore form and enter email - // service find user by email, - // if user not found -> error - // service find otp code - // if exist -> error + // service find user by email, if user not found -> error + // service find otp code, if exist -> error // else create new code + // send email, if not -> error // save otp code to db (with lifetime) - // todo send email with code - public ResponseEntity generateOtpCode(GenerateOtpDto request) { + public ResponseEntity generateOtpCode(GenerateOtpDto request, HttpServletRequest http) { var userExist = userService.userExistByEmail(request.email()); if (!userExist) throw new CredentialEx(ResponseCode.USER_NOT_EXIST); var otpCode = jsonUtils.generateRandomOtpCode().toString(); + log.info("RequestId: {}. Generate OTP code. Email {}, Code {}", http.getRequestId(), request.email(), otpCode); + + emailService.sendMail(generateOtpEmailTemplate(request.email(), otpCode)); + log.info("RequestId: {}. Email with code send to: {}", http.getRequestId(), request.email()); + redisOtpService.saveOptCode(request.email(), otpCode, otpCodeLifeTime); + log.info("RequestId: {}. OTP code to email: {} saved", http.getRequestId(), request.email()); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.OTP_CODE_CREATED, StatusLevel.SUCCESS)); } @@ -91,4 +106,19 @@ public ResponseEntity restorePasswordByOtp(RestorePasswordDto re } throw new CredentialEx(ResponseCode.PASSWORD_EQUALS); } + + private OtpCodeEmail generateOtpEmailTemplate(String sendToEmail, String otpCode) { + var email = new OtpCodeEmail(); + email.setTo(sendToEmail); + email.setFrom(EmailMessages.sendFrom); + email.setSubject(EmailMessages.emailSubjectRestorePassword); + email.setTemplateLocation(EmailMessages.restorePasswordTemplateName); + email.setContext(Map.of( + "otpCode", otpCode, + "otpCodeLifetime", otpCodeLifeTime.toMinutes(), + "loginTime", LocalDateTime.now(), + "email", sendToEmail + )); + return email; + } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java new file mode 100644 index 0000000..5a2ac6f --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java @@ -0,0 +1,13 @@ +package com.github.gribanoveu.cuddly.entities.services.email; + +import com.github.gribanoveu.cuddly.controllers.dtos.data.AbstractEmailContext; +import jakarta.mail.MessagingException; + +/** + * @author Evgeny Gribanov + * @version 27.11.2023 + */ +public interface EmailService { + void sendEmail(String toEmail, String subject, String message); + void sendMail(AbstractEmailContext email); +} diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java new file mode 100644 index 0000000..65409aa --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java @@ -0,0 +1,65 @@ +package com.github.gribanoveu.cuddly.entities.services.email; + +import com.github.gribanoveu.cuddly.controllers.dtos.data.AbstractEmailContext; +import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import jakarta.mail.MessagingException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; + +import java.nio.charset.StandardCharsets; + +/** + * @author Evgeny Gribanov + * @version 27.11.2023 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class EmailServiceImpl implements EmailService { + private final JavaMailSender mailSender; + private final TemplateEngine templateEngine; + + + @Override + public void sendEmail(String toEmail, String subject, String message) { + var simpleMailMessage = new SimpleMailMessage(); + simpleMailMessage.setTo(toEmail); + simpleMailMessage.setSubject(subject); + simpleMailMessage.setText(message); + try { + mailSender.send(simpleMailMessage); + } catch (MailException e) { + throw new CredentialEx(ResponseCode.EMAIL_NOT_SEND); + } + } + + @Override + public void sendMail(AbstractEmailContext email) { + try { + var message = mailSender.createMimeMessage(); + var mimeMessageHelper = new MimeMessageHelper(message, + MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, + StandardCharsets.UTF_8.name()); + var context = new Context(); + context.setVariables(email.getContext()); + var emailContent = templateEngine.process(email.getTemplateLocation(), context); + + mimeMessageHelper.setTo(email.getTo()); + mimeMessageHelper.setSubject(email.getSubject()); + mimeMessageHelper.setFrom(email.getFrom()); + mimeMessageHelper.setText(emailContent, true); + + mailSender.send(message); + } catch (MailException | MessagingException e) { + throw new CredentialEx(ResponseCode.EMAIL_NOT_SEND); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b70a057..c441123 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -10,6 +10,17 @@ rsa: private-key: classpath:certs/private.pem public-key: classpath:certs/public.pem spring: + mail: + host: smtp.gmail.com + port: 587 + username: ${SPRING_EMAIL_USER} + password: ${SPRING_EMAIL_PASSWORD} + properties: + mail: + smtp: + auth: true + starttls: + enable: true mvc: throw-exception-if-no-handler-found: true web: @@ -38,4 +49,4 @@ spring: host: localhost port: 6379 application: - name: auth-service + name: cuddle-backend \ No newline at end of file diff --git a/src/main/resources/template/otp-code-template.html b/src/main/resources/template/otp-code-template.html new file mode 100644 index 0000000..3a7894f --- /dev/null +++ b/src/main/resources/template/otp-code-template.html @@ -0,0 +1,69 @@ + + + + OTP Code + + + + + + + + + + + +
+
+
Здравствуйте!
+
 
+
Для вашего аккаунта запрошено восстановление пароля.
+
+ Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо. +
+
+
+ Чтобы продолжить процедуру восстановления пароля, введите следующий код: +
+
+

123456

+
+
+
+
Детали входа:
+
+
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно создано автоматически. +
+
По всем вопросам обращайтесь в support@cuddly.pw
+
---
+
С уважением, администрация Cuddle
+
+
+
 
+
2023 © Codecow.pw
+ + + From b6a73a773f3129a4ac8b63324c38a5ad0c68a34d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sat, 2 Dec 2023 17:15:21 +0300 Subject: [PATCH 14/34] add email template Took 2 hours 20 minutes --- pom.xml | 2 +- .../cuddly/constants/EmailMessages.java | 8 +- .../dtos/data/AbstractEmailContext.java | 18 --- .../controllers/dtos/data/OtpCodeEmail.java | 8 - .../dtos/data/SimpleEmailObject.java | 16 ++ .../endpoints/auth/AccountController.java | 2 + .../facade/auth/AccountControllerFacade.java | 29 +--- .../entities/services/email/EmailService.java | 5 +- .../services/email/EmailServiceImpl.java | 14 +- .../emails/RestorePasswordEmailTemplates.java | 40 +++++ .../resources/template/otp-code-template.html | 137 ++++++++++-------- .../resources/template/password-changed.html | 74 ++++++++++ 12 files changed, 232 insertions(+), 121 deletions(-) delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java create mode 100644 src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java create mode 100644 src/main/resources/template/password-changed.html diff --git a/pom.xml b/pom.xml index cc552a1..dcaa420 100644 --- a/pom.xml +++ b/pom.xml @@ -91,7 +91,7 @@ de.siegmar logback-gelf - 1.1.0 + 5.0.0 diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java b/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java index 25979db..22fdbd0 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java @@ -5,7 +5,11 @@ * @version 27.11.2023 */ public class EmailMessages { - public static final String sendFrom = "robot@codecow.pw"; - public static final String emailSubjectRestorePassword = "Восстановление пароля"; + public static final String sendFrom = "noreply@codecow.pw"; + public static final String restorePasswordEmailSubject = "Восстановление пароля"; public static final String restorePasswordTemplateName = "otp-code-template"; + + public static final String passwordChangedEmailSubject = "Пароль успешно изменен"; + public static final String passwordChangedTemplateName = "password-changed"; + } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java deleted file mode 100644 index 3c8ca04..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/AbstractEmailContext.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.data; - -import lombok.Data; - -import java.util.Map; - -/** - * @author Evgeny Gribanov - * @version 28.11.2023 - */ -@Data -public abstract class AbstractEmailContext { - private String from; - private String to; - private String subject; - private String templateLocation; - private Map context; -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java deleted file mode 100644 index 767302e..0000000 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/OtpCodeEmail.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.data; - -/** - * @author Evgeny Gribanov - * @version 28.11.2023 - */ -public class OtpCodeEmail extends AbstractEmailContext { -} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java new file mode 100644 index 0000000..36ed4a3 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java @@ -0,0 +1,16 @@ +package com.github.gribanoveu.cuddly.controllers.dtos.data; + +import java.util.Map; + +/** + * @author Evgeny Gribanov + * @version 28.11.2023 + */ + +public record SimpleEmailObject( + String from, + String to, + String subject, + String templateLocation, + Map context +) {} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java index 1b84041..d0a59b8 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java @@ -37,6 +37,8 @@ public ResponseEntity changePassword(@Valid @RequestBody ChangeP return userControllerFacade.changePassword(request, auth); } + @LogRequest + @LogResponse @PostMapping("/generate-code") // anonymous access public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request, HttpServletRequest http) { return userControllerFacade.generateOtpCode(request, http); diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java index 3a6bdaa..a7748d7 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java @@ -1,8 +1,5 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; -import com.github.gribanoveu.cuddly.constants.EmailMessages; -import com.github.gribanoveu.cuddly.controllers.dtos.data.AbstractEmailContext; -import com.github.gribanoveu.cuddly.controllers.dtos.data.OtpCodeEmail; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; @@ -15,18 +12,21 @@ import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; import com.github.gribanoveu.cuddly.entities.services.user.UserService; import com.github.gribanoveu.cuddly.utils.JsonUtils; +import com.github.gribanoveu.cuddly.utils.emails.RestorePasswordEmailTemplates; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Service; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; import java.time.Duration; -import java.time.LocalDateTime; -import java.util.Map; /** * @author Evgeny Gribanov @@ -81,7 +81,7 @@ public ResponseEntity generateOtpCode(GenerateOtpDto request, Ht var otpCode = jsonUtils.generateRandomOtpCode().toString(); log.info("RequestId: {}. Generate OTP code. Email {}, Code {}", http.getRequestId(), request.email(), otpCode); - emailService.sendMail(generateOtpEmailTemplate(request.email(), otpCode)); + emailService.sendMail(RestorePasswordEmailTemplates.generateOtpEmail(request.email(), otpCode, otpCodeLifeTime)); log.info("RequestId: {}. Email with code send to: {}", http.getRequestId(), request.email()); redisOtpService.saveOptCode(request.email(), otpCode, otpCodeLifeTime); @@ -102,23 +102,10 @@ public ResponseEntity restorePasswordByOtp(RestorePasswordDto re if (!passwordEncoder.matches(request.password(), user.getPassword())) { userService.updatePasswordByEmail(user, passwordEncoder.encode(request.password())); redisOtpService.deleteOtpCode(request.email()); + emailService.sendMail(RestorePasswordEmailTemplates.passwordChangedEmail(request.email())); + log.info("Password change message sent to: {}", request.email()); return ResponseEntity.ok(StatusResponse.create(ResponseCode.PASSWORD_UPDATED, StatusLevel.SUCCESS)); } throw new CredentialEx(ResponseCode.PASSWORD_EQUALS); } - - private OtpCodeEmail generateOtpEmailTemplate(String sendToEmail, String otpCode) { - var email = new OtpCodeEmail(); - email.setTo(sendToEmail); - email.setFrom(EmailMessages.sendFrom); - email.setSubject(EmailMessages.emailSubjectRestorePassword); - email.setTemplateLocation(EmailMessages.restorePasswordTemplateName); - email.setContext(Map.of( - "otpCode", otpCode, - "otpCodeLifetime", otpCodeLifeTime.toMinutes(), - "loginTime", LocalDateTime.now(), - "email", sendToEmail - )); - return email; - } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java index 5a2ac6f..d18587d 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java @@ -1,7 +1,6 @@ package com.github.gribanoveu.cuddly.entities.services.email; -import com.github.gribanoveu.cuddly.controllers.dtos.data.AbstractEmailContext; -import jakarta.mail.MessagingException; +import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; /** * @author Evgeny Gribanov @@ -9,5 +8,5 @@ */ public interface EmailService { void sendEmail(String toEmail, String subject, String message); - void sendMail(AbstractEmailContext email); + void sendMail(SimpleEmailObject email); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java index 65409aa..38a073c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddly.entities.services.email; -import com.github.gribanoveu.cuddly.controllers.dtos.data.AbstractEmailContext; +import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import jakarta.mail.MessagingException; @@ -42,19 +42,19 @@ public void sendEmail(String toEmail, String subject, String message) { } @Override - public void sendMail(AbstractEmailContext email) { + public void sendMail(SimpleEmailObject email) { try { var message = mailSender.createMimeMessage(); var mimeMessageHelper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name()); var context = new Context(); - context.setVariables(email.getContext()); - var emailContent = templateEngine.process(email.getTemplateLocation(), context); + context.setVariables(email.context()); + var emailContent = templateEngine.process(email.templateLocation(), context); - mimeMessageHelper.setTo(email.getTo()); - mimeMessageHelper.setSubject(email.getSubject()); - mimeMessageHelper.setFrom(email.getFrom()); + mimeMessageHelper.setTo(email.to()); + mimeMessageHelper.setSubject(email.subject()); + mimeMessageHelper.setFrom(email.from()); mimeMessageHelper.setText(emailContent, true); mailSender.send(message); diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java b/src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java new file mode 100644 index 0000000..c5efa78 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java @@ -0,0 +1,40 @@ +package com.github.gribanoveu.cuddly.utils.emails; + +import com.github.gribanoveu.cuddly.constants.EmailMessages; +import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.Map; + +/** + * @author Evgeny Gribanov + * @version 28.11.2023 + */ +public abstract class RestorePasswordEmailTemplates { + public static SimpleEmailObject generateOtpEmail(String sendToEmail, String otpCode, Duration otpCodeLifeTime) { + return new SimpleEmailObject( + EmailMessages.sendFrom, + sendToEmail, + EmailMessages.restorePasswordEmailSubject, + EmailMessages.restorePasswordTemplateName, + Map.of( + "otpCode", otpCode, + "otpCodeLifetime", otpCodeLifeTime.toMinutes(), + "email", sendToEmail + ) + ); + } + + public static SimpleEmailObject passwordChangedEmail(String sendToEmail) { + return new SimpleEmailObject( + EmailMessages.sendFrom, + sendToEmail, + EmailMessages.passwordChangedEmailSubject, + EmailMessages.passwordChangedTemplateName, + Map.of( + "email", sendToEmail + ) + ); + } +} diff --git a/src/main/resources/template/otp-code-template.html b/src/main/resources/template/otp-code-template.html index 3a7894f..40c73bd 100644 --- a/src/main/resources/template/otp-code-template.html +++ b/src/main/resources/template/otp-code-template.html @@ -5,65 +5,80 @@ xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" > - - OTP Code - - - - - - - - - - - -
-
-
Здравствуйте!
-
 
-
Для вашего аккаунта запрошено восстановление пароля.
-
- Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо. -
-
-
- Чтобы продолжить процедуру восстановления пароля, введите следующий код: -
-
-

123456

-
-
-
-
Детали входа:
-
-
-
 
-
- Внимание! Отвечать на это письмо не нужно, оно создано автоматически. -
-
По всем вопросам обращайтесь в support@cuddly.pw
-
---
-
С уважением, администрация Cuddle
-
-
-
 
-
2023 © Codecow.pw
- + + OTP Code + + + + + + + + + + + + + + +
+
+ +
+
+
+

Запрошена смена пароля

+
 
+
Для вашего аккаунта запрошено восстановление пароля.
+
+ Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо, тогда + ничего не изменится. +
+
 
+
+ Чтобы продолжить процедуру восстановления пароля, введите следующий код: +
+
+

000 000

+
+
+
 
+
Детали запроса:
+
+
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно создано автоматически. +
+
По всем вопросам обращайтесь в support@cuddly.pw
+
---
+
С уважением, администрация Cuddle
+
+
+
 
+
+
+ + + \ No newline at end of file diff --git a/src/main/resources/template/password-changed.html b/src/main/resources/template/password-changed.html new file mode 100644 index 0000000..f29188c --- /dev/null +++ b/src/main/resources/template/password-changed.html @@ -0,0 +1,74 @@ + + + + OTP Code + + + + + + + + + + + + + + +
+
+ +
+
+
+

Пароль изменен

+
 
+
Пароль на вашем аккаунте успешно изменен.
+
+ Если это сделали не вы, проверьте безопасность своего аккаунта или обратитесь в службу поддержки. +
+
 
+
Детали запроса:
+
+
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно создано автоматически. +
+
По всем вопросам обращайтесь в support@cuddly.pw
+
---
+
С уважением, администрация Cuddle
+
+
+
 
+
+
+ + + \ No newline at end of file From b4738ffb9959d2fc811b43b3ab753aed4ef91375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sat, 2 Dec 2023 17:47:18 +0300 Subject: [PATCH 15/34] serts gen instruction added --- .../com/github/gribanoveu/cuddly/utils/RSAEncryption.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java b/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java index 0869670..c35be50 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java @@ -12,6 +12,11 @@ /** * @author Evgeny Gribanov * @version 24.10.2023 + * For gen serts: + * openssl genrsa -out keypair.pem 2048 + * openssl rsa -in keypair.pem -pubout -out public.pem + * openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in keypair.pem -out private.pem + * place serts in resources/certs */ @Component @RequiredArgsConstructor From 00495301a4f03a2c0481514038069fff7f8f1ad2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sat, 2 Dec 2023 18:18:49 +0300 Subject: [PATCH 16/34] fix template --- .../cuddly/config/ThymeleafConfig.java | 6 +- .../resources/template/otp-code-template.html | 84 ------------------- .../resources/template/password-changed.html | 74 ---------------- .../templates/otp-code-template.html | 83 ++++++++++++++++++ .../resources/templates/password-changed.html | 73 ++++++++++++++++ 5 files changed, 158 insertions(+), 162 deletions(-) delete mode 100644 src/main/resources/template/otp-code-template.html delete mode 100644 src/main/resources/template/password-changed.html create mode 100644 src/main/resources/templates/otp-code-template.html create mode 100644 src/main/resources/templates/password-changed.html diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java index be2fc05..e7bc1dc 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java @@ -1,9 +1,7 @@ package com.github.gribanoveu.cuddly.config; -import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; import org.springframework.web.servlet.ViewResolver; import org.thymeleaf.spring6.SpringTemplateEngine; import org.thymeleaf.spring6.view.ThymeleafViewResolver; @@ -19,10 +17,10 @@ public class ThymeleafConfig { @Bean public ClassLoaderTemplateResolver templateResolver() { var templateResolver = new ClassLoaderTemplateResolver(); - templateResolver.setPrefix("template/"); + templateResolver.setPrefix("templates/"); templateResolver.setCacheable(false); templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); + templateResolver.setTemplateMode("HTML"); templateResolver.setCharacterEncoding("UTF-8"); return templateResolver; } diff --git a/src/main/resources/template/otp-code-template.html b/src/main/resources/template/otp-code-template.html deleted file mode 100644 index 40c73bd..0000000 --- a/src/main/resources/template/otp-code-template.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - OTP Code - - - - - - - - - - - - - - -
-
- -
-
-
-

Запрошена смена пароля

-
 
-
Для вашего аккаунта запрошено восстановление пароля.
-
- Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо, тогда - ничего не изменится. -
-
 
-
- Чтобы продолжить процедуру восстановления пароля, введите следующий код: -
-
-

000 000

-
-
-
 
-
Детали запроса:
-
-
-
 
-
- Внимание! Отвечать на это письмо не нужно, оно создано автоматически. -
-
По всем вопросам обращайтесь в support@cuddly.pw
-
---
-
С уважением, администрация Cuddle
-
-
-
 
-
-
- - - \ No newline at end of file diff --git a/src/main/resources/template/password-changed.html b/src/main/resources/template/password-changed.html deleted file mode 100644 index f29188c..0000000 --- a/src/main/resources/template/password-changed.html +++ /dev/null @@ -1,74 +0,0 @@ - - - - OTP Code - - - - - - - - - - - - - - -
-
- -
-
-
-

Пароль изменен

-
 
-
Пароль на вашем аккаунте успешно изменен.
-
- Если это сделали не вы, проверьте безопасность своего аккаунта или обратитесь в службу поддержки. -
-
 
-
Детали запроса:
-
-
-
 
-
- Внимание! Отвечать на это письмо не нужно, оно создано автоматически. -
-
По всем вопросам обращайтесь в support@cuddly.pw
-
---
-
С уважением, администрация Cuddle
-
-
-
 
-
-
- - - \ No newline at end of file diff --git a/src/main/resources/templates/otp-code-template.html b/src/main/resources/templates/otp-code-template.html new file mode 100644 index 0000000..fe7e30c --- /dev/null +++ b/src/main/resources/templates/otp-code-template.html @@ -0,0 +1,83 @@ + + + + OTP Code + + + + + + + + + + + + + + +
+
+ +
+
+
+

Запрошена смена пароля

+
 
+
Для вашего аккаунта запрошено восстановление пароля.
+
+ Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо, тогда + ничего не изменится. +
+
 
+
+ Чтобы продолжить процедуру восстановления пароля, введите следующий код: +
+
+

000 000

+
+
+
 
+
Детали запроса:
+
+
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно создано автоматически. +
+
По всем вопросам обращайтесь в support@cuddly.pw
+
---
+
С уважением, администрация Cuddle
+
+
+
 
+
+
+ + + \ No newline at end of file diff --git a/src/main/resources/templates/password-changed.html b/src/main/resources/templates/password-changed.html new file mode 100644 index 0000000..e2c5b9d --- /dev/null +++ b/src/main/resources/templates/password-changed.html @@ -0,0 +1,73 @@ + + + + OTP Code + + + + + + + + + + + + + + +
+
+ +
+
+
+

Пароль изменен

+
 
+
Пароль на вашем аккаунте успешно изменен.
+
+ Если это сделали не вы, проверьте безопасность своего аккаунта или обратитесь в службу поддержки. +
+
 
+
Детали запроса:
+
+
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно создано автоматически. +
+
По всем вопросам обращайтесь в support@cuddly.pw
+
---
+
С уважением, администрация Cuddle
+
+
+
 
+
+
+ + + \ No newline at end of file From 40fbbbe101c18bad5865c1709943f639e939ba6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sat, 2 Dec 2023 18:24:26 +0300 Subject: [PATCH 17/34] fix template --- src/main/resources/templates/otp-code-template.html | 8 +++++--- src/main/resources/templates/password-changed.html | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/resources/templates/otp-code-template.html b/src/main/resources/templates/otp-code-template.html index fe7e30c..2d3a570 100644 --- a/src/main/resources/templates/otp-code-template.html +++ b/src/main/resources/templates/otp-code-template.html @@ -16,7 +16,6 @@ padding-top: 5px; line-height: 130%; } - .tableStyle { width: 600px; border-collapse: collapse; @@ -24,7 +23,10 @@ margin-left: auto; margin-right: auto; font-family: Arial, sans-serif; - + } + .logoStyle { + padding-top: 5px; + padding-left: 10px } @@ -32,7 +34,7 @@ -
+
diff --git a/src/main/resources/templates/password-changed.html b/src/main/resources/templates/password-changed.html index e2c5b9d..4edd6d6 100644 --- a/src/main/resources/templates/password-changed.html +++ b/src/main/resources/templates/password-changed.html @@ -16,7 +16,6 @@ padding-top: 5px; line-height: 130%; } - .tableStyle { width: 600px; border-collapse: collapse; @@ -24,7 +23,10 @@ margin-left: auto; margin-right: auto; font-family: Arial, sans-serif; - + } + .logoStyle { + padding-top: 5px; + padding-left: 10px } @@ -32,7 +34,7 @@ -
+
From 0a60f87bd92bdc2951f7e5578f335c9002158b70 Mon Sep 17 00:00:00 2001 From: Evgeny Gribanov Date: Sun, 3 Dec 2023 19:20:31 +0300 Subject: [PATCH 18/34] Create successfull-registration.html --- .../templates/successfull-registration.html | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/main/resources/templates/successfull-registration.html diff --git a/src/main/resources/templates/successfull-registration.html b/src/main/resources/templates/successfull-registration.html new file mode 100644 index 0000000..0b12805 --- /dev/null +++ b/src/main/resources/templates/successfull-registration.html @@ -0,0 +1,111 @@ + + + + OTP Code + + + + + + + + + + + + + + +
+
+ +
+
+
+

Успешная регистрация

+
 
+
+ Добро пожаловать, мы рады вас видеть в нашем + приложении. +
+
+ Чтобы полноценно стать частью нашего сообщества, + выполните вход в свою учетную запись и заполните + профиль. +
+
 
+

Внимание!

+

+ Продолжая регистрацию, вы подтверждаете, что вам + исполнилось 18 лет и понимаете, какая информация + представленная в приложении. В случае, если + данная информация способна вывести вас из + состояния душевного равновесия, вам необходимо + покинуть данный ресурс. +

+
+ Перед тем, как начать пользоваться приложением, + пожалуйста, прочтите нашу + политику конфиденциальности + и + условия использования. +
 
+ А так же ознакомтесь с нашими + правилами сообщества, в нем вам будет рассказано, какую информацию + о себе вы можете публиковать. +
+
 
+
Детали запроса:
+
+
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно + создано автоматически. +
+
+ По всем вопросам обращайтесь в support@cuddly.pw +
+
---
+
С уважением, администрация Cuddle
+
+
+
 
+
+ + From f119ec13204e4ecb05a665bd276918e7000adb97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 18 Dec 2023 18:08:24 +0300 Subject: [PATCH 19/34] refactor emails Took 4 hours 5 minutes --- .../cuddly/constants/EmailMessages.java | 16 ++- .../facade/auth/AccountControllerFacade.java | 34 +++--- .../facade/auth/AuthControllerFacade.java | 6 + .../facade/auth/UserControllerFacade.java | 13 +- ...mailTemplates.java => EmailTemplates.java} | 25 ++-- .../resources/templates/email-changed.html | 60 ++++++++++ .../resources/templates/fragment/about.html | 14 +++ .../resources/templates/fragment/footer.html | 9 ++ .../resources/templates/fragment/logo.html | 8 ++ .../templates/otp-code-template.html | 95 +++++++-------- .../resources/templates/password-changed.html | 73 +++++------- .../templates/successfull-registration.html | 111 ------------------ .../templates/successfully-login.html | 61 ++++++++++ .../templates/successfully-registration.html | 72 ++++++++++++ .../resources/templates/user-deleted.html | 71 +++++++++++ 15 files changed, 426 insertions(+), 242 deletions(-) rename src/main/java/com/github/gribanoveu/cuddly/utils/emails/{RestorePasswordEmailTemplates.java => EmailTemplates.java} (51%) create mode 100644 src/main/resources/templates/email-changed.html create mode 100644 src/main/resources/templates/fragment/about.html create mode 100644 src/main/resources/templates/fragment/footer.html create mode 100644 src/main/resources/templates/fragment/logo.html delete mode 100644 src/main/resources/templates/successfull-registration.html create mode 100644 src/main/resources/templates/successfully-login.html create mode 100644 src/main/resources/templates/successfully-registration.html create mode 100644 src/main/resources/templates/user-deleted.html diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java b/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java index 22fdbd0..f47d7a3 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java @@ -6,10 +6,18 @@ */ public class EmailMessages { public static final String sendFrom = "noreply@codecow.pw"; - public static final String restorePasswordEmailSubject = "Восстановление пароля"; - public static final String restorePasswordTemplateName = "otp-code-template"; + public static final String restorePasswordSubject = "Восстановление пароля"; + public static final String restorePasswordTemplate = "otp-code-template"; - public static final String passwordChangedEmailSubject = "Пароль успешно изменен"; - public static final String passwordChangedTemplateName = "password-changed"; + public static final String passwordChangedSubject = "Пароль успешно изменен"; + public static final String passwordChangedTemplate = "password-changed"; + public static final String userRegisteredSubject = "Успешная регистрация"; + public static final String userRegisteredTemplate = "successfully-registration"; + + public static final String loginSubject = "В ваш аккаунт выполнен вход"; + public static final String loginTemplate = "successfully-login"; + + public static final String changeEmailSubject = "Электронная почта изменена"; + public static final String changeEmailTemplate = "email-changed"; } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java index a7748d7..4694c06 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; +import com.github.gribanoveu.cuddly.constants.EmailMessages; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; @@ -12,19 +13,15 @@ import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; import com.github.gribanoveu.cuddly.entities.services.user.UserService; import com.github.gribanoveu.cuddly.utils.JsonUtils; -import com.github.gribanoveu.cuddly.utils.emails.RestorePasswordEmailTemplates; +import com.github.gribanoveu.cuddly.utils.emails.EmailTemplates; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Service; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; import java.time.Duration; @@ -45,11 +42,14 @@ public class AccountControllerFacade { private final JsonUtils jsonUtils; // user change email from app, authenticated - public ResponseEntity changeEmail(ChangeEmailDto request, Authentication authentication) { - var user = userService.findUserByEmail(authentication.getName()); - userService.updateEmail(user, request.email()); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UPDATED, StatusLevel.SUCCESS)); - } + public ResponseEntity changeEmail(ChangeEmailDto request, Authentication authentication) { + var user = userService.findUserByEmail(authentication.getName()); + var oldEmail = user.getEmail(); + userService.updateEmail(user, request.email()); + emailService.sendMail(EmailTemplates.emailChanged(oldEmail, request.email())); + log.info("Email change old email: {}, new email: {}", oldEmail, request.email()); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UPDATED, StatusLevel.SUCCESS)); + } // check that password and confirm password match // find user, if not exist -> error @@ -63,6 +63,11 @@ public ResponseEntity changePassword(ChangePasswordDto request, if (passwordEncoder.matches(request.oldPassword(), user.getPassword())) if (!passwordEncoder.matches(request.password(), user.getPassword())) { userService.updatePasswordByEmail(user, passwordEncoder.encode(request.password())); + + emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(), + EmailMessages.passwordChangedSubject, EmailMessages.passwordChangedTemplate)); + log.info("Password change message sent to: {}", user.getEmail()); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.PASSWORD_UPDATED, StatusLevel.SUCCESS)); } else throw new CredentialEx(ResponseCode.PASSWORD_EQUALS); @@ -81,12 +86,12 @@ public ResponseEntity generateOtpCode(GenerateOtpDto request, Ht var otpCode = jsonUtils.generateRandomOtpCode().toString(); log.info("RequestId: {}. Generate OTP code. Email {}, Code {}", http.getRequestId(), request.email(), otpCode); - emailService.sendMail(RestorePasswordEmailTemplates.generateOtpEmail(request.email(), otpCode, otpCodeLifeTime)); - log.info("RequestId: {}. Email with code send to: {}", http.getRequestId(), request.email()); - redisOtpService.saveOptCode(request.email(), otpCode, otpCodeLifeTime); log.info("RequestId: {}. OTP code to email: {} saved", http.getRequestId(), request.email()); + emailService.sendMail(EmailTemplates.generateOtpEmail(request.email(), otpCode, otpCodeLifeTime)); + log.info("RequestId: {}. Email with code send to: {}", http.getRequestId(), request.email()); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.OTP_CODE_CREATED, StatusLevel.SUCCESS)); } @@ -102,7 +107,8 @@ public ResponseEntity restorePasswordByOtp(RestorePasswordDto re if (!passwordEncoder.matches(request.password(), user.getPassword())) { userService.updatePasswordByEmail(user, passwordEncoder.encode(request.password())); redisOtpService.deleteOtpCode(request.email()); - emailService.sendMail(RestorePasswordEmailTemplates.passwordChangedEmail(request.email())); + emailService.sendMail(EmailTemplates.simpleEmail(request.email(), + EmailMessages.passwordChangedSubject, EmailMessages.passwordChangedTemplate)); log.info("Password change message sent to: {}", request.email()); return ResponseEntity.ok(StatusResponse.create(ResponseCode.PASSWORD_UPDATED, StatusLevel.SUCCESS)); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java index 07805a5..01319b2 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; +import com.github.gribanoveu.cuddly.constants.EmailMessages; import com.github.gribanoveu.cuddly.constants.RegexpFormat; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; @@ -7,12 +8,14 @@ import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.TokenType; +import com.github.gribanoveu.cuddly.entities.services.email.EmailService; import com.github.gribanoveu.cuddly.entities.services.token.TokenService; import com.github.gribanoveu.cuddly.security.CustomUserDetails; import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import com.github.gribanoveu.cuddly.utils.RSAEncryption; import com.github.gribanoveu.cuddly.config.RsaProperties; import com.github.gribanoveu.cuddly.utils.RefreshTokenUtils; +import com.github.gribanoveu.cuddly.utils.emails.EmailTemplates; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -42,6 +45,7 @@ public class AuthControllerFacade { private final AuthenticationManager authManager; private final CustomUserDetailsService usrDetailsService; private final RefreshTokenUtils refreshTokenUtils; + private final EmailService emailService; public ResponseEntity authenticateUser(LoginDto request) { var authenticationToken = new UsernamePasswordAuthenticationToken(request.email(), request.password()); @@ -49,6 +53,8 @@ public ResponseEntity authenticateUser(LoginDto request) { var user = (CustomUserDetails) auth.getPrincipal(); var accessToken = tokenService.generateToken(user, TokenType.ACCESS); var encryptedRefreshToken = refreshTokenUtils.generateEncryptedRefreshToken(request.email()); + emailService.sendMail(EmailTemplates.simpleEmail(request.email(), + EmailMessages.loginSubject, EmailMessages.loginTemplate)); return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, encryptedRefreshToken)); // encrypted token so that it is not used as a main token diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java index 4b75738..c9b94d8 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java @@ -1,14 +1,18 @@ package com.github.gribanoveu.cuddly.controllers.facade.auth; +import com.github.gribanoveu.cuddly.constants.EmailMessages; import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RegisterDto; import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; import com.github.gribanoveu.cuddly.entities.enums.Role; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddly.entities.services.email.EmailService; import com.github.gribanoveu.cuddly.entities.services.user.UserService; import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddly.utils.emails.EmailTemplates; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; @@ -16,19 +20,19 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.time.LocalDate; -import java.time.Month; import java.time.format.DateTimeFormatter; -import java.util.Set; /** * @author Evgeny Gribanov * @version 29.08.2023 */ +@Slf4j @Service @RequiredArgsConstructor public class UserControllerFacade { private final UserService userService; private final PasswordEncoder passwordEncoder; + private final EmailService emailService; public ResponseEntity getUserData(Authentication authentication) { var userData = userService.findUserByEmail(authentication.getName()); @@ -45,11 +49,16 @@ public ResponseEntity registerUser(RegisterDto request) { user.setPassword(passwordEncoder.encode(request.password())); user.setRole(Role.USER); userService.saveUser(user); + log.info("User saved: {}", user.getEmail()); var location = ServletUriComponentsBuilder .fromCurrentContextPath().path("/v1/user/{id}") .buildAndExpand(user.getId()).toUri(); + emailService.sendMail(EmailTemplates.simpleEmail(request.email(), + EmailMessages.userRegisteredSubject, EmailMessages.userRegisteredTemplate)); + log.info("Register confirm send to email: {}", request.email()); + return ResponseEntity.created (location).body(StatusResponse.create( ResponseCode.USER_CREATED, StatusLevel.SUCCESS)); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java b/src/main/java/com/github/gribanoveu/cuddly/utils/emails/EmailTemplates.java similarity index 51% rename from src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java rename to src/main/java/com/github/gribanoveu/cuddly/utils/emails/EmailTemplates.java index c5efa78..c145fbd 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/emails/RestorePasswordEmailTemplates.java +++ b/src/main/java/com/github/gribanoveu/cuddly/utils/emails/EmailTemplates.java @@ -4,20 +4,19 @@ import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; import java.time.Duration; -import java.time.LocalDateTime; import java.util.Map; /** * @author Evgeny Gribanov * @version 28.11.2023 */ -public abstract class RestorePasswordEmailTemplates { +public abstract class EmailTemplates { public static SimpleEmailObject generateOtpEmail(String sendToEmail, String otpCode, Duration otpCodeLifeTime) { return new SimpleEmailObject( EmailMessages.sendFrom, sendToEmail, - EmailMessages.restorePasswordEmailSubject, - EmailMessages.restorePasswordTemplateName, + EmailMessages.restorePasswordSubject, + EmailMessages.restorePasswordTemplate, Map.of( "otpCode", otpCode, "otpCodeLifetime", otpCodeLifeTime.toMinutes(), @@ -26,14 +25,18 @@ public static SimpleEmailObject generateOtpEmail(String sendToEmail, String otpC ); } - public static SimpleEmailObject passwordChangedEmail(String sendToEmail) { - return new SimpleEmailObject( - EmailMessages.sendFrom, - sendToEmail, - EmailMessages.passwordChangedEmailSubject, - EmailMessages.passwordChangedTemplateName, + public static SimpleEmailObject simpleEmail(String sendToEmail, String subject, String templateName) { + return new SimpleEmailObject(EmailMessages.sendFrom,sendToEmail,subject,templateName, + Map.of("email", sendToEmail) + ); + } + + public static SimpleEmailObject emailChanged(String oldEmail, String newEmail) { + return new SimpleEmailObject(EmailMessages.sendFrom, oldEmail, EmailMessages.changeEmailSubject, + EmailMessages.changeEmailTemplate, Map.of( - "email", sendToEmail + "oldEmail", oldEmail, + "newEmail", newEmail ) ); } diff --git a/src/main/resources/templates/email-changed.html b/src/main/resources/templates/email-changed.html new file mode 100644 index 0000000..8a238d5 --- /dev/null +++ b/src/main/resources/templates/email-changed.html @@ -0,0 +1,60 @@ + + + + Электронная почта изменена + + + + + + + + + + + + + + +
+
+

Электронная почта изменена

+
 
+
Электронная почта на вашем аккаунте успешно изменена.
+
+ Если это были вы, то нет причин для беспокойства, но если это не так, то проверьте безопасность своего аккаунта или обратитесь в службу поддержки. + Для последующего входа в свой аккаунт используйте новый адрес электронной почты. +
+
 
+
Детали запроса:
+
+
+
+
+
+
+
 
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/fragment/about.html b/src/main/resources/templates/fragment/about.html new file mode 100644 index 0000000..cac399b --- /dev/null +++ b/src/main/resources/templates/fragment/about.html @@ -0,0 +1,14 @@ + + + +
+
 
+
+ Внимание! Отвечать на это письмо не нужно, оно создано автоматически. +
+
По всем вопросам обращайтесь в support@cuddly.pw
+
---
+
С уважением, администрация Cuddle
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/fragment/footer.html b/src/main/resources/templates/fragment/footer.html new file mode 100644 index 0000000..1d556ef --- /dev/null +++ b/src/main/resources/templates/fragment/footer.html @@ -0,0 +1,9 @@ + + + +
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/fragment/logo.html b/src/main/resources/templates/fragment/logo.html new file mode 100644 index 0000000..7f0debe --- /dev/null +++ b/src/main/resources/templates/fragment/logo.html @@ -0,0 +1,8 @@ + + + +
+ +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/otp-code-template.html b/src/main/resources/templates/otp-code-template.html index 2d3a570..460a45d 100644 --- a/src/main/resources/templates/otp-code-template.html +++ b/src/main/resources/templates/otp-code-template.html @@ -1,10 +1,7 @@ - + - OTP Code + Запрошена смена пароля - - - - - - - - - -
-
- -
-
-
-

Запрошена смена пароля

-
 
-
Для вашего аккаунта запрошено восстановление пароля.
-
- Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо, тогда - ничего не изменится. -
-
 
-
- Чтобы продолжить процедуру восстановления пароля, введите следующий код: -
-
-

000 000

-
-
-
 
-
Детали запроса:
-
-
-
 
-
- Внимание! Отвечать на это письмо не нужно, оно создано автоматически. -
-
По всем вопросам обращайтесь в support@cuddly.pw
-
---
-
С уважением, администрация Cuddle
-
-
-
 
-
-
+ + + + + + + + + +
+
+

Запрошена смена пароля

+
 
+
+ Для вашего аккаунта запрошено восстановление пароля. +
+
+ Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо, тогда ничего не изменится. + Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать разные пароли для электронной почты и на данном аккаунте. +
+
 
+
+ Чтобы продолжить процедуру восстановления пароля, введите следующий код: +
+
+

000 000

+
+
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
- \ No newline at end of file diff --git a/src/main/resources/templates/password-changed.html b/src/main/resources/templates/password-changed.html index 4edd6d6..95a5ed2 100644 --- a/src/main/resources/templates/password-changed.html +++ b/src/main/resources/templates/password-changed.html @@ -1,10 +1,7 @@ - + - OTP Code + Пароль изменен - - - - - - - - - -
-
- -
-
-
-

Пароль изменен

-
 
-
Пароль на вашем аккаунте успешно изменен.
-
- Если это сделали не вы, проверьте безопасность своего аккаунта или обратитесь в службу поддержки. -
-
 
-
Детали запроса:
-
-
-
 
-
- Внимание! Отвечать на это письмо не нужно, оно создано автоматически. -
-
По всем вопросам обращайтесь в support@cuddly.pw
-
---
-
С уважением, администрация Cuddle
-
-
-
 
-
-
+ + + + + + + + + +
+
+

Пароль изменен

+
 
+
Пароль на вашем аккаунте успешно изменен.
+
+ Если это были вы, то нет причин для беспокойства, но если это не так, то проверьте безопасность своего аккаунта или обратитесь в службу поддержки. +
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
- \ No newline at end of file diff --git a/src/main/resources/templates/successfull-registration.html b/src/main/resources/templates/successfull-registration.html deleted file mode 100644 index 0b12805..0000000 --- a/src/main/resources/templates/successfull-registration.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - OTP Code - - - - - - - - - - - - - - -
-
- -
-
-
-

Успешная регистрация

-
 
-
- Добро пожаловать, мы рады вас видеть в нашем - приложении. -
-
- Чтобы полноценно стать частью нашего сообщества, - выполните вход в свою учетную запись и заполните - профиль. -
-
 
-

Внимание!

-

- Продолжая регистрацию, вы подтверждаете, что вам - исполнилось 18 лет и понимаете, какая информация - представленная в приложении. В случае, если - данная информация способна вывести вас из - состояния душевного равновесия, вам необходимо - покинуть данный ресурс. -

-
- Перед тем, как начать пользоваться приложением, - пожалуйста, прочтите нашу - политику конфиденциальности - и - условия использования. -
 
- А так же ознакомтесь с нашими - правилами сообщества, в нем вам будет рассказано, какую информацию - о себе вы можете публиковать. -
-
 
-
Детали запроса:
-
-
-
 
-
- Внимание! Отвечать на это письмо не нужно, оно - создано автоматически. -
-
- По всем вопросам обращайтесь в support@cuddly.pw -
-
---
-
С уважением, администрация Cuddle
-
-
-
 
-
- - diff --git a/src/main/resources/templates/successfully-login.html b/src/main/resources/templates/successfully-login.html new file mode 100644 index 0000000..034f7ff --- /dev/null +++ b/src/main/resources/templates/successfully-login.html @@ -0,0 +1,61 @@ + + + + В ваш аккаунт выполнен вход + + + + + + + + + + + + + + +
+
+

В ваш аккаунт выполнен вход

+
 
+
+ Недавно кто-то вошел в ваш аккаунт. +
+
 
+
+ Если это были вы, то нет причин для беспокойства, но если это не так, то мы рекомендуем сменить пароль. +
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + diff --git a/src/main/resources/templates/successfully-registration.html b/src/main/resources/templates/successfully-registration.html new file mode 100644 index 0000000..99cc714 --- /dev/null +++ b/src/main/resources/templates/successfully-registration.html @@ -0,0 +1,72 @@ + + + + Успешная регистрация + + + + + + + + + + + + + + +
+
+

Успешная регистрация

+
 
+
+ Добро пожаловать, мы рады вас видеть в нашем приложении. +
+
+ Вы почти стали полноправным пользователем нашего приложения для знакомств! 🎉 + Для продолжения, войдите в свою учётную запись и заполните профиль. +
+
 
+

Внимание!

+

+ Продолжая регистрацию, вы подтверждаете своё совершеннолетие (18+) и осознаёте, какую информацию вы публикуете на нашем ресурсе. Если представленная информация в приложении способна вывести вас из состояния душевного равновесия, не продолжайте регистрацию и не используйте приложение! +

+
+ Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования. +
 
+ А так же ознакомьтесь с нашими правилами сообщества, в них вам будет рассказано, какую информацию о себе вы можете публиковать не нарушая правила. + Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать разные пароли для электронной почты и для ваших учетных записей. +
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + diff --git a/src/main/resources/templates/user-deleted.html b/src/main/resources/templates/user-deleted.html new file mode 100644 index 0000000..937b698 --- /dev/null +++ b/src/main/resources/templates/user-deleted.html @@ -0,0 +1,71 @@ + + + + Ваш аккаунт удален + + + + + + + + + + + + + + +
+
+

Ваш аккаунт удален

+
 
+
Мы сожалеем, что вы решили удалить свой аккаунт из нашего сервиса.
+
+ Напоминаем, что удаление аккаунта это безвозвратная операция и восстановить ваши данные не получится. +
+
 
+
+

Следующие функции и данные были удалены в соответствии с вашей учетной записью:

+
    +
  • Ваш профиль и все связанные с ним данные, включая фотографии и контактную информацию.
  • +
  • Все сообщения и переписки, которые вы создали или участвовали в них.
  • +
  • Ваши настройки и предпочтения, связанные с нашим сервисом.
  • +
+
+
+ Спасибо за использование нашего сервиса. Если вы захотите вернуться, вам потребуется зарегистрироваться снова. +
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + \ No newline at end of file From 9cec24de559fe59178735e68acd5f8f9c73e56fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Mon, 18 Dec 2023 18:08:49 +0300 Subject: [PATCH 20/34] add swagger --- .fleet/run.json | 5 +++++ pom.xml | 5 +++++ .../cuddly/AuthServiceApplication.java | 19 +++++++++++++--- .../cuddly/config/SecurityConfig.java | 4 +++- .../cuddly/config/ThymeleafConfig.java | 9 +++++--- .../dtos/request/auth/ChangeEmailDto.java | 3 +++ .../dtos/request/auth/ChangePasswordDto.java | 5 +++++ .../dtos/request/auth/GenerateOtpDto.java | 3 +++ .../dtos/request/auth/LoginDto.java | 5 +++++ .../dtos/request/auth/RefreshTokenDto.java | 3 +++ .../dtos/request/auth/RegisterDto.java | 6 +++++ .../dtos/request/auth/RestorePasswordDto.java | 6 +++++ .../dtos/response/ResponseDetails.java | 7 ++++++ .../dtos/response/StatusResponse.java | 7 ++++++ .../response/auth/PermissionsResponse.java | 6 +++++ .../dtos/response/auth/TokenResponse.java | 22 +++++++++++++++---- .../dtos/response/auth/UsersResponse.java | 7 +++++- .../endpoints/admin/ModeratorController.java | 2 ++ .../endpoints/auth/AccountController.java | 11 ++++++++++ .../endpoints/auth/AuthController.java | 5 +++++ .../endpoints/auth/UserController.java | 9 ++++++++ 21 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 .fleet/run.json diff --git a/.fleet/run.json b/.fleet/run.json new file mode 100644 index 0000000..9951506 --- /dev/null +++ b/.fleet/run.json @@ -0,0 +1,5 @@ +{ + "configurations": [ + + ] +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index dcaa420..05cb7c6 100644 --- a/pom.xml +++ b/pom.xml @@ -93,6 +93,11 @@ logback-gelf 5.0.0 + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.3.0 + diff --git a/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java b/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java index 6ff9c0a..2513f9f 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java +++ b/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java @@ -1,13 +1,26 @@ package com.github.gribanoveu.cuddly; import com.github.gribanoveu.cuddly.config.RsaProperties; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.info.Contact; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.security.SecurityScheme; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; -@EnableConfigurationProperties({ - RsaProperties.class -}) +@OpenAPIDefinition(info = @Info( + title = "Spring Api", + description = "Описание Api", version = "0.1.0", + contact = @Contact( + name = "Evgeny Gribanov", + email = "egribanov@yandex.com", + url = "https://codecow.pw" + ) +)) +@SecurityScheme(name = "JWT", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer") +@EnableConfigurationProperties({RsaProperties.class}) @SpringBootApplication public class AuthServiceApplication { public static void main(String[] args) { diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java index 57c359c..0de860e 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java @@ -3,7 +3,6 @@ import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AuthErrorEntryPoint; import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.ServerErrorEntryPoint; -import com.github.gribanoveu.cuddly.entities.enums.Role; import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; @@ -53,6 +52,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .requestMatchers(HttpMethod.POST, "*/account/generate-code").anonymous() .requestMatchers(HttpMethod.POST, "*/account/restore-password").anonymous() + // anonymous scope (swagger) + .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll() + // authenticated scope .requestMatchers("*/users/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) .requestMatchers("*/moderator/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java b/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java index e7bc1dc..1ed4918 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java @@ -5,8 +5,11 @@ import org.springframework.web.servlet.ViewResolver; import org.thymeleaf.spring6.SpringTemplateEngine; import org.thymeleaf.spring6.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import java.nio.charset.StandardCharsets; + /** * @author Evgeny Gribanov * @version 28.11.2023 @@ -20,8 +23,8 @@ public ClassLoaderTemplateResolver templateResolver() { templateResolver.setPrefix("templates/"); templateResolver.setCacheable(false); templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML"); - templateResolver.setCharacterEncoding("UTF-8"); + templateResolver.setTemplateMode(TemplateMode.HTML); + templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name()); return templateResolver; } @@ -36,7 +39,7 @@ public SpringTemplateEngine templateEngine() { public ViewResolver viewResolver() { var viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setCharacterEncoding("UTF-8"); + viewResolver.setCharacterEncoding(StandardCharsets.UTF_8.name()); return viewResolver; } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java index c3ddc51..52092ea 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; @@ -11,7 +12,9 @@ * @author Evgeny Gribanov * @version 08.09.2023 */ +@Schema(description = "Сущность для смены email авторизованным пользователем") public record ChangeEmailDto( + @Schema(description = "Электронная почта", example = "user@email.com") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java index 11842db..d1bad87 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; @@ -9,15 +10,19 @@ * @author Evgeny Gribanov * @version 08.09.2023 */ +@Schema(description = "Сущность для смены пароля авторизованным пользователем") public record ChangePasswordDto( + @Schema(description = "Старый пароль", example = "Qwerty123") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String oldPassword, + @Schema(description = "Новый пароль", example = "Qwerty1234") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String password, + @Schema(description = "Повторный ввод нового пароля", example = "Qwerty1234") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String confirmPassword diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java index f9935f0..b90c296 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; @@ -11,7 +12,9 @@ * @author Evgeny Gribanov * @version 22.09.2023 */ +@Schema(description = "Сущность для генерации временного кода OTP") public record GenerateOtpDto ( + @Schema(description = "Email", example = "user@email.com") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java index b5681f3..57fd4aa 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java @@ -1,5 +1,7 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; @@ -11,12 +13,15 @@ * @author Evgeny Gribanov * @version 29.08.2023 */ +@Schema(description = "Сущность для авторизации") public record LoginDto( + @Schema(description = "Электронная почта", example = "user@email.com") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String email, + @Schema(description = "Пароль пользователя", example = "Qwerty123") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String password diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java index 1a9467c..1935221 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import static com.github.gribanoveu.cuddly.constants.ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE; @@ -8,7 +9,9 @@ * @author Evgeny Gribanov * @version 24.10.2023 */ +@Schema(description = "Сущность для получения нового access token") public record RefreshTokenDto( + @Schema(description = "Токен обновления (refresh token)") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) String refreshToken ) {} diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java index ec88ac5..b0ba219 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java @@ -1,6 +1,7 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; import com.github.gribanoveu.cuddly.utils.validators.MinimalAge; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.*; import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; @@ -10,19 +11,24 @@ * @author Evgeny Gribanov * @version 29.08.2023 */ +@Schema(description = "Сущность для регистрации нового пользователя") public record RegisterDto( + @Schema(description = "Электронная почта", example = "user@email.com") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String email, + @Schema(description = "Дата рождения", example = "2001-12-13") @MinimalAge(message = MINIMAL_AGE_EXCEPTION_MESSAGE) String birthDate, // todo write tests + @Schema(description = "Пароль") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String password, + @Schema(description = "Пароль повторно") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String confirmPassword diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java index 250b2ba..00ca2c7 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; @@ -12,20 +13,25 @@ * @author Evgeny Gribanov * @version 22.09.2023 */ +@Schema(description = "Сущность для восстановления пароля") public record RestorePasswordDto( + @Schema(description = "Электронная почта", example = "user@email.com") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) String email, + @Schema(description = "Временный код подтверждения OTP") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Pattern(regexp = OTP_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) String otpCode, + @Schema(description = "Пароль") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String password, + @Schema(description = "Пароль повторно") @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) @Size(max = 80, message = SIZE_EXCEPTION_MESSAGE) String confirmPassword diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java index 7f07054..7d9b832 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java @@ -2,15 +2,22 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) +@Schema(description = "Сущность для описания деталей операции") public class ResponseDetails { + @Schema(description = "Тип операции") private String type; + + @Schema(description = "Код операции") private String code; + + @Schema(description = "Подробное описание операции") private String message; public ResponseDetails(ResponseCode responseCode) { diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java index d3fd42b..bec85a6 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; @@ -18,10 +19,16 @@ @Data @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) +@Schema(description = "Сущность для возврата статуса операции") public class StatusResponse { @JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Europe/Moscow") + @Schema(description = "Время выполнения запроса") private LocalDateTime timestamp; + + @Schema(description = "Уровень статуса запроса", defaultValue = "INFO") private StatusLevel status; + + @Schema(description = "Детали запроса") private Collection details; public static StatusResponse create(Collection responseDetails, StatusLevel status) { diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java index 25cfb62..443c215 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.github.gribanoveu.cuddly.entities.enums.Role; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; @@ -19,9 +20,14 @@ @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class PermissionsResponse { + @Schema(description = "Время выполнения запроса") @JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Europe/Moscow") private LocalDateTime timestamp; + + @Schema(description = "Уровень статуса запроса", defaultValue = "INFO") private StatusLevel status; + + @Schema(description = "Информация о ролях пользователя") private Collection permissions; public static PermissionsResponse create(HttpStatus status, Collection permissions) { diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java index 12d5485..66c3e03 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; @@ -17,11 +18,24 @@ @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class TokenResponse { + @Schema(description = "Время выполнения запроса") private LocalDateTime timestamp; - @JsonProperty("access_token") private String accessToken; - @JsonProperty("token_type") private String type; - @JsonProperty("expires_in") private Long accessLifetimeMin; - @JsonProperty("refresh_token") private String refreshToken; + + @Schema(description = "Токен доступа") + @JsonProperty("access_token") + private String accessToken; + + @Schema(description = "Тип токена", defaultValue = "Bearer") + @JsonProperty("token_type") + private String type; + + @Schema(description = "Время жизни токена в секундах", defaultValue = "900") + @JsonProperty("expires_in") + private Long accessLifetimeMin; + + @Schema(description = "Токен для обновления") + @JsonProperty("refresh_token") + private String refreshToken; public static TokenResponse create( Long accessTokenLifetime, diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java index 0cdb474..9f2c13f 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java @@ -7,7 +7,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; - +import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; import java.util.Collection; @@ -20,8 +20,13 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class UsersResponse { @JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Europe/Moscow") + @Schema(description = "Время выполнения запроса") private LocalDateTime timestamp; + + @Schema(description = "Уровень статуса запроса", defaultValue = "INFO") private StatusLevel status; + + @Schema(description = "Информация о пользователе") private Collection users; public static UsersResponse create(HttpStatus status, Collection users) { diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java index a2fdbea..d387b6b 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java @@ -1,6 +1,7 @@ package com.github.gribanoveu.cuddly.controllers.endpoints.admin; import com.github.gribanoveu.cuddly.controllers.facade.admin.ModeratorControllerFacade; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -12,6 +13,7 @@ @RestController @RequiredArgsConstructor @RequestMapping("/v1/moderator") +@Tag(name="Контороллер для модерации", description="Управляет ограничениями пользователя") public class ModeratorController { private final ModeratorControllerFacade moderatorControllerFacade; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java index d0a59b8..71141fe 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java @@ -8,6 +8,10 @@ import com.github.gribanoveu.cuddly.controllers.facade.auth.AccountControllerFacade; import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -22,17 +26,22 @@ @RestController @RequiredArgsConstructor @RequestMapping("/v1/account") +@Tag(name="Управление аккаунтом", description="Позволяет управлять данными учетной записи") public class AccountController { private final AccountControllerFacade userControllerFacade; @LogRequest @LogResponse @PatchMapping("/change-email") + @Operation(summary = "Сменить Email") + @SecurityRequirement(name = "JWT") public ResponseEntity changeEmail(@Valid @RequestBody ChangeEmailDto request, Authentication auth) { return userControllerFacade.changeEmail(request, auth); } @PatchMapping("/change-password") + @Operation(summary = "Сменить пароль") + @SecurityRequirement(name = "JWT") public ResponseEntity changePassword(@Valid @RequestBody ChangePasswordDto request, Authentication auth) { return userControllerFacade.changePassword(request, auth); } @@ -40,11 +49,13 @@ public ResponseEntity changePassword(@Valid @RequestBody ChangeP @LogRequest @LogResponse @PostMapping("/generate-code") // anonymous access + @Operation(summary = "Сгенерировать OTP код") public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request, HttpServletRequest http) { return userControllerFacade.generateOtpCode(request, http); } @PostMapping("/restore-password") // anonymous access + @Operation(summary = "Восстановить пароль через OTP код") public ResponseEntity restorePassword(@Valid @RequestBody RestorePasswordDto request) { return userControllerFacade.restorePasswordByOtp(request); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java index 0b90359..7a07e41 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java @@ -6,6 +6,8 @@ import com.github.gribanoveu.cuddly.controllers.facade.auth.AuthControllerFacade; import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -19,15 +21,18 @@ @RestController @RequiredArgsConstructor @RequestMapping("/v1/auth") +@Tag(name="Аутентификация пользователя", description="Позволяет получить и обновить токен") public class AuthController { private final AuthControllerFacade authControllerFacade; @PostMapping + @Operation(summary = "Получить токен", description = "Получение access token и refresh token") public ResponseEntity authenticateUser(@Valid @RequestBody LoginDto request) { return authControllerFacade.authenticateUser(request); } @PatchMapping + @Operation(summary = "Обновить токен", description = "Получение нового токена на основе refresh token") public ResponseEntity refreshToken(@Valid @RequestBody RefreshTokenDto request) { return authControllerFacade.refreshToken(request); } diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java index 5723c4b..743bc02 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java @@ -6,6 +6,9 @@ import com.github.gribanoveu.cuddly.entities.tables.User; import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -22,12 +25,15 @@ @RestController @RequiredArgsConstructor @RequestMapping("/v1/user") +@Tag(name="Контроллер пользователя", description="Юзер управляет своим аккаунтом") public class UserController { private final UserControllerFacade userControllerFacade; @LogRequest @LogResponse @GetMapping + @Operation(summary = "Получить данные текущего пользователя") + @SecurityRequirement(name = "JWT") public ResponseEntity getUserData(Authentication authentication) { return userControllerFacade.getUserData(authentication); } @@ -35,11 +41,14 @@ public ResponseEntity getUserData(Authentication authentication) { @LogRequest @LogResponse @PostMapping + @Operation(summary = "Регистрация нового пользователя") public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { return userControllerFacade.registerUser(request); } @DeleteMapping + @Operation(summary = "Удалить текущего авторизованного пользователя", description = "Пользователь удаляет сам себя") + @SecurityRequirement(name = "JWT") public ResponseEntity deleteUser(Authentication authentication) { return userControllerFacade.deleteUser(authentication); } From b9ddf59706fd5f83ad4243ba11e3099abc22ecc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 21 Dec 2023 17:03:37 +0300 Subject: [PATCH 21/34] change name to cuddle Took 41 minutes --- docker/dev-compose.yml | 58 +++++++++++++++++++ docker/postgres-compose.yml | 29 ---------- docker/redis-compose.yml | 16 ----- pom.xml | 12 ++-- .../CuddleApplication.java} | 8 +-- .../config/RedisConfig.java | 2 +- .../config/RsaProperties.java | 2 +- .../config/SecurityConfig.java | 12 ++-- .../config/ThymeleafConfig.java | 2 +- .../config/TokenConfig.java | 2 +- .../constants/Constants.java | 2 +- .../constants/EmailMessages.java | 2 +- .../constants/RegexpFormat.java | 2 +- .../constants/ValidationMessages.java | 2 +- .../dtos/data/SimpleEmailObject.java | 2 +- .../dtos/request/admin/PermissionDto.java | 6 +- .../request/admin/UpdatePermissionDto.java | 6 +- .../dtos/request/auth/ChangeEmailDto.java | 6 +- .../dtos/request/auth/ChangePasswordDto.java | 4 +- .../dtos/request/auth/GenerateOtpDto.java | 6 +- .../dtos/request/auth/LoginDto.java | 7 +-- .../dtos/request/auth/RefreshTokenDto.java | 4 +- .../dtos/request/auth/RegisterDto.java | 8 +-- .../dtos/request/auth/RestorePasswordDto.java | 8 +-- .../dtos/response/ResponseDetails.java | 4 +- .../dtos/response/StatusResponse.java | 6 +- .../response/auth/PermissionsResponse.java | 6 +- .../dtos/response/auth/TokenResponse.java | 4 +- .../dtos/response/auth/UsersResponse.java | 6 +- .../endpoints/admin/ModeratorController.java | 4 +- .../endpoints/auth/AccountController.java | 19 +++--- .../endpoints/auth/AuthController.java | 13 ++--- .../endpoints/auth/UserController.java | 14 ++--- .../controllers/exeptions/CredentialEx.java | 6 +- .../exeptions/GlobalExceptionHandler.java | 16 +++-- .../entrypoint/AccessDeniedEntryPoint.java | 11 ++-- .../entrypoint/AuthErrorEntryPoint.java | 10 ++-- .../AuthenticationFailureEntryPoint.java | 4 +- .../entrypoint/ServerErrorEntryPoint.java | 12 ++-- .../admin/ModeratorControllerFacade.java | 12 ++-- .../facade/auth/AccountControllerFacade.java | 30 +++++----- .../facade/auth/AuthControllerFacade.java | 34 ++++------- .../facade/auth/UserControllerFacade.java | 24 ++++---- .../entities/enums/ResponseCode.java | 3 +- .../entities/enums/Role.java | 2 +- .../entities/enums/StatusLevel.java | 2 +- .../entities/enums/TokenType.java | 2 +- .../repositories/PermissionRepository.java | 4 +- .../entities/repositories/UserRepository.java | 4 +- .../entities/services/email/EmailService.java | 4 +- .../services/email/EmailServiceImpl.java | 8 +-- .../services/otp/RedisOtpService.java | 2 +- .../services/otp/RedisOtpServiceImpl.java | 7 +-- .../permission/PermissionService.java | 4 +- .../entities/services/token/TokenService.java | 6 +- .../services/token/TokenServiceImpl.java | 12 ++-- .../entities/services/user/UserService.java | 4 +- .../services/user/UserServiceImpl.java | 11 ++-- .../entities/tables/User.java | 4 +- .../security/CustomUserDetails.java | 4 +- .../security/CustomUserDetailsService.java | 6 +- .../{cuddly => cuddle}/utils/JsonUtils.java | 2 +- .../utils/RSAEncryption.java | 5 +- .../utils/RefreshTokenUtils.java | 18 ++++-- .../utils/aspects/LogRequest.java | 2 +- .../utils/aspects/LogResponse.java | 2 +- .../utils/aspects/RequestLoggingAspect.java | 10 +--- .../utils/emails/EmailTemplates.java | 6 +- .../utils/validators/MinimalAge.java | 3 +- .../utils/validators/MinimalAgeValidator.java | 4 +- src/main/resources/application.yml | 12 ++-- .../resources/templates/fragment/about.html | 2 +- .../templates/successfully-registration.html | 4 +- .../CuddleApplicationTests.java} | 4 +- .../base/BaseMockMvcTest.java | 10 ++-- .../base/BaseValidatorTest.java | 2 +- .../base/ContainersConfig.java | 2 +- .../base/TestJsonUtils.java | 2 +- .../implementation/TokenServiceImplTest.java | 8 +-- .../utils/JsonUtilsTest.java | 4 +- 80 files changed, 309 insertions(+), 325 deletions(-) create mode 100644 docker/dev-compose.yml delete mode 100644 docker/postgres-compose.yml delete mode 100644 docker/redis-compose.yml rename src/main/java/com/github/gribanoveu/{cuddly/AuthServiceApplication.java => cuddle/CuddleApplication.java} (83%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/config/RedisConfig.java (96%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/config/RsaProperties.java (89%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/config/SecurityConfig.java (91%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/config/ThymeleafConfig.java (97%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/config/TokenConfig.java (96%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/constants/Constants.java (81%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/constants/EmailMessages.java (95%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/constants/RegexpFormat.java (92%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/constants/ValidationMessages.java (92%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/data/SimpleEmailObject.java (79%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/admin/PermissionDto.java (72%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/admin/UpdatePermissionDto.java (79%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/ChangeEmailDto.java (79%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/ChangePasswordDto.java (89%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/GenerateOtpDto.java (78%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/LoginDto.java (79%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/RefreshTokenDto.java (79%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/RegisterDto.java (82%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/request/auth/RestorePasswordDto.java (84%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/response/ResponseDetails.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/response/StatusResponse.java (89%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/response/auth/PermissionsResponse.java (86%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/response/auth/TokenResponse.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/dtos/response/auth/UsersResponse.java (85%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/endpoints/admin/ModeratorController.java (93%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/endpoints/auth/AccountController.java (78%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/endpoints/auth/AuthController.java (73%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/endpoints/auth/UserController.java (82%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/exeptions/CredentialEx.java (78%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/exeptions/GlobalExceptionHandler.java (90%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java (76%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java (80%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java (91%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java (80%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/facade/admin/ModeratorControllerFacade.java (83%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/facade/auth/AccountControllerFacade.java (85%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/facade/auth/AuthControllerFacade.java (65%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/controllers/facade/auth/UserControllerFacade.java (76%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/enums/ResponseCode.java (98%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/enums/Role.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/enums/StatusLevel.java (75%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/enums/TokenType.java (67%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/repositories/PermissionRepository.java (81%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/repositories/UserRepository.java (82%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/email/EmailService.java (63%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/email/EmailServiceImpl.java (89%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/otp/RedisOtpService.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/otp/RedisOtpServiceImpl.java (86%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/permission/PermissionService.java (82%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/token/TokenService.java (68%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/token/TokenServiceImpl.java (89%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/user/UserService.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/user/UserServiceImpl.java (86%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/entities/tables/User.java (93%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/security/CustomUserDetails.java (93%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/security/CustomUserDetailsService.java (84%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/JsonUtils.java (96%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/RSAEncryption.java (89%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/RefreshTokenUtils.java (83%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/aspects/LogRequest.java (85%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/aspects/LogResponse.java (87%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/aspects/RequestLoggingAspect.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/emails/EmailTemplates.java (88%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/validators/MinimalAge.java (84%) rename src/main/java/com/github/gribanoveu/{cuddly => cuddle}/utils/validators/MinimalAgeValidator.java (89%) rename src/test/java/com/github/gribanoveu/{cuddly/AuthServiceApplicationTests.java => cuddle/CuddleApplicationTests.java} (67%) rename src/test/java/com/github/gribanoveu/{cuddly => cuddle}/base/BaseMockMvcTest.java (88%) rename src/test/java/com/github/gribanoveu/{cuddly => cuddle}/base/BaseValidatorTest.java (93%) rename src/test/java/com/github/gribanoveu/{cuddly => cuddle}/base/ContainersConfig.java (92%) rename src/test/java/com/github/gribanoveu/{cuddly => cuddle}/base/TestJsonUtils.java (97%) rename src/test/java/com/github/gribanoveu/{cuddly => cuddle}/entities/services/implementation/TokenServiceImplTest.java (92%) rename src/test/java/com/github/gribanoveu/{cuddly => cuddle}/utils/JsonUtilsTest.java (91%) diff --git a/docker/dev-compose.yml b/docker/dev-compose.yml new file mode 100644 index 0000000..9fb7b15 --- /dev/null +++ b/docker/dev-compose.yml @@ -0,0 +1,58 @@ +name: cuddle +version: '3.7' + +services: + postgres-db: + image: postgres:15.4-alpine + container_name: cuddle_db_postgres + restart: unless-stopped + environment: + POSTGRES_USER: auth_postgres + POSTGRES_PASSWORD: auth#7533245 + POSTGRES_DB: auth_service_db + volumes: + - pgdata:/var/lib/postgresql/data + ports: + - "5432:5432" + command: > + postgres + -c max_connections=100 + -c shared_buffers=256MB + -c effective_cache_size=512MB + -c maintenance_work_mem=128MB + -c checkpoint_completion_target=0.7 + -c wal_buffers=8MB + -c random_page_cost=2 + -c effective_io_concurrency=1 + -c work_mem=8192kB + + redis-db: + image: redis:7.2.1-alpine + container_name: cuddle_db_redis + restart: unless-stopped + ports: + - "6379:6379" + command: redis-server --save 20 1 --loglevel warning + volumes: + - cache:/data + +# dev only stuff + mailcatcher: + container_name: cuddle_dev_mailcatcher + image: sj26/mailcatcher + restart: unless-stopped + ports: + - "1080:1080" # smtp + - "1025:1025" # http (ui) + + it-tools: + container_name: cuddle_dev_it-tools + image: 'corentinth/it-tools:latest' + ports: + - '8888:80' + restart: unless-stopped + +volumes: + pgdata: + cache: + driver: local \ No newline at end of file diff --git a/docker/postgres-compose.yml b/docker/postgres-compose.yml deleted file mode 100644 index 2eb0f16..0000000 --- a/docker/postgres-compose.yml +++ /dev/null @@ -1,29 +0,0 @@ -version: '3.7' - -services: - postgres-db: - image: postgres:15.4-alpine - container_name: auth_service_db_postgres - restart: always - environment: - POSTGRES_USER: auth_postgres - POSTGRES_PASSWORD: auth#7533245 - POSTGRES_DB: auth_service_db - volumes: - - pgdata:/var/lib/postgresql/data - ports: - - "5432:5432" - command: > - postgres - -c max_connections=100 - -c shared_buffers=256MB - -c effective_cache_size=512MB - -c maintenance_work_mem=128MB - -c checkpoint_completion_target=0.7 - -c wal_buffers=8MB - -c random_page_cost=2 - -c effective_io_concurrency=1 - -c work_mem=8192kB - -volumes: - pgdata: diff --git a/docker/redis-compose.yml b/docker/redis-compose.yml deleted file mode 100644 index 094fcb6..0000000 --- a/docker/redis-compose.yml +++ /dev/null @@ -1,16 +0,0 @@ -version: '3.7' - -services: - redis-db: - image: redis:7.2.1-alpine - container_name: auth_service_db_redis - restart: always - ports: - - "6379:6379" - command: redis-server --save 20 1 --loglevel warning - volumes: - - cache:/data - -volumes: - cache: - driver: local \ No newline at end of file diff --git a/pom.xml b/pom.xml index 05cb7c6..e23489c 100644 --- a/pom.xml +++ b/pom.xml @@ -11,15 +11,17 @@ com.github.gribanoveu - auth-service + cuddle-backend 0.1 - auth-service - Auth stateless server on Spring Boot 3, Security 6 + cuddle-backend + Cuddle backend server on Spring 17 2.0 1.0.7 + 5.0.0 + 2.3.0 @@ -91,12 +93,12 @@ de.siegmar logback-gelf - 5.0.0 + ${logback-gelf.version} org.springdoc springdoc-openapi-starter-webmvc-ui - 2.3.0 + ${springdoc-openapi-starter-webmvc-ui.version} diff --git a/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java b/src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java similarity index 83% rename from src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java rename to src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java index 2513f9f..e511208 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/AuthServiceApplication.java +++ b/src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly; +package com.github.gribanoveu.cuddle; -import com.github.gribanoveu.cuddly.config.RsaProperties; +import com.github.gribanoveu.cuddle.config.RsaProperties; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; import io.swagger.v3.oas.annotations.info.Contact; @@ -22,8 +22,8 @@ @SecurityScheme(name = "JWT", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer") @EnableConfigurationProperties({RsaProperties.class}) @SpringBootApplication -public class AuthServiceApplication { +public class CuddleApplication { public static void main(String[] args) { - SpringApplication.run(AuthServiceApplication.class, args); + SpringApplication.run(CuddleApplication.class, args); } } diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/RedisConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/RedisConfig.java similarity index 96% rename from src/main/java/com/github/gribanoveu/cuddly/config/RedisConfig.java rename to src/main/java/com/github/gribanoveu/cuddle/config/RedisConfig.java index d9997b1..fa00067 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/RedisConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/RedisConfig.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.config; +package com.github.gribanoveu.cuddle.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/RsaProperties.java b/src/main/java/com/github/gribanoveu/cuddle/config/RsaProperties.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/config/RsaProperties.java rename to src/main/java/com/github/gribanoveu/cuddle/config/RsaProperties.java index 7381e62..dac21be 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/RsaProperties.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/RsaProperties.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.config; +package com.github.gribanoveu.cuddle.config; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java similarity index 91% rename from src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java rename to src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java index 0de860e..a5c8cf1 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.config; +package com.github.gribanoveu.cuddle.config; -import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; -import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.AuthErrorEntryPoint; -import com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint.ServerErrorEntryPoint; -import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; +import com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; +import com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint.AuthErrorEntryPoint; +import com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint.ServerErrorEntryPoint; +import com.github.gribanoveu.cuddle.security.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -21,7 +21,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; -import static com.github.gribanoveu.cuddly.entities.enums.Role.*; +import static com.github.gribanoveu.cuddle.entities.enums.Role.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/ThymeleafConfig.java similarity index 97% rename from src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java rename to src/main/java/com/github/gribanoveu/cuddle/config/ThymeleafConfig.java index 1ed4918..0b21192 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/ThymeleafConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/ThymeleafConfig.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.config; +package com.github.gribanoveu.cuddle.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/TokenConfig.java similarity index 96% rename from src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java rename to src/main/java/com/github/gribanoveu/cuddle/config/TokenConfig.java index 0605c1c..ff44818 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/config/TokenConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/TokenConfig.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.config; +package com.github.gribanoveu.cuddle.config; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/Constants.java b/src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java similarity index 81% rename from src/main/java/com/github/gribanoveu/cuddly/constants/Constants.java rename to src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java index bad31ca..b6081f2 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/Constants.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.constants; +package com.github.gribanoveu.cuddle.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java b/src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java similarity index 95% rename from src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java rename to src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java index f47d7a3..979f380 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/EmailMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.constants; +package com.github.gribanoveu.cuddle.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java b/src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java rename to src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java index b1a9701..0a689d9 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/RegexpFormat.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.constants; +package com.github.gribanoveu.cuddle.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java b/src/main/java/com/github/gribanoveu/cuddle/constants/ValidationMessages.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java rename to src/main/java/com/github/gribanoveu/cuddle/constants/ValidationMessages.java index 90e3a60..f9b7358 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/constants/ValidationMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/ValidationMessages.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.constants; +package com.github.gribanoveu.cuddle.constants; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/data/SimpleEmailObject.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/data/SimpleEmailObject.java index 36ed4a3..891764c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/data/SimpleEmailObject.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/data/SimpleEmailObject.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.data; +package com.github.gribanoveu.cuddle.controllers.dtos.data; import java.util.Map; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/PermissionDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/PermissionDto.java similarity index 72% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/PermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/PermissionDto.java index 1632291..4cf7010 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/PermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/PermissionDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.admin; +package com.github.gribanoveu.cuddle.controllers.dtos.request.admin; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.PERMISSION_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.PERMISSION_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/UpdatePermissionDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/UpdatePermissionDto.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/UpdatePermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/UpdatePermissionDto.java index d09841a..d7829d4 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/admin/UpdatePermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/UpdatePermissionDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.admin; +package com.github.gribanoveu.cuddle.controllers.dtos.request.admin; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.PERMISSION_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.PERMISSION_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangeEmailDto.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangeEmailDto.java index 52092ea..1f20975 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangeEmailDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangeEmailDto.java @@ -1,12 +1,12 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangePasswordDto.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangePasswordDto.java index d1bad87..e08199a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangePasswordDto.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/GenerateOtpDto.java similarity index 78% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/GenerateOtpDto.java index b90c296..b6eaf48 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/GenerateOtpDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/GenerateOtpDto.java @@ -1,12 +1,12 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/LoginDto.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/LoginDto.java index 57fd4aa..7be090e 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/LoginDto.java @@ -1,13 +1,12 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; -import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RefreshTokenDto.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RefreshTokenDto.java index 1935221..988ba3e 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RefreshTokenDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RefreshTokenDto.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RegisterDto.java similarity index 82% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RegisterDto.java index b0ba219..621d48a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RegisterDto.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; -import com.github.gribanoveu.cuddly.utils.validators.MinimalAge; +import com.github.gribanoveu.cuddle.utils.validators.MinimalAge; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.*; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RestorePasswordDto.java similarity index 84% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RestorePasswordDto.java index 00ca2c7..fdf358a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/request/auth/RestorePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RestorePasswordDto.java @@ -1,13 +1,13 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.EMAIL_PATTERN; -import static com.github.gribanoveu.cuddly.constants.RegexpFormat.OTP_PATTERN; -import static com.github.gribanoveu.cuddly.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.OTP_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/ResponseDetails.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/ResponseDetails.java index 7d9b832..b27c79e 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/ResponseDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/ResponseDetails.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response; +package com.github.gribanoveu.cuddle.controllers.dtos.response; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/StatusResponse.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/StatusResponse.java index bec85a6..7ce65c6 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/StatusResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/StatusResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response; +package com.github.gribanoveu.cuddle.controllers.dtos.response; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/PermissionsResponse.java similarity index 86% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/PermissionsResponse.java index 443c215..b735985 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/PermissionsResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/PermissionsResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddly.entities.enums.Role; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.enums.Role; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/TokenResponse.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/TokenResponse.java index 66c3e03..7064a7e 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/TokenResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/TokenResponse.java @@ -1,12 +1,10 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.http.HttpStatus; import java.time.LocalDateTime; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/UsersResponse.java similarity index 85% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/UsersResponse.java index 9f2c13f..4913347 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/dtos/response/auth/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/UsersResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.controllers.dtos.response.auth; +package com.github.gribanoveu.cuddle.controllers.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.tables.User; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/admin/ModeratorController.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/admin/ModeratorController.java index d387b6b..596e68a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/admin/ModeratorController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/admin/ModeratorController.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints.admin; +package com.github.gribanoveu.cuddle.controllers.endpoints.admin; -import com.github.gribanoveu.cuddly.controllers.facade.admin.ModeratorControllerFacade; +import com.github.gribanoveu.cuddle.controllers.facade.admin.ModeratorControllerFacade; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java similarity index 78% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java index 71141fe..4db9796 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java @@ -1,15 +1,14 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints.auth; +package com.github.gribanoveu.cuddle.controllers.endpoints.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RestorePasswordDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.facade.auth.AccountControllerFacade; -import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; -import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangeEmailDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangePasswordDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.GenerateOtpDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RestorePasswordDto; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.facade.auth.AccountControllerFacade; +import com.github.gribanoveu.cuddle.utils.aspects.LogRequest; +import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AuthController.java similarity index 73% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AuthController.java index 7a07e41..af19337 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/AuthController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AuthController.java @@ -1,14 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints.auth; +package com.github.gribanoveu.cuddle.controllers.endpoints.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddly.controllers.facade.auth.AuthControllerFacade; -import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; -import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RefreshTokenDto; +import com.github.gribanoveu.cuddle.controllers.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddle.controllers.facade.auth.AuthControllerFacade; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/UserController.java similarity index 82% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/UserController.java index 743bc02..706f875 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/endpoints/auth/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/UserController.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.endpoints.auth; +package com.github.gribanoveu.cuddle.controllers.endpoints.auth; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RegisterDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.facade.auth.UserControllerFacade; -import com.github.gribanoveu.cuddly.entities.tables.User; -import com.github.gribanoveu.cuddly.utils.aspects.LogRequest; -import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.facade.auth.UserControllerFacade; +import com.github.gribanoveu.cuddle.entities.tables.User; +import com.github.gribanoveu.cuddle.utils.aspects.LogRequest; +import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/CredentialEx.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/CredentialEx.java similarity index 78% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/CredentialEx.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/CredentialEx.java index 50bad4a..69e6f5c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/CredentialEx.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/CredentialEx.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddly.controllers.exeptions; +package com.github.gribanoveu.cuddle.controllers.exeptions; -import com.github.gribanoveu.cuddly.controllers.dtos.response.ResponseDetails; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.controllers.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; import lombok.Getter; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.BadCredentialsException; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/GlobalExceptionHandler.java similarity index 90% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/GlobalExceptionHandler.java index 8cb8b9c..2f02ea6 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/GlobalExceptionHandler.java @@ -1,11 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.exeptions; +package com.github.gribanoveu.cuddle.controllers.exeptions; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; -import com.github.gribanoveu.cuddly.controllers.dtos.response.ResponseDetails; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.utils.aspects.LogResponse; +import com.github.gribanoveu.cuddle.constants.ValidationMessages; +import com.github.gribanoveu.cuddle.controllers.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import jakarta.validation.ConstraintViolationException; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; @@ -17,8 +17,6 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; -import java.time.DateTimeException; - /** * @author Evgeny Gribanov * @version 07.07.2023 diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java similarity index 76% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java index 2648033..000c3b8 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java @@ -1,15 +1,14 @@ -package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.utils.JsonUtils; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.authentication.DisabledException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java similarity index 80% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java index e5236c0..23f9f00 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.utils.JsonUtils; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java similarity index 91% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java index 89d5a74..828bdbc 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; -import com.github.gribanoveu.cuddly.utils.JsonUtils; +import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java similarity index 80% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java index 2dd6764..e6c67ea 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -1,13 +1,11 @@ -package com.github.gribanoveu.cuddly.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.utils.JsonUtils; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.AuthenticationException; @@ -16,7 +14,7 @@ import java.io.IOException; -import static com.github.gribanoveu.cuddly.entities.enums.ResponseCode.*; +import static com.github.gribanoveu.cuddle.entities.enums.ResponseCode.*; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/ModeratorControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/admin/ModeratorControllerFacade.java similarity index 83% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/ModeratorControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/facade/admin/ModeratorControllerFacade.java index e7b1326..acc37ef 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/admin/ModeratorControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/admin/ModeratorControllerFacade.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.cuddly.controllers.facade.admin; +package com.github.gribanoveu.cuddle.controllers.facade.admin; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.UsersResponse; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.services.user.UserService; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.dtos.response.auth.UsersResponse; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.services.user.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AccountControllerFacade.java similarity index 85% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AccountControllerFacade.java index 4694c06..fcd17cf 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AccountControllerFacade.java @@ -1,19 +1,19 @@ -package com.github.gribanoveu.cuddly.controllers.facade.auth; +package com.github.gribanoveu.cuddle.controllers.facade.auth; -import com.github.gribanoveu.cuddly.constants.EmailMessages; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangeEmailDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.ChangePasswordDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.GenerateOtpDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RestorePasswordDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.services.email.EmailService; -import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; -import com.github.gribanoveu.cuddly.entities.services.user.UserService; -import com.github.gribanoveu.cuddly.utils.JsonUtils; -import com.github.gribanoveu.cuddly.utils.emails.EmailTemplates; +import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangeEmailDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangePasswordDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.GenerateOtpDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RestorePasswordDto; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.services.email.EmailService; +import com.github.gribanoveu.cuddle.entities.services.otp.RedisOtpService; +import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import com.github.gribanoveu.cuddle.utils.JsonUtils; +import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AuthControllerFacade.java similarity index 65% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AuthControllerFacade.java index 01319b2..18549c4 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/AuthControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AuthControllerFacade.java @@ -1,21 +1,16 @@ -package com.github.gribanoveu.cuddly.controllers.facade.auth; +package com.github.gribanoveu.cuddle.controllers.facade.auth; -import com.github.gribanoveu.cuddly.constants.EmailMessages; -import com.github.gribanoveu.cuddly.constants.RegexpFormat; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RefreshTokenDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.email.EmailService; -import com.github.gribanoveu.cuddly.entities.services.token.TokenService; -import com.github.gribanoveu.cuddly.security.CustomUserDetails; -import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; -import com.github.gribanoveu.cuddly.utils.RSAEncryption; -import com.github.gribanoveu.cuddly.config.RsaProperties; -import com.github.gribanoveu.cuddly.utils.RefreshTokenUtils; -import com.github.gribanoveu.cuddly.utils.emails.EmailTemplates; +import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RefreshTokenDto; +import com.github.gribanoveu.cuddle.controllers.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.entities.services.email.EmailService; +import com.github.gribanoveu.cuddle.entities.services.token.TokenService; +import com.github.gribanoveu.cuddle.security.CustomUserDetails; +import com.github.gribanoveu.cuddle.security.CustomUserDetailsService; +import com.github.gribanoveu.cuddle.utils.RefreshTokenUtils; +import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -24,12 +19,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.stereotype.Service; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; import java.time.Duration; -import java.time.Instant; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java similarity index 76% rename from src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java index c9b94d8..dda8f8c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/controllers/facade/auth/UserControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java @@ -1,16 +1,16 @@ -package com.github.gribanoveu.cuddly.controllers.facade.auth; +package com.github.gribanoveu.cuddle.controllers.facade.auth; -import com.github.gribanoveu.cuddly.constants.EmailMessages; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.RegisterDto; -import com.github.gribanoveu.cuddly.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.Role; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddly.entities.services.email.EmailService; -import com.github.gribanoveu.cuddly.entities.services.user.UserService; -import com.github.gribanoveu.cuddly.entities.tables.User; -import com.github.gribanoveu.cuddly.utils.emails.EmailTemplates; +import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.Role; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.services.email.EmailService; +import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import com.github.gribanoveu.cuddle.entities.tables.User; +import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/ResponseCode.java similarity index 98% rename from src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/enums/ResponseCode.java index aeaec3d..03d8306 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/ResponseCode.java @@ -1,8 +1,7 @@ -package com.github.gribanoveu.cuddly.entities.enums; +package com.github.gribanoveu.cuddle.entities.enums; import lombok.AllArgsConstructor; import lombok.Getter; -import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; /** diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Role.java b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/Role.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/entities/enums/Role.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/enums/Role.java index f656abb..1bbe49c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/Role.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/Role.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.enums; +package com.github.gribanoveu.cuddle.entities.enums; import org.springframework.security.core.GrantedAuthority; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/StatusLevel.java b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/StatusLevel.java similarity index 75% rename from src/main/java/com/github/gribanoveu/cuddly/entities/enums/StatusLevel.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/enums/StatusLevel.java index e322a9b..9c86cd5 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/StatusLevel.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/StatusLevel.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.enums; +package com.github.gribanoveu.cuddle.entities.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/TokenType.java b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/TokenType.java similarity index 67% rename from src/main/java/com/github/gribanoveu/cuddly/entities/enums/TokenType.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/enums/TokenType.java index 649f346..cd4f1e7 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/enums/TokenType.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/enums/TokenType.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.enums; +package com.github.gribanoveu.cuddle.entities.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java similarity index 81% rename from src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java index 0c4e19b..4fc4d87 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/PermissionRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.entities.repositories; +package com.github.gribanoveu.cuddle.entities.repositories; -import com.github.gribanoveu.cuddly.entities.enums.Role; +import com.github.gribanoveu.cuddle.entities.enums.Role; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java similarity index 82% rename from src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java index 7e710ea..c56c7a8 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/repositories/UserRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.entities.repositories; +package com.github.gribanoveu.cuddle.entities.repositories; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddle.entities.tables.User; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java similarity index 63% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java index d18587d..6ffb6ae 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.entities.services.email; +package com.github.gribanoveu.cuddle.entities.services.email; -import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; +import com.github.gribanoveu.cuddle.controllers.dtos.data.SimpleEmailObject; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java index 38a073c..2dc52a5 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/email/EmailServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddly.entities.services.email; +package com.github.gribanoveu.cuddle.entities.services.email; -import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.controllers.dtos.data.SimpleEmailObject; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; import jakarta.mail.MessagingException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpService.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpService.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpService.java index de5c1a3..3a75c31 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpService.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.entities.services.otp; +package com.github.gribanoveu.cuddle.entities.services.otp; import java.time.Duration; import java.util.Optional; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java similarity index 86% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java index 3546fa2..8edd7a2 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/otp/RedisOtpServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java @@ -1,8 +1,7 @@ -package com.github.gribanoveu.cuddly.entities.services.otp; +package com.github.gribanoveu.cuddle.entities.services.otp; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.services.otp.RedisOtpService; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java similarity index 82% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java index bd23926..05010f5 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/permission/PermissionService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.entities.services.permission; +package com.github.gribanoveu.cuddle.entities.services.permission; -import com.github.gribanoveu.cuddly.entities.enums.Role; +import com.github.gribanoveu.cuddle.entities.enums.Role; import org.springframework.transaction.annotation.Transactional; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java similarity index 68% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenService.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java index 163f7f7..9fd5723 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddly.entities.services.token; +package com.github.gribanoveu.cuddle.entities.services.token; -import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.security.CustomUserDetails; +import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.security.CustomUserDetails; import java.util.Date; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java index a4118cc..7fb6f9a 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/token/TokenServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java @@ -1,11 +1,9 @@ -package com.github.gribanoveu.cuddly.entities.services.token; +package com.github.gribanoveu.cuddle.entities.services.token; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.token.TokenService; -import com.github.gribanoveu.cuddly.security.CustomUserDetails; -import com.nimbusds.jose.Header; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.security.CustomUserDetails; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import lombok.Getter; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserService.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java index ead69ad..f2a2c35 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.entities.services.user; +package com.github.gribanoveu.cuddle.entities.services.user; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddle.entities.tables.User; import org.springframework.transaction.annotation.Transactional; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java similarity index 86% rename from src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserServiceImpl.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java index c50284a..88c166b 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/services/user/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java @@ -1,10 +1,9 @@ -package com.github.gribanoveu.cuddly.entities.services.user; +package com.github.gribanoveu.cuddle.entities.services.user; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddly.entities.repositories.UserRepository; -import com.github.gribanoveu.cuddly.entities.services.user.UserService; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.entities.repositories.UserRepository; +import com.github.gribanoveu.cuddle.entities.tables.User; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java rename to src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java index c9e0105..1392922 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/entities/tables/User.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.entities.tables; +package com.github.gribanoveu.cuddle.entities.tables; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.gribanoveu.cuddly.entities.enums.Role; +import com.github.gribanoveu.cuddle.entities.enums.Role; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java b/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java rename to src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java index 6ff0795..06749dc 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.security; +package com.github.gribanoveu.cuddle.security; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddle.entities.tables.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetailsService.java b/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetailsService.java similarity index 84% rename from src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetailsService.java rename to src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetailsService.java index 4f50424..6458017 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/security/CustomUserDetailsService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetailsService.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddly.security; +package com.github.gribanoveu.cuddle.security; -import com.github.gribanoveu.cuddly.entities.repositories.UserRepository; -import com.github.gribanoveu.cuddly.entities.tables.User; +import com.github.gribanoveu.cuddle.entities.repositories.UserRepository; +import com.github.gribanoveu.cuddle.entities.tables.User; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/JsonUtils.java b/src/main/java/com/github/gribanoveu/cuddle/utils/JsonUtils.java similarity index 96% rename from src/main/java/com/github/gribanoveu/cuddly/utils/JsonUtils.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/JsonUtils.java index 25b5e04..615ffd5 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/JsonUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/JsonUtils.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.utils; +package com.github.gribanoveu.cuddle.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryption.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryption.java index c35be50..190aa49 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/RSAEncryption.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryption.java @@ -1,13 +1,10 @@ -package com.github.gribanoveu.cuddly.utils; +package com.github.gribanoveu.cuddle.utils; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import javax.crypto.Cipher; import java.security.*; -import java.security.spec.EncodedKeySpec; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java similarity index 83% rename from src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java index 0c2fa48..d404889 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/RefreshTokenUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java @@ -1,10 +1,11 @@ -package com.github.gribanoveu.cuddly.utils; +package com.github.gribanoveu.cuddle.utils; -import com.github.gribanoveu.cuddly.config.RsaProperties; -import com.github.gribanoveu.cuddly.constants.RegexpFormat; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.config.RsaProperties; +import com.github.gribanoveu.cuddle.constants.RegexpFormat; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -12,6 +13,10 @@ import java.security.interfaces.RSAPublicKey; import java.time.Duration; import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -19,6 +24,7 @@ * @author Evgeny Gribanov * @version 24.10.2023 */ +@Slf4j @Component @RequiredArgsConstructor public class RefreshTokenUtils { @@ -53,7 +59,7 @@ public String validateRefreshTokenAndExtractEmail(String token) { private void checkTokenValidity(String tokenValue) { Pattern datePattern = Pattern.compile(RegexpFormat.UNIX_DATE_TOKEN_PATTERN); Matcher dateMatcher = datePattern.matcher(tokenValue); - if (dateMatcher.find()) { // todo добавить отображение даты в лог + if (dateMatcher.find()) { var refreshTokenDateInMillis = Long.parseLong(dateMatcher.group(1)); if (Instant.now().toEpochMilli() > refreshTokenDateInMillis) { throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/LogRequest.java similarity index 85% rename from src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/aspects/LogRequest.java index f8eecc4..0941280 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogRequest.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/LogRequest.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.utils.aspects; +package com.github.gribanoveu.cuddle.utils.aspects; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/LogResponse.java similarity index 87% rename from src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/aspects/LogResponse.java index ee4200a..a482a88 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/LogResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/LogResponse.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.utils.aspects; +package com.github.gribanoveu.cuddle.utils.aspects; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java index 986c654..889e85c 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/aspects/RequestLoggingAspect.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java @@ -1,9 +1,6 @@ -package com.github.gribanoveu.cuddly.utils.aspects; +package com.github.gribanoveu.cuddle.utils.aspects; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.gribanoveu.cuddly.utils.JsonUtils; -import jakarta.servlet.http.HttpServletRequest; +import com.github.gribanoveu.cuddle.utils.JsonUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; @@ -16,9 +13,6 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import java.util.Arrays; -import java.util.Map; - @Aspect @Component @Slf4j diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/emails/EmailTemplates.java b/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddly/utils/emails/EmailTemplates.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java index c145fbd..eb52cc3 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/emails/EmailTemplates.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddly.utils.emails; +package com.github.gribanoveu.cuddle.utils.emails; -import com.github.gribanoveu.cuddly.constants.EmailMessages; -import com.github.gribanoveu.cuddly.controllers.dtos.data.SimpleEmailObject; +import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.controllers.dtos.data.SimpleEmailObject; import java.time.Duration; import java.util.Map; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java b/src/main/java/com/github/gribanoveu/cuddle/utils/validators/MinimalAge.java similarity index 84% rename from src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/validators/MinimalAge.java index ced326e..eb292b3 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAge.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/validators/MinimalAge.java @@ -1,6 +1,5 @@ -package com.github.gribanoveu.cuddly.utils.validators; +package com.github.gribanoveu.cuddle.utils.validators; -import com.github.gribanoveu.cuddly.constants.ValidationMessages; import jakarta.validation.Constraint; import jakarta.validation.Payload; diff --git a/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java b/src/main/java/com/github/gribanoveu/cuddle/utils/validators/MinimalAgeValidator.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/validators/MinimalAgeValidator.java index 797f870..2c45ed8 100644 --- a/src/main/java/com/github/gribanoveu/cuddly/utils/validators/MinimalAgeValidator.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/validators/MinimalAgeValidator.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.utils.validators; +package com.github.gribanoveu.cuddle.utils.validators; -import com.github.gribanoveu.cuddly.constants.RegexpFormat; +import com.github.gribanoveu.cuddle.constants.RegexpFormat; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index c441123..7ad4b1a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -11,16 +11,16 @@ rsa: public-key: classpath:certs/public.pem spring: mail: - host: smtp.gmail.com - port: 587 - username: ${SPRING_EMAIL_USER} - password: ${SPRING_EMAIL_PASSWORD} + host: localhost + port: 1025 + username: + password: properties: mail: smtp: - auth: true + auth: false starttls: - enable: true + enable: false mvc: throw-exception-if-no-handler-found: true web: diff --git a/src/main/resources/templates/fragment/about.html b/src/main/resources/templates/fragment/about.html index cac399b..9804562 100644 --- a/src/main/resources/templates/fragment/about.html +++ b/src/main/resources/templates/fragment/about.html @@ -6,7 +6,7 @@
Внимание! Отвечать на это письмо не нужно, оно создано автоматически.
-
По всем вопросам обращайтесь в support@cuddly.pw
+
По всем вопросам обращайтесь в support@cuddle.pw
---
С уважением, администрация Cuddle
diff --git a/src/main/resources/templates/successfully-registration.html b/src/main/resources/templates/successfully-registration.html index 99cc714..c04af54 100644 --- a/src/main/resources/templates/successfully-registration.html +++ b/src/main/resources/templates/successfully-registration.html @@ -51,9 +51,9 @@

Продолжая регистрацию, вы подтверждаете своё совершеннолетие (18+) и осознаёте, какую информацию вы публикуете на нашем ресурсе. Если представленная информация в приложении способна вывести вас из состояния душевного равновесия, не продолжайте регистрацию и не используйте приложение!

- Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования. + Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования.
 
- А так же ознакомьтесь с нашими правилами сообщества, в них вам будет рассказано, какую информацию о себе вы можете публиковать не нарушая правила. + А так же ознакомьтесь с нашими правилами сообщества, в них вам будет рассказано, какую информацию о себе вы можете публиковать не нарушая правила. Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать разные пароли для электронной почты и для ваших учетных записей.
 
diff --git a/src/test/java/com/github/gribanoveu/cuddly/AuthServiceApplicationTests.java b/src/test/java/com/github/gribanoveu/cuddle/CuddleApplicationTests.java similarity index 67% rename from src/test/java/com/github/gribanoveu/cuddly/AuthServiceApplicationTests.java rename to src/test/java/com/github/gribanoveu/cuddle/CuddleApplicationTests.java index 3f5f137..6a5ebec 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/AuthServiceApplicationTests.java +++ b/src/test/java/com/github/gribanoveu/cuddle/CuddleApplicationTests.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.cuddly; +package com.github.gribanoveu.cuddle; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class AuthServiceApplicationTests { +class CuddleApplicationTests { @Test void contextLoads() { diff --git a/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java b/src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java similarity index 88% rename from src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java rename to src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java index 85ef6d0..af88ace 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/base/BaseMockMvcTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddly.base; +package com.github.gribanoveu.cuddle.base; -import com.github.gribanoveu.cuddly.entities.enums.TokenType; -import com.github.gribanoveu.cuddly.entities.services.token.TokenService; -import com.github.gribanoveu.cuddly.security.CustomUserDetails; -import com.github.gribanoveu.cuddly.security.CustomUserDetailsService; +import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.entities.services.token.TokenService; +import com.github.gribanoveu.cuddle.security.CustomUserDetails; +import com.github.gribanoveu.cuddle.security.CustomUserDetailsService; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; diff --git a/src/test/java/com/github/gribanoveu/cuddly/base/BaseValidatorTest.java b/src/test/java/com/github/gribanoveu/cuddle/base/BaseValidatorTest.java similarity index 93% rename from src/test/java/com/github/gribanoveu/cuddly/base/BaseValidatorTest.java rename to src/test/java/com/github/gribanoveu/cuddle/base/BaseValidatorTest.java index 46459fa..7bbe19a 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/base/BaseValidatorTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/base/BaseValidatorTest.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.base; +package com.github.gribanoveu.cuddle.base; import jakarta.validation.Validation; import jakarta.validation.Validator; diff --git a/src/test/java/com/github/gribanoveu/cuddly/base/ContainersConfig.java b/src/test/java/com/github/gribanoveu/cuddle/base/ContainersConfig.java similarity index 92% rename from src/test/java/com/github/gribanoveu/cuddly/base/ContainersConfig.java rename to src/test/java/com/github/gribanoveu/cuddle/base/ContainersConfig.java index f8e9bea..92395d1 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/base/ContainersConfig.java +++ b/src/test/java/com/github/gribanoveu/cuddle/base/ContainersConfig.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.base; +package com.github.gribanoveu.cuddle.base; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; diff --git a/src/test/java/com/github/gribanoveu/cuddly/base/TestJsonUtils.java b/src/test/java/com/github/gribanoveu/cuddle/base/TestJsonUtils.java similarity index 97% rename from src/test/java/com/github/gribanoveu/cuddly/base/TestJsonUtils.java rename to src/test/java/com/github/gribanoveu/cuddle/base/TestJsonUtils.java index 9312ece..6abe804 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/base/TestJsonUtils.java +++ b/src/test/java/com/github/gribanoveu/cuddle/base/TestJsonUtils.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddly.base; +package com.github.gribanoveu.cuddle.base; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java b/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java similarity index 92% rename from src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java rename to src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java index fe00a8f..41c1ffa 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/entities/services/implementation/TokenServiceImplTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddly.entities.services.implementation; +package com.github.gribanoveu.cuddle.entities.services.implementation; -import com.github.gribanoveu.cuddly.base.BaseMockMvcTest; -import com.github.gribanoveu.cuddly.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddly.entities.services.token.TokenService; +import com.github.gribanoveu.cuddle.base.BaseMockMvcTest; +import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.entities.services.token.TokenService; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java b/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java similarity index 91% rename from src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java rename to src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java index 8fcd377..4ff5450 100644 --- a/src/test/java/com/github/gribanoveu/cuddly/utils/JsonUtilsTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java @@ -1,6 +1,6 @@ -package com.github.gribanoveu.cuddly.utils; +package com.github.gribanoveu.cuddle.utils; -import com.github.gribanoveu.cuddly.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.LoginDto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; From 1023ec0bcc21ecf04e5a86af60d1df648dd276cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 10:15:50 +0300 Subject: [PATCH 22/34] refactor project structure Took 1 hour 4 minutes --- .../cuddle/config/SecurityConfig.java | 8 +-- .../AuthenticationControllerFacade.java} | 14 ++-- .../PublicAccountControllerFacade.java} | 46 +++++++++--- .../endpoints/auth/AccountController.java | 61 ---------------- .../facade/auth/UserControllerFacade.java | 71 ------------------- .../ModeratorControllerFacade.java | 10 +-- .../secure/UserControllerFacade.java | 47 ++++++++++++ .../dtos/data/SimpleEmailObject.java | 2 +- .../enums/ResponseCode.java | 2 +- .../cuddle/{entities => dtos}/enums/Role.java | 2 +- .../{entities => dtos}/enums/StatusLevel.java | 2 +- .../{entities => dtos}/enums/TokenType.java | 2 +- .../dtos/request/admin/PermissionDto.java | 2 +- .../request/admin/UpdatePermissionDto.java | 2 +- .../dtos/request/auth/ChangeEmailDto.java | 2 +- .../dtos/request/auth/ChangePasswordDto.java | 2 +- .../dtos/request/auth/GenerateOtpDto.java | 2 +- .../dtos/request/auth/LoginDto.java | 2 +- .../dtos/request/auth/RefreshTokenDto.java | 2 +- .../dtos/request/auth/RegisterDto.java | 2 +- .../dtos/request/auth/RestorePasswordDto.java | 2 +- .../dtos/response/ResponseDetails.java | 4 +- .../dtos/response/StatusResponse.java | 6 +- .../response/auth/PermissionsResponse.java | 6 +- .../dtos/response/auth/TokenResponse.java | 2 +- .../dtos/response/auth/UsersResponse.java | 4 +- .../anonymous/AuthenticationController.java} | 18 ++--- .../anonymous/PublicAccountController.java | 44 ++++++++++++ .../secure}/ModeratorController.java | 20 +++++- .../secure/PrivateAccountController.java | 43 +++++++++++ .../secure}/UserController.java | 26 ++----- .../endpoints/secure/UserRoleController.java | 41 +++++++++++ .../repositories/PermissionRepository.java | 2 +- .../entities/services/email/EmailService.java | 2 +- .../services/email/EmailServiceImpl.java | 6 +- .../services/otp/RedisOtpServiceImpl.java | 4 +- .../permission/PermissionService.java | 2 +- .../entities/services/token/TokenService.java | 2 +- .../services/token/TokenServiceImpl.java | 6 +- .../services/user/UserServiceImpl.java | 4 +- .../cuddle/entities/tables/User.java | 3 +- .../exeptions/CredentialEx.java | 6 +- .../exeptions/GlobalExceptionHandler.java | 10 +-- .../entrypoint/AccessDeniedEntryPoint.java | 8 +-- .../entrypoint/AuthErrorEntryPoint.java | 8 +-- .../AuthenticationFailureEntryPoint.java | 2 +- .../entrypoint/ServerErrorEntryPoint.java | 8 +-- ...ncryption.java => RSAEncryptionUtils.java} | 2 +- .../cuddle/utils/RefreshTokenUtils.java | 14 ++-- .../cuddle/utils/emails/EmailTemplates.java | 2 +- .../cuddle/base/BaseMockMvcTest.java | 2 +- .../implementation/TokenServiceImplTest.java | 2 +- .../cuddle/utils/JsonUtilsTest.java | 2 +- 53 files changed, 327 insertions(+), 269 deletions(-) rename src/main/java/com/github/gribanoveu/cuddle/controllers/{facade/auth/AuthControllerFacade.java => anonymous/AuthenticationControllerFacade.java} (87%) rename src/main/java/com/github/gribanoveu/cuddle/controllers/{facade/auth/AccountControllerFacade.java => anonymous/PublicAccountControllerFacade.java} (74%) delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java rename src/main/java/com/github/gribanoveu/cuddle/controllers/{facade/admin => secure}/ModeratorControllerFacade.java (85%) create mode 100644 src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/data/SimpleEmailObject.java (79%) rename src/main/java/com/github/gribanoveu/cuddle/{entities => dtos}/enums/ResponseCode.java (99%) rename src/main/java/com/github/gribanoveu/cuddle/{entities => dtos}/enums/Role.java (88%) rename src/main/java/com/github/gribanoveu/cuddle/{entities => dtos}/enums/StatusLevel.java (75%) rename src/main/java/com/github/gribanoveu/cuddle/{entities => dtos}/enums/TokenType.java (67%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/admin/PermissionDto.java (90%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/admin/UpdatePermissionDto.java (92%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/ChangeEmailDto.java (92%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/ChangePasswordDto.java (94%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/GenerateOtpDto.java (92%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/LoginDto.java (93%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/RefreshTokenDto.java (89%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/RegisterDto.java (95%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/request/auth/RestorePasswordDto.java (95%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/response/ResponseDetails.java (88%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/response/StatusResponse.java (89%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/response/auth/PermissionsResponse.java (85%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/response/auth/TokenResponse.java (95%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/dtos/response/auth/UsersResponse.java (89%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers/endpoints/auth/AuthController.java => endpoints/anonymous/AuthenticationController.java} (63%) create mode 100644 src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java rename src/main/java/com/github/gribanoveu/cuddle/{controllers/endpoints/admin => endpoints/secure}/ModeratorController.java (58%) create mode 100644 src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java rename src/main/java/com/github/gribanoveu/cuddle/{controllers/endpoints/auth => endpoints/secure}/UserController.java (62%) create mode 100644 src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/exeptions/CredentialEx.java (76%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/exeptions/GlobalExceptionHandler.java (92%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/exeptions/entrypoint/AccessDeniedEntryPoint.java (82%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/exeptions/entrypoint/AuthErrorEntryPoint.java (82%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/exeptions/entrypoint/AuthenticationFailureEntryPoint.java (94%) rename src/main/java/com/github/gribanoveu/cuddle/{controllers => }/exeptions/entrypoint/ServerErrorEntryPoint.java (85%) rename src/main/java/com/github/gribanoveu/cuddle/utils/{RSAEncryption.java => RSAEncryptionUtils.java} (97%) diff --git a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java index a5c8cf1..1ccab5f 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.config; -import com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint.AccessDeniedEntryPoint; -import com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint.AuthErrorEntryPoint; -import com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint.ServerErrorEntryPoint; +import com.github.gribanoveu.cuddle.exeptions.entrypoint.AccessDeniedEntryPoint; +import com.github.gribanoveu.cuddle.exeptions.entrypoint.AuthErrorEntryPoint; +import com.github.gribanoveu.cuddle.exeptions.entrypoint.ServerErrorEntryPoint; import com.github.gribanoveu.cuddle.security.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; @@ -21,8 +21,6 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; -import static com.github.gribanoveu.cuddle.entities.enums.Role.*; - /** * @author Evgeny Gribanov * @version 28.08.2023 diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AuthControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java similarity index 87% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AuthControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java index 18549c4..cfec2a3 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AuthControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.cuddle.controllers.facade.auth; +package com.github.gribanoveu.cuddle.controllers.anonymous; import com.github.gribanoveu.cuddle.constants.EmailMessages; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.LoginDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RefreshTokenDto; -import com.github.gribanoveu.cuddle.controllers.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.dtos.request.auth.RefreshTokenDto; +import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddle.dtos.enums.TokenType; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.token.TokenService; import com.github.gribanoveu.cuddle.security.CustomUserDetails; @@ -28,7 +28,7 @@ @Slf4j @Service @RequiredArgsConstructor -public class AuthControllerFacade { +public class AuthenticationControllerFacade { @Value("${time-variable.accessTokenLifetime}") private Duration accessTokenLifetime; private final TokenService tokenService; @@ -59,6 +59,4 @@ public ResponseEntity refreshToken(RefreshTokenDto request) { return ResponseEntity.ok(TokenResponse.create(accessTokenLifetime.toSeconds(), accessToken, encryptedRefreshToken)); } - - } diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java similarity index 74% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AccountControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java index fcd17cf..7a8a0a0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/AccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java @@ -1,14 +1,13 @@ -package com.github.gribanoveu.cuddle.controllers.facade.auth; +package com.github.gribanoveu.cuddle.controllers.anonymous; import com.github.gribanoveu.cuddle.constants.EmailMessages; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangeEmailDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangePasswordDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.GenerateOtpDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RestorePasswordDto; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.enums.Role; +import com.github.gribanoveu.cuddle.dtos.request.auth.*; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.entities.tables.User; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.otp.RedisOtpService; import com.github.gribanoveu.cuddle.entities.services.user.UserService; @@ -22,8 +21,11 @@ import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.time.Duration; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; /** * @author Evgeny Gribanov @@ -32,7 +34,7 @@ @Slf4j @Service @RequiredArgsConstructor -public class AccountControllerFacade { +public class PublicAccountControllerFacade { @Value("${time-variable.otpCodeLifetime}") private Duration otpCodeLifeTime; private final UserService userService; @@ -41,6 +43,30 @@ public class AccountControllerFacade { private final EmailService emailService; private final JsonUtils jsonUtils; + public ResponseEntity registerUser(RegisterDto request) { + if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); + if (userService.userExistByEmail(request.email())) throw new CredentialEx(ResponseCode.USER_ALREADY_EXIST); + + var user = new User(); + user.setEmail(request.email()); + user.setBirthDate(LocalDate.parse(request.birthDate(), DateTimeFormatter.ISO_LOCAL_DATE)); // yyyy-MM-dd + user.setPassword(passwordEncoder.encode(request.password())); + user.setRole(Role.USER); + userService.saveUser(user); + log.info("User saved: {}", user.getEmail()); + + var location = ServletUriComponentsBuilder + .fromCurrentContextPath().path("/v1/user/{id}") + .buildAndExpand(user.getId()).toUri(); + + emailService.sendMail(EmailTemplates.simpleEmail(request.email(), + EmailMessages.userRegisteredSubject, EmailMessages.userRegisteredTemplate)); + log.info("Register confirm send to email: {}", request.email()); + + return ResponseEntity.created (location).body(StatusResponse.create( + ResponseCode.USER_CREATED, StatusLevel.SUCCESS)); + } + // user change email from app, authenticated public ResponseEntity changeEmail(ChangeEmailDto request, Authentication authentication) { var user = userService.findUserByEmail(authentication.getName()); diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java deleted file mode 100644 index 4db9796..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AccountController.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.github.gribanoveu.cuddle.controllers.endpoints.auth; - -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangeEmailDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.ChangePasswordDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.GenerateOtpDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RestorePasswordDto; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.facade.auth.AccountControllerFacade; -import com.github.gribanoveu.cuddle.utils.aspects.LogRequest; -import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.security.SecurityRequirement; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.*; - -/** - * @author Evgeny Gribanov - * @version 22.09.2023 - */ -@RestController -@RequiredArgsConstructor -@RequestMapping("/v1/account") -@Tag(name="Управление аккаунтом", description="Позволяет управлять данными учетной записи") -public class AccountController { - private final AccountControllerFacade userControllerFacade; - - @LogRequest - @LogResponse - @PatchMapping("/change-email") - @Operation(summary = "Сменить Email") - @SecurityRequirement(name = "JWT") - public ResponseEntity changeEmail(@Valid @RequestBody ChangeEmailDto request, Authentication auth) { - return userControllerFacade.changeEmail(request, auth); - } - - @PatchMapping("/change-password") - @Operation(summary = "Сменить пароль") - @SecurityRequirement(name = "JWT") - public ResponseEntity changePassword(@Valid @RequestBody ChangePasswordDto request, Authentication auth) { - return userControllerFacade.changePassword(request, auth); - } - - @LogRequest - @LogResponse - @PostMapping("/generate-code") // anonymous access - @Operation(summary = "Сгенерировать OTP код") - public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request, HttpServletRequest http) { - return userControllerFacade.generateOtpCode(request, http); - } - - @PostMapping("/restore-password") // anonymous access - @Operation(summary = "Восстановить пароль через OTP код") - public ResponseEntity restorePassword(@Valid @RequestBody RestorePasswordDto request) { - return userControllerFacade.restorePasswordByOtp(request); - } -} diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java deleted file mode 100644 index dda8f8c..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/auth/UserControllerFacade.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.github.gribanoveu.cuddle.controllers.facade.auth; - -import com.github.gribanoveu.cuddle.constants.EmailMessages; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RegisterDto; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.Role; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; -import com.github.gribanoveu.cuddle.entities.services.email.EmailService; -import com.github.gribanoveu.cuddle.entities.services.user.UserService; -import com.github.gribanoveu.cuddle.entities.tables.User; -import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -/** - * @author Evgeny Gribanov - * @version 29.08.2023 - */ -@Slf4j -@Service -@RequiredArgsConstructor -public class UserControllerFacade { - private final UserService userService; - private final PasswordEncoder passwordEncoder; - private final EmailService emailService; - - public ResponseEntity getUserData(Authentication authentication) { - var userData = userService.findUserByEmail(authentication.getName()); - return ResponseEntity.ok(userData); - } - - public ResponseEntity registerUser(RegisterDto request) { - if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS); - if (userService.userExistByEmail(request.email())) throw new CredentialEx(ResponseCode.USER_ALREADY_EXIST); - - var user = new User(); - user.setEmail(request.email()); - user.setBirthDate(LocalDate.parse(request.birthDate(), DateTimeFormatter.ISO_LOCAL_DATE)); // yyyy-MM-dd - user.setPassword(passwordEncoder.encode(request.password())); - user.setRole(Role.USER); - userService.saveUser(user); - log.info("User saved: {}", user.getEmail()); - - var location = ServletUriComponentsBuilder - .fromCurrentContextPath().path("/v1/user/{id}") - .buildAndExpand(user.getId()).toUri(); - - emailService.sendMail(EmailTemplates.simpleEmail(request.email(), - EmailMessages.userRegisteredSubject, EmailMessages.userRegisteredTemplate)); - log.info("Register confirm send to email: {}", request.email()); - - return ResponseEntity.created (location).body(StatusResponse.create( - ResponseCode.USER_CREATED, StatusLevel.SUCCESS)); - } - - public ResponseEntity deleteUser(Authentication authentication) { - userService.deleteUserByEmail(authentication.getName()); - return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS)); - } -} - diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/admin/ModeratorControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java similarity index 85% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/facade/admin/ModeratorControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java index acc37ef..bf1ae98 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/facade/admin/ModeratorControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddle.controllers.facade.admin; +package com.github.gribanoveu.cuddle.controllers.secure; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.dtos.response.auth.UsersResponse; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.dtos.response.auth.UsersResponse; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.entities.services.user.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java new file mode 100644 index 0000000..c1c1acb --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java @@ -0,0 +1,47 @@ +package com.github.gribanoveu.cuddle.controllers.secure; + +import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.entities.services.email.EmailService; +import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import com.github.gribanoveu.cuddle.entities.tables.User; +import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +/** + * @author Evgeny Gribanov + * @version 29.08.2023 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UserControllerFacade { + private final UserService userService; + private final PasswordEncoder passwordEncoder; + private final EmailService emailService; + + public ResponseEntity getUserData(Authentication authentication) { + var userData = userService.findUserByEmail(authentication.getName()); + return ResponseEntity.ok(userData); + } + + public ResponseEntity deleteUser(Authentication authentication) { + userService.deleteUserByEmail(authentication.getName()); + return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS)); + } +} + diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/data/SimpleEmailObject.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/data/SimpleEmailObject.java similarity index 79% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/data/SimpleEmailObject.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/data/SimpleEmailObject.java index 891764c..369a277 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/data/SimpleEmailObject.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/data/SimpleEmailObject.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.data; +package com.github.gribanoveu.cuddle.dtos.data; import java.util.Map; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java similarity index 99% rename from src/main/java/com/github/gribanoveu/cuddle/entities/enums/ResponseCode.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java index 03d8306..23e2c4c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.entities.enums; +package com.github.gribanoveu.cuddle.dtos.enums; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/Role.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/Role.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddle/entities/enums/Role.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/enums/Role.java index 1bbe49c..aff80b6 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/Role.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/Role.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.entities.enums; +package com.github.gribanoveu.cuddle.dtos.enums; import org.springframework.security.core.GrantedAuthority; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/StatusLevel.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/StatusLevel.java similarity index 75% rename from src/main/java/com/github/gribanoveu/cuddle/entities/enums/StatusLevel.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/enums/StatusLevel.java index 9c86cd5..ab1944a 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/StatusLevel.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/StatusLevel.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.entities.enums; +package com.github.gribanoveu.cuddle.dtos.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/TokenType.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/TokenType.java similarity index 67% rename from src/main/java/com/github/gribanoveu/cuddle/entities/enums/TokenType.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/enums/TokenType.java index cd4f1e7..529a956 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/enums/TokenType.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/TokenType.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.entities.enums; +package com.github.gribanoveu.cuddle.dtos.enums; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/PermissionDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java similarity index 90% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/PermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java index 4cf7010..34ff455 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/PermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.admin; +package com.github.gribanoveu.cuddle.dtos.request.admin; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/UpdatePermissionDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/UpdatePermissionDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java index d7829d4..c8b7783 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/admin/UpdatePermissionDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.admin; +package com.github.gribanoveu.cuddle.dtos.request.admin; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangeEmailDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangeEmailDto.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangeEmailDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangeEmailDto.java index 1f20975..4a5a1cd 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangeEmailDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangeEmailDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java similarity index 94% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java index e08199a..1ba5d19 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/GenerateOtpDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/GenerateOtpDto.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/GenerateOtpDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/GenerateOtpDto.java index b6eaf48..01d973b 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/GenerateOtpDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/GenerateOtpDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/LoginDto.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/LoginDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/LoginDto.java index 7be090e..718ff19 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/LoginDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RefreshTokenDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RefreshTokenDto.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RefreshTokenDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RefreshTokenDto.java index 988ba3e..787aa05 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RefreshTokenDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RefreshTokenDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java similarity index 95% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RegisterDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java index 621d48a..aefe379 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import com.github.gribanoveu.cuddle.utils.validators.MinimalAge; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RestorePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RestorePasswordDto.java similarity index 95% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RestorePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RestorePasswordDto.java index fdf358a..53053f0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/request/auth/RestorePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RestorePasswordDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request.auth; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/ResponseDetails.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java similarity index 88% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/ResponseDetails.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java index b27c79e..421dba0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/ResponseDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.response; +package com.github.gribanoveu.cuddle.dtos.response; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/StatusResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/StatusResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java index 7ce65c6..0d359cb 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/StatusResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.response; +package com.github.gribanoveu.cuddle.dtos.response; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/PermissionsResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java similarity index 85% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/PermissionsResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java index b735985..b439459 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/PermissionsResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.response.auth; +package com.github.gribanoveu.cuddle.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddle.entities.enums.Role; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java similarity index 95% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/TokenResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java index 7064a7e..6f8bd56 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/TokenResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.response.auth; +package com.github.gribanoveu.cuddle.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java similarity index 89% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/UsersResponse.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java index 4913347..766b84c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/dtos/response/auth/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddle.controllers.dtos.response.auth; +package com.github.gribanoveu.cuddle.dtos.response.auth; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.entities.tables.User; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AuthController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java similarity index 63% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AuthController.java rename to src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java index af19337..2840d39 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/AuthController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java @@ -1,9 +1,9 @@ -package com.github.gribanoveu.cuddle.controllers.endpoints.auth; +package com.github.gribanoveu.cuddle.endpoints.anonymous; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.LoginDto; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RefreshTokenDto; -import com.github.gribanoveu.cuddle.controllers.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddle.controllers.facade.auth.AuthControllerFacade; +import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.dtos.request.auth.RefreshTokenDto; +import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddle.controllers.anonymous.AuthenticationControllerFacade; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; @@ -19,18 +19,18 @@ @RequiredArgsConstructor @RequestMapping("/v1/auth") @Tag(name="Аутентификация пользователя", description="Позволяет получить и обновить токен") -public class AuthController { - private final AuthControllerFacade authControllerFacade; +public class AuthenticationController { + private final AuthenticationControllerFacade authenticationControllerFacade; @PostMapping @Operation(summary = "Получить токен", description = "Получение access token и refresh token") public ResponseEntity authenticateUser(@Valid @RequestBody LoginDto request) { - return authControllerFacade.authenticateUser(request); + return authenticationControllerFacade.authenticateUser(request); } @PatchMapping @Operation(summary = "Обновить токен", description = "Получение нового токена на основе refresh token") public ResponseEntity refreshToken(@Valid @RequestBody RefreshTokenDto request) { - return authControllerFacade.refreshToken(request); + return authenticationControllerFacade.refreshToken(request); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java new file mode 100644 index 0000000..ce2dbf8 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java @@ -0,0 +1,44 @@ +package com.github.gribanoveu.cuddle.endpoints.anonymous; + +import com.github.gribanoveu.cuddle.dtos.request.auth.GenerateOtpDto; +import com.github.gribanoveu.cuddle.dtos.request.auth.RegisterDto; +import com.github.gribanoveu.cuddle.dtos.request.auth.RestorePasswordDto; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +/** + * @author Evgeny Gribanov + * @version 22.09.2023 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/v1/account") +@Tag(name="Управление аккаунтом без авторизации", description="Позволяет управлять данными учетной записи") +public class PublicAccountController { + private final PublicAccountControllerFacade publicAccountControllerFacade; + + @PostMapping("/generate-code") + @Operation(summary = "Сгенерировать OTP код") + public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request, HttpServletRequest http) { + return publicAccountControllerFacade.generateOtpCode(request, http); + } + + @PostMapping("/restore-password") + @Operation(summary = "Восстановить пароль через OTP код") + public ResponseEntity restorePassword(@Valid @RequestBody RestorePasswordDto request) { + return publicAccountControllerFacade.restorePasswordByOtp(request); + } + + @PostMapping("/create") + @Operation(summary = "Регистрация нового пользователя") + public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { + return publicAccountControllerFacade.registerUser(request); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/admin/ModeratorController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java similarity index 58% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/admin/ModeratorController.java rename to src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java index 596e68a..7faa6e4 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/admin/ModeratorController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java @@ -1,6 +1,8 @@ -package com.github.gribanoveu.cuddle.controllers.endpoints.admin; +package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.controllers.facade.admin.ModeratorControllerFacade; +import com.github.gribanoveu.cuddle.controllers.secure.ModeratorControllerFacade; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -13,35 +15,47 @@ @RestController @RequiredArgsConstructor @RequestMapping("/v1/moderator") -@Tag(name="Контороллер для модерации", description="Управляет ограничениями пользователя") +@Tag(name="Контроллер для модерации", description="Управляет ограничениями пользователя") public class ModeratorController { private final ModeratorControllerFacade moderatorControllerFacade; + @Operation(summary = "Получить список всех пользователей") + @SecurityRequirement(name = "JWT") @GetMapping("/users-list") public ResponseEntity getAllUsersList(@RequestParam int pageNumber, @RequestParam int pageSize) { return moderatorControllerFacade.getAllUsersList(pageNumber, pageSize); } + @Operation(summary = "Удалить пользователя") + @SecurityRequirement(name = "JWT") @DeleteMapping("/{userId}") // only admin can delete user public ResponseEntity deleteUser(@PathVariable Long userId) { return moderatorControllerFacade.deleteUser(userId); } + @Operation(summary = "Отключить пользователя") + @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/disable") public ResponseEntity disableUser(@PathVariable Long userId) { return moderatorControllerFacade.disableUser(userId); } + @Operation(summary = "Включить пользователя") + @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/enable") public ResponseEntity enableUser(@PathVariable Long userId) { return moderatorControllerFacade.enabledUser(userId); } + @Operation(summary = "Выдать бан пользователю") + @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/ban") public ResponseEntity banUser(@PathVariable Long userId) { return moderatorControllerFacade.banUser(userId); } + @Operation(summary = "Снять бан с пользователя") + @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/mercy") public ResponseEntity mercyUser(@PathVariable Long userId) { return moderatorControllerFacade.mercyUser(userId); diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java new file mode 100644 index 0000000..4129b64 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java @@ -0,0 +1,43 @@ +package com.github.gribanoveu.cuddle.endpoints.secure; + +import com.github.gribanoveu.cuddle.dtos.request.auth.ChangeEmailDto; +import com.github.gribanoveu.cuddle.dtos.request.auth.ChangePasswordDto; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author Evgeny Gribanov + * @version 22.12.2023 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/v1/account") +@Tag(name="Управление аккаунтом с авторизацией", description="Позволяет управлять данными учетной записи") +public class PrivateAccountController { + private final PublicAccountControllerFacade userControllerFacade; + + @Operation(summary = "Сменить Email") + @SecurityRequirement(name = "JWT") + @PatchMapping("/change-email") + public ResponseEntity changeEmail(@Valid @RequestBody ChangeEmailDto request, Authentication auth) { + return userControllerFacade.changeEmail(request, auth); + } + + @Operation(summary = "Сменить пароль") + @SecurityRequirement(name = "JWT") + @PatchMapping("/change-password") + public ResponseEntity changePassword(@Valid @RequestBody ChangePasswordDto request, Authentication auth) { + return userControllerFacade.changePassword(request, auth); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/UserController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java similarity index 62% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/UserController.java rename to src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java index 706f875..fd63515 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/endpoints/auth/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java @@ -1,15 +1,11 @@ -package com.github.gribanoveu.cuddle.controllers.endpoints.auth; +package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.RegisterDto; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.facade.auth.UserControllerFacade; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.controllers.secure.UserControllerFacade; import com.github.gribanoveu.cuddle.entities.tables.User; -import com.github.gribanoveu.cuddle.utils.aspects.LogRequest; -import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; @@ -29,26 +25,16 @@ public class UserController { private final UserControllerFacade userControllerFacade; - @LogRequest - @LogResponse - @GetMapping @Operation(summary = "Получить данные текущего пользователя") @SecurityRequirement(name = "JWT") + @GetMapping public ResponseEntity getUserData(Authentication authentication) { return userControllerFacade.getUserData(authentication); } - @LogRequest - @LogResponse - @PostMapping - @Operation(summary = "Регистрация нового пользователя") - public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { - return userControllerFacade.registerUser(request); - } - - @DeleteMapping - @Operation(summary = "Удалить текущего авторизованного пользователя", description = "Пользователь удаляет сам себя") + @Operation(summary = "Удалить текущего авторизованного пользователя") @SecurityRequirement(name = "JWT") + @DeleteMapping public ResponseEntity deleteUser(Authentication authentication) { return userControllerFacade.deleteUser(authentication); } diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java new file mode 100644 index 0000000..5f13920 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java @@ -0,0 +1,41 @@ +package com.github.gribanoveu.cuddle.endpoints.secure; + +import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +/** + * @author Evgeny Gribanov + * @version 21.12.2023 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/v1/role") +@Tag(name="Контроллер для назначения модераторов", description="Управляет ролями пользователя") +public class UserRoleController { + + @SecurityRequirement(name = "JWT") + @Operation(summary = "Получить роль пользователя") + @GetMapping("/{userId}") + public ResponseEntity getUserRole(@PathVariable Long userId) { + return null; + } + + @SecurityRequirement(name = "JWT") + @Operation(summary = "Обновить роль до модератора") + @PatchMapping("/{userId}") + public ResponseEntity updateToModerator(@PathVariable Long userId) { + return null; + } + + @SecurityRequirement(name = "JWT") + @Operation(summary = "Обновить роль до пользователя") + @DeleteMapping("/{userId}") + public ResponseEntity updateToUser(@PathVariable Long userId) { + return null; + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java index 4fc4d87..ed41cca 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.entities.repositories; -import com.github.gribanoveu.cuddle.entities.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.Role; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java index 6ffb6ae..b64706b 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.entities.services.email; -import com.github.gribanoveu.cuddle.controllers.dtos.data.SimpleEmailObject; +import com.github.gribanoveu.cuddle.dtos.data.SimpleEmailObject; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java index 2dc52a5..7a62c1f 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.entities.services.email; -import com.github.gribanoveu.cuddle.controllers.dtos.data.SimpleEmailObject; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.data.SimpleEmailObject; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import jakarta.mail.MessagingException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java index 8edd7a2..90b0016 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.entities.services.otp; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java index 05010f5..39af974 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.entities.services.permission; -import com.github.gribanoveu.cuddle.entities.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.Role; import org.springframework.transaction.annotation.Transactional; import java.util.List; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java index 9fd5723..558396f 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenService.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.entities.services.token; -import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.dtos.enums.TokenType; import com.github.gribanoveu.cuddle.security.CustomUserDetails; import java.util.Date; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java index 7fb6f9a..a14abc5 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.entities.services.token; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.TokenType; import com.github.gribanoveu.cuddle.security.CustomUserDetails; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java index 88c166b..3179d5a 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.entities.services.user; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.entities.repositories.UserRepository; import com.github.gribanoveu.cuddle.entities.tables.User; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java index 1392922..9233b48 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java @@ -3,7 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.gribanoveu.cuddle.entities.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.Role; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; @@ -46,7 +46,6 @@ public class User { @Column(name = "role") private Role role; - @Column(name = "account_non_expired") private Boolean accountNonExpired = true; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/CredentialEx.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java similarity index 76% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/CredentialEx.java rename to src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java index 69e6f5c..dad017d 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/CredentialEx.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddle.controllers.exeptions; +package com.github.gribanoveu.cuddle.exeptions; -import com.github.gribanoveu.cuddle.controllers.dtos.response.ResponseDetails; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import lombok.Getter; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.BadCredentialsException; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java similarity index 92% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/GlobalExceptionHandler.java rename to src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java index 2f02ea6..edd1385 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java @@ -1,10 +1,10 @@ -package com.github.gribanoveu.cuddle.controllers.exeptions; +package com.github.gribanoveu.cuddle.exeptions; import com.github.gribanoveu.cuddle.constants.ValidationMessages; -import com.github.gribanoveu.cuddle.controllers.dtos.response.ResponseDetails; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import jakarta.validation.ConstraintViolationException; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java similarity index 82% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java index 000c3b8..b4656f9 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AccessDeniedEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java similarity index 82% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java index 23f9f00..1057e9c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java @@ -1,8 +1,8 @@ -package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java similarity index 94% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java index 828bdbc..cd06b4f 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/AuthenticationFailureEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.exeptions.entrypoint; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.ServletException; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java similarity index 85% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java rename to src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java index e6c67ea..1070483 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -1,7 +1,7 @@ -package com.github.gribanoveu.cuddle.controllers.exeptions.entrypoint; +package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.controllers.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.entities.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -14,8 +14,6 @@ import java.io.IOException; -import static com.github.gribanoveu.cuddle.entities.enums.ResponseCode.*; - /** * @author Evgeny Gribanov * @version 06.09.2023 diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryption.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java similarity index 97% rename from src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryption.java rename to src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java index 190aa49..3b449c4 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryption.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java @@ -17,7 +17,7 @@ */ @Component @RequiredArgsConstructor -public class RSAEncryption { +public class RSAEncryptionUtils { private static final String ALGORITHM = "RSA"; public String encrypt(String data, PublicKey publicKey) throws Exception { diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java index d404889..7a9edf0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java @@ -2,8 +2,8 @@ import com.github.gribanoveu.cuddle.config.RsaProperties; import com.github.gribanoveu.cuddle.constants.RegexpFormat; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.entities.enums.ResponseCode; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -13,10 +13,6 @@ import java.security.interfaces.RSAPublicKey; import java.time.Duration; import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -31,7 +27,7 @@ public class RefreshTokenUtils { @Value("${time-variable.refreshTokenLifetime}") private Duration refreshTokenLifetime; private final RsaProperties rsaKeys; - private final RSAEncryption rsaEncryption; + private final RSAEncryptionUtils rsaEncryptionUtils; public String generateEncryptedRefreshToken(String email) { RSAPublicKey publicKey = rsaKeys.publicKey(); @@ -39,7 +35,7 @@ public String generateEncryptedRefreshToken(String email) { final String TOKEN_SEPARATOR = "|"; // admin@email.com|1698159942361 var refreshTokenExpire = Instant.now().plus(refreshTokenLifetime).toEpochMilli(); var refreshToken = email + TOKEN_SEPARATOR + refreshTokenExpire; - return rsaEncryption.encrypt(refreshToken, publicKey); + return rsaEncryptionUtils.encrypt(refreshToken, publicKey); } catch (Exception e) { throw new CredentialEx(ResponseCode.TOKEN_NOT_VALID); } @@ -48,7 +44,7 @@ public String generateEncryptedRefreshToken(String email) { public String validateRefreshTokenAndExtractEmail(String token) { RSAPrivateKey privateKey = rsaKeys.privateKey(); try { - var tokenValue = rsaEncryption.decrypt(token, privateKey); + var tokenValue = rsaEncryptionUtils.decrypt(token, privateKey); checkTokenValidity(tokenValue); return extractEmailFromToken(tokenValue); } catch (Exception e) { diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java b/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java index eb52cc3..d271739 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.utils.emails; import com.github.gribanoveu.cuddle.constants.EmailMessages; -import com.github.gribanoveu.cuddle.controllers.dtos.data.SimpleEmailObject; +import com.github.gribanoveu.cuddle.dtos.data.SimpleEmailObject; import java.time.Duration; import java.util.Map; diff --git a/src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java b/src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java index af88ace..c69c4e1 100644 --- a/src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/base/BaseMockMvcTest.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.base; -import com.github.gribanoveu.cuddle.entities.enums.TokenType; +import com.github.gribanoveu.cuddle.dtos.enums.TokenType; import com.github.gribanoveu.cuddle.entities.services.token.TokenService; import com.github.gribanoveu.cuddle.security.CustomUserDetails; import com.github.gribanoveu.cuddle.security.CustomUserDetailsService; diff --git a/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java b/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java index 41c1ffa..1efacd1 100644 --- a/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.entities.services.implementation; import com.github.gribanoveu.cuddle.base.BaseMockMvcTest; -import com.github.gribanoveu.cuddle.controllers.exeptions.CredentialEx; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.entities.services.token.TokenService; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java b/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java index 4ff5450..580a917 100644 --- a/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.utils; -import com.github.gribanoveu.cuddle.controllers.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; From 046b14c615517b32cecd41827046b3fcdf17c279 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 10:17:54 +0300 Subject: [PATCH 23/34] fix imports Took 2 minutes --- .../gribanoveu/cuddle/config/SecurityConfig.java | 3 +++ .../anonymous/AuthenticationControllerFacade.java | 2 +- .../anonymous/PublicAccountControllerFacade.java | 8 ++++---- .../controllers/secure/ModeratorControllerFacade.java | 4 ++-- .../controllers/secure/UserControllerFacade.java | 11 +---------- .../cuddle/dtos/request/auth/ChangePasswordDto.java | 3 ++- .../cuddle/dtos/request/auth/RegisterDto.java | 4 +++- .../cuddle/dtos/response/auth/UsersResponse.java | 3 ++- .../endpoints/anonymous/AuthenticationController.java | 2 +- .../endpoints/anonymous/PublicAccountController.java | 7 +++++-- .../endpoints/secure/PrivateAccountController.java | 2 +- .../cuddle/endpoints/secure/UserController.java | 7 +++++-- .../entities/services/email/EmailServiceImpl.java | 2 +- .../entities/services/otp/RedisOtpServiceImpl.java | 2 +- .../entities/services/token/TokenServiceImpl.java | 2 +- .../entities/services/user/UserServiceImpl.java | 2 +- .../gribanoveu/cuddle/exeptions/CredentialEx.java | 2 +- .../cuddle/exeptions/GlobalExceptionHandler.java | 4 ++-- .../exeptions/entrypoint/AccessDeniedEntryPoint.java | 2 +- .../exeptions/entrypoint/AuthErrorEntryPoint.java | 2 +- .../exeptions/entrypoint/ServerErrorEntryPoint.java | 4 +++- .../gribanoveu/cuddle/security/CustomUserDetails.java | 5 ++++- .../gribanoveu/cuddle/utils/RSAEncryptionUtils.java | 3 ++- .../gribanoveu/cuddle/utils/RefreshTokenUtils.java | 2 +- .../services/implementation/TokenServiceImplTest.java | 2 +- 25 files changed, 50 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java index 1ccab5f..c0d3fc3 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java @@ -21,6 +21,9 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; +import static com.github.gribanoveu.cuddle.dtos.enums.Role.ADMIN; +import static com.github.gribanoveu.cuddle.dtos.enums.Role.MODERATOR; + /** * @author Evgeny Gribanov * @version 28.08.2023 diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java index cfec2a3..8e5058a 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java @@ -1,10 +1,10 @@ package com.github.gribanoveu.cuddle.controllers.anonymous; import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.dtos.enums.TokenType; import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; import com.github.gribanoveu.cuddle.dtos.request.auth.RefreshTokenDto; import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddle.dtos.enums.TokenType; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.token.TokenService; import com.github.gribanoveu.cuddle.security.CustomUserDetails; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java index 7a8a0a0..d11eee5 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java @@ -1,16 +1,16 @@ package com.github.gribanoveu.cuddle.controllers.anonymous; import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.dtos.request.auth.*; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.entities.tables.User; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; -import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.otp.RedisOtpService; import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import com.github.gribanoveu.cuddle.entities.tables.User; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.utils.JsonUtils; import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; import jakarta.servlet.http.HttpServletRequest; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java index bf1ae98..e35e3a8 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java @@ -1,9 +1,9 @@ package com.github.gribanoveu.cuddle.controllers.secure; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.dtos.response.auth.UsersResponse; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.dtos.response.auth.UsersResponse; import com.github.gribanoveu.cuddle.entities.services.user.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java index c1c1acb..39e8efa 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java @@ -1,26 +1,17 @@ package com.github.gribanoveu.cuddle.controllers.secure; -import com.github.gribanoveu.cuddle.constants.EmailMessages; -import com.github.gribanoveu.cuddle.dtos.request.auth.RegisterDto; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; -import com.github.gribanoveu.cuddle.dtos.enums.Role; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.user.UserService; import com.github.gribanoveu.cuddle.entities.tables.User; -import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java index 1ba5d19..e0f0fa7 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java @@ -4,7 +4,8 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; -import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.NOT_BLANK_EXCEPTION_MESSAGE; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.SIZE_EXCEPTION_MESSAGE; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java index aefe379..761fc1c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java @@ -2,7 +2,9 @@ import com.github.gribanoveu.cuddle.utils.validators.MinimalAge; import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.*; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java index 766b84c..26c344e 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java @@ -4,10 +4,11 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.entities.tables.User; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.http.HttpStatus; -import io.swagger.v3.oas.annotations.media.Schema; + import java.time.LocalDateTime; import java.util.Collection; diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java index 2840d39..35d71a8 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java @@ -1,9 +1,9 @@ package com.github.gribanoveu.cuddle.endpoints.anonymous; +import com.github.gribanoveu.cuddle.controllers.anonymous.AuthenticationControllerFacade; import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; import com.github.gribanoveu.cuddle.dtos.request.auth.RefreshTokenDto; import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; -import com.github.gribanoveu.cuddle.controllers.anonymous.AuthenticationControllerFacade; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java index ce2dbf8..fbabe36 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java @@ -1,17 +1,20 @@ package com.github.gribanoveu.cuddle.endpoints.anonymous; +import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; import com.github.gribanoveu.cuddle.dtos.request.auth.GenerateOtpDto; import com.github.gribanoveu.cuddle.dtos.request.auth.RegisterDto; import com.github.gribanoveu.cuddle.dtos.request.auth.RestorePasswordDto; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +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.RestController; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java index 4129b64..c8b5648 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java @@ -1,9 +1,9 @@ package com.github.gribanoveu.cuddle.endpoints.secure; +import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; import com.github.gribanoveu.cuddle.dtos.request.auth.ChangeEmailDto; import com.github.gribanoveu.cuddle.dtos.request.auth.ChangePasswordDto; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java index fd63515..69461ee 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.controllers.secure.UserControllerFacade; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.entities.tables.User; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; @@ -9,7 +9,10 @@ import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java index 7a62c1f..6550e0e 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.entities.services.email; import com.github.gribanoveu.cuddle.dtos.data.SimpleEmailObject; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import jakarta.mail.MessagingException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java index 90b0016..a271732 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/otp/RedisOtpServiceImpl.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.entities.services.otp; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java index a14abc5..1a4f6bd 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/token/TokenServiceImpl.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.entities.services.token; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.TokenType; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.security.CustomUserDetails; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java index 3179d5a..0c11990 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java @@ -1,9 +1,9 @@ package com.github.gribanoveu.cuddle.entities.services.user; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.entities.repositories.UserRepository; import com.github.gribanoveu.cuddle.entities.tables.User; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java index dad017d..6d7145f 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/CredentialEx.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.exeptions; -import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; import lombok.Getter; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.BadCredentialsException; diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java index edd1385..6dada94 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java @@ -1,10 +1,10 @@ package com.github.gribanoveu.cuddle.exeptions; import com.github.gribanoveu.cuddle.constants.ValidationMessages; -import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import jakarta.validation.ConstraintViolationException; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java index b4656f9..57fa438 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AccessDeniedEntryPoint.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java index 1057e9c..fc938f0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthErrorEntryPoint.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java index 1070483..b142d3c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -1,7 +1,7 @@ package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -14,6 +14,8 @@ import java.io.IOException; +import static com.github.gribanoveu.cuddle.dtos.enums.ResponseCode.*; + /** * @author Evgeny Gribanov * @version 06.09.2023 diff --git a/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java b/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java index 06749dc..cf576ff 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddle/security/CustomUserDetails.java @@ -5,7 +5,10 @@ import org.springframework.security.core.userdetails.UserDetails; import java.io.Serial; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java index 3b449c4..0d95f42 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java @@ -4,7 +4,8 @@ import org.springframework.stereotype.Component; import javax.crypto.Cipher; -import java.security.*; +import java.security.PrivateKey; +import java.security.PublicKey; /** * @author Evgeny Gribanov diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java index 7a9edf0..1f4f0f8 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RefreshTokenUtils.java @@ -2,8 +2,8 @@ import com.github.gribanoveu.cuddle.config.RsaProperties; import com.github.gribanoveu.cuddle.constants.RegexpFormat; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; diff --git a/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java b/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java index 1efacd1..dac575e 100644 --- a/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/entities/services/implementation/TokenServiceImplTest.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.entities.services.implementation; import com.github.gribanoveu.cuddle.base.BaseMockMvcTest; -import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import com.github.gribanoveu.cuddle.entities.services.token.TokenService; +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; From 6925651b24c9aec1e4967fad15362b03aced9bed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 12:27:53 +0300 Subject: [PATCH 24/34] add set moderator controller and refactor code Took 1 hour 35 minutes --- .../cuddle/config/SecurityConfig.java | 4 +- .../cuddle/constants/RegexpFormat.java | 1 - ...java => AuthenticationControllerImpl.java} | 6 +- ....java => PublicAccountControllerImpl.java} | 4 +- ...cade.java => ModeratorControllerImpl.java} | 4 +- ...lerFacade.java => UserControllerImpl.java} | 6 +- .../secure/UserRoleControllerImpl.java | 43 +++++++++++++ .../cuddle/dtos/enums/ResponseCode.java | 60 ++++++------------- .../request/{auth => }/ChangeEmailDto.java | 2 +- .../request/{auth => }/ChangePasswordDto.java | 2 +- .../request/{auth => }/GenerateOtpDto.java | 2 +- .../dtos/request/{auth => }/LoginDto.java | 2 +- .../request/{auth => }/RefreshTokenDto.java | 2 +- .../dtos/request/{auth => }/RegisterDto.java | 2 +- .../{auth => }/RestorePasswordDto.java | 2 +- .../request/admin/UpdatePermissionDto.java | 24 -------- .../cuddle/dtos/response/ResponseDetails.java | 6 ++ .../cuddle/dtos/response/StatusResponse.java | 4 ++ .../response/auth/PermissionsResponse.java | 36 ----------- .../anonymous/AuthenticationController.java | 12 ++-- .../anonymous/PublicAccountController.java | 16 ++--- .../endpoints/secure/ModeratorController.java | 16 ++--- .../secure/PrivateAccountController.java | 8 +-- .../endpoints/secure/UserController.java | 8 +-- .../endpoints/secure/UserRoleController.java | 15 ++--- .../repositories/PermissionRepository.java | 21 ------- .../entities/services/email/EmailService.java | 1 - .../services/email/EmailServiceImpl.java | 15 ----- .../permission/PermissionService.java | 21 ------- .../entities/services/user/UserService.java | 3 +- .../services/user/UserServiceImpl.java | 13 ++-- .../exeptions/GlobalExceptionHandler.java | 10 ++++ .../AuthenticationFailureEntryPoint.java | 3 +- .../entrypoint/ServerErrorEntryPoint.java | 2 +- .../cuddle/utils/RSAEncryptionUtils.java | 15 +++-- .../utils/aspects/RequestLoggingAspect.java | 6 +- .../cuddle/utils/JsonUtilsTest.java | 2 +- 37 files changed, 161 insertions(+), 238 deletions(-) rename src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/{AuthenticationControllerFacade.java => AuthenticationControllerImpl.java} (94%) rename src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/{PublicAccountControllerFacade.java => PublicAccountControllerImpl.java} (98%) rename src/main/java/com/github/gribanoveu/cuddle/controllers/secure/{ModeratorControllerFacade.java => ModeratorControllerImpl.java} (93%) rename src/main/java/com/github/gribanoveu/cuddle/controllers/secure/{UserControllerFacade.java => UserControllerImpl.java} (81%) create mode 100644 src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserRoleControllerImpl.java rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/ChangeEmailDto.java (93%) rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/ChangePasswordDto.java (95%) rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/GenerateOtpDto.java (93%) rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/LoginDto.java (94%) rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/RefreshTokenDto.java (90%) rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/RegisterDto.java (96%) rename src/main/java/com/github/gribanoveu/cuddle/dtos/request/{auth => }/RestorePasswordDto.java (96%) delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java diff --git a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java index c0d3fc3..4108914 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java @@ -49,7 +49,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // anonymous scope .requestMatchers( HttpMethod.POST, "*/auth").anonymous() // issue token .requestMatchers( HttpMethod.PATCH, "*/auth").anonymous() // refresh token - .requestMatchers(HttpMethod.POST, "*/user").anonymous() // register + .requestMatchers(HttpMethod.POST, "*/account/create").anonymous() // register .requestMatchers(HttpMethod.POST, "*/account/generate-code").anonymous() .requestMatchers(HttpMethod.POST, "*/account/restore-password").anonymous() @@ -59,6 +59,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // authenticated scope .requestMatchers("*/users/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) .requestMatchers("*/moderator/**").hasAnyAuthority(ADMIN.scope(), MODERATOR.scope()) + .requestMatchers("*/role/**").hasAnyAuthority(ADMIN.scope()) + .anyRequest().authenticated() ) .sessionManagement(manager -> manager diff --git a/src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java b/src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java index 0a689d9..81cf2b8 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/RegexpFormat.java @@ -6,7 +6,6 @@ */ public class RegexpFormat { public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - public static final String PERMISSION_PATTERN = "^[A-Z]{2}_[A-Z_]+$"; public static final String OTP_PATTERN = "^\\d{6}$"; public static final String BIRTHDAY_PATTERN = "^(19\\d{2}|20\\d{2}|2100)-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$"; public static final String UNIX_DATE_TOKEN_PATTERN = "\\|(\\d+)"; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerImpl.java similarity index 94% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerImpl.java index 8e5058a..5f3dd88 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/AuthenticationControllerImpl.java @@ -2,8 +2,8 @@ import com.github.gribanoveu.cuddle.constants.EmailMessages; import com.github.gribanoveu.cuddle.dtos.enums.TokenType; -import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; -import com.github.gribanoveu.cuddle.dtos.request.auth.RefreshTokenDto; +import com.github.gribanoveu.cuddle.dtos.request.LoginDto; +import com.github.gribanoveu.cuddle.dtos.request.RefreshTokenDto; import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.token.TokenService; @@ -28,7 +28,7 @@ @Slf4j @Service @RequiredArgsConstructor -public class AuthenticationControllerFacade { +public class AuthenticationControllerImpl { @Value("${time-variable.accessTokenLifetime}") private Duration accessTokenLifetime; private final TokenService tokenService; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java similarity index 98% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java index d11eee5..8d32dd2 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java @@ -4,7 +4,7 @@ import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.Role; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; -import com.github.gribanoveu.cuddle.dtos.request.auth.*; +import com.github.gribanoveu.cuddle.dtos.request.*; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.otp.RedisOtpService; @@ -34,7 +34,7 @@ @Slf4j @Service @RequiredArgsConstructor -public class PublicAccountControllerFacade { +public class PublicAccountControllerImpl { @Value("${time-variable.otpCodeLifetime}") private Duration otpCodeLifeTime; private final UserService userService; diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java index e35e3a8..b948fc9 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java @@ -7,7 +7,6 @@ import com.github.gribanoveu.cuddle.entities.services.user.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import static org.springframework.http.HttpStatus.OK; @@ -18,9 +17,8 @@ */ @Service @RequiredArgsConstructor -public class ModeratorControllerFacade { +public class ModeratorControllerImpl { private final UserService userService; - private final PasswordEncoder passwordEncoder; public ResponseEntity getAllUsersList(int pageNumber, int pageSize) { return ResponseEntity.ok(UsersResponse.create(OK, userService.getAllUsers(pageNumber, pageSize))); diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerImpl.java similarity index 81% rename from src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java rename to src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerImpl.java index 39e8efa..b552247 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerFacade.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerImpl.java @@ -3,14 +3,12 @@ import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; -import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.user.UserService; import com.github.gribanoveu.cuddle.entities.tables.User; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; /** @@ -20,10 +18,8 @@ @Slf4j @Service @RequiredArgsConstructor -public class UserControllerFacade { +public class UserControllerImpl { private final UserService userService; - private final PasswordEncoder passwordEncoder; - private final EmailService emailService; public ResponseEntity getUserData(Authentication authentication) { var userData = userService.findUserByEmail(authentication.getName()); diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserRoleControllerImpl.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserRoleControllerImpl.java new file mode 100644 index 0000000..0382111 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserRoleControllerImpl.java @@ -0,0 +1,43 @@ +package com.github.gribanoveu.cuddle.controllers.secure; + +import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.Role; +import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; +import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; +import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * @author Evgeny Gribanov + * @version 22.12.2023 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UserRoleControllerImpl { + private final UserService userService; + + public ResponseEntity getUserRole(Long userId) { + var userRole = userService.findUserById(userId).getRole().getAuthority(); + return ResponseEntity.ok(StatusResponse.create( + new ResponseDetails(userRole), StatusLevel.SUCCESS)); + } + + public ResponseEntity updateToModerator(Long userId) { + var user = userService.findUserById(userId); + userService.updateRole(user, Role.MODERATOR); + return ResponseEntity.ok(StatusResponse.create( + ResponseCode.PERMISSION_UPDATED_MODERATOR, StatusLevel.SUCCESS)); + } + + public ResponseEntity updateToUser(Long userId) { + var user = userService.findUserById(userId); + userService.updateRole(user, Role.USER); + return ResponseEntity.ok(StatusResponse.create( + ResponseCode.PERMISSION_UPDATED_USER, StatusLevel.SUCCESS)); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java index 23e2c4c..cad08ad 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java @@ -20,7 +20,7 @@ public enum ResponseCode { ACCESS_DENIED( "AUT-101", "Access denied", - "Access denied. Please check your credentials and make sure you have the required access rights", + "Please check your credentials and make sure you have the required access rights", HttpStatus.FORBIDDEN ), UNAUTHORIZED( @@ -32,7 +32,7 @@ public enum ResponseCode { BAD_CREDENTIAL( "AUT-103", "Invalid credentials", - "Incorrect credentials. Please verify that the information entered is correct and try again. If you have forgotten your credentials, please use the password recovery feature", + "Please verify that the information entered is correct and try again. If you have forgotten your credentials, please use the password recovery feature", HttpStatus.BAD_REQUEST ), MISSING_PARAM( @@ -44,13 +44,13 @@ public enum ResponseCode { TOKEN_NOT_VALID( "AUT-105", "Invalid token", - "Invalid token. Please make sure you are using a valid token and try again", + "Please make sure you are using a valid token and try again", HttpStatus.UNAUTHORIZED ), VALIDATION_ERROR( "AUT-106", "Validation error", - "Validation Error. Please check that the data is in the correct format and try again", + "Please check that the data is in the correct format and try again", HttpStatus.BAD_REQUEST ), VALIDATION_ERROR_DETAIL( @@ -77,12 +77,6 @@ public enum ResponseCode { "Your account has been disabled contact support to find out why", HttpStatus.UNAUTHORIZED ), - AGE_NOT_VALID( - "AUT-111", - "Age not valid", - "Age must be at least 18 years old, or have expected format", - HttpStatus.BAD_REQUEST - ), PASSWORD_UPDATED( "AUT-200", "Password updated", @@ -161,65 +155,47 @@ public enum ResponseCode { "User not found. Please make sure you have entered the correct email and try again", HttpStatus.NOT_FOUND ), - USER_DEFAULT_PASSWORD( - "AUT-405", - "Set default password", - "Default password has been successfully set for the user", - HttpStatus.OK - ), USER_UPDATED( - "AUT-406", + "AUT-405", "User updated successfully", "User has been successfully updated", HttpStatus.OK ), USER_ALREADY_EXIST( - "AUT-407", + "AUT-406", "User already exists", "User already exists. Please make sure you have entered the correct email and try again", HttpStatus.CONFLICT ), USER_BANNED( - "AUT-408", + "AUT-407", "User banned", "User has been successfully banned", HttpStatus.OK ), USER_UN_BANNED( - "AUT-409", + "AUT-408", "User unbanned", "User has been successfully unbanned", HttpStatus.OK ), - PERMISSION_CREATED( + PERMISSION_UPDATED_MODERATOR( "AUT-500", - "Permission created", - "Permission has been successfully created", + "Permission updated", + "The user is now a moderator", HttpStatus.OK ), - PERMISSION_DELETED( + PERMISSION_UPDATED_USER( "AUT-501", - "Permission deleted", - "Permission has been successfully deleted", - HttpStatus.OK - ), - PERMISSION_UPDATED( - "AUT-502", "Permission updated", - "Permission has been successfully updated", + "The user is now a user", HttpStatus.OK ), - PERMISSION_EXIST( - "AUT-504", - "Permission already exists", - "Permission already exists. Please make sure you have entered the correct permission name and try again", - HttpStatus.CONFLICT - ), - PERMISSION_NOT_EXIST( - "AUT-505", - "Permission not found", - "Permission not found. Please make sure you have entered the correct permission name and try again", - HttpStatus.NOT_FOUND + SEND_MESSAGE( + "INF-100", + "Information message", + "%s", + HttpStatus.OK ); private final String code; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangeEmailDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/ChangeEmailDto.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangeEmailDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/ChangeEmailDto.java index 4a5a1cd..7418290 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangeEmailDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/ChangeEmailDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/ChangePasswordDto.java similarity index 95% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/ChangePasswordDto.java index e0f0fa7..ab4045e 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/ChangePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/ChangePasswordDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/GenerateOtpDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/GenerateOtpDto.java similarity index 93% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/GenerateOtpDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/GenerateOtpDto.java index 01d973b..917a593 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/GenerateOtpDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/GenerateOtpDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/LoginDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/LoginDto.java similarity index 94% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/LoginDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/LoginDto.java index 718ff19..c2a8608 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/LoginDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/LoginDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RefreshTokenDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RefreshTokenDto.java similarity index 90% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RefreshTokenDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/RefreshTokenDto.java index 787aa05..d6b6342 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RefreshTokenDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RefreshTokenDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RegisterDto.java similarity index 96% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/RegisterDto.java index 761fc1c..c2af973 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RegisterDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RegisterDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import com.github.gribanoveu.cuddle.utils.validators.MinimalAge; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RestorePasswordDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestorePasswordDto.java similarity index 96% rename from src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RestorePasswordDto.java rename to src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestorePasswordDto.java index 53053f0..0746c31 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/auth/RestorePasswordDto.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestorePasswordDto.java @@ -1,4 +1,4 @@ -package com.github.gribanoveu.cuddle.dtos.request.auth; +package com.github.gribanoveu.cuddle.dtos.request; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java deleted file mode 100644 index c8b7783..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/UpdatePermissionDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.github.gribanoveu.cuddle.dtos.request.admin; - -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.Pattern; -import jakarta.validation.constraints.Size; - -import static com.github.gribanoveu.cuddle.constants.RegexpFormat.PERMISSION_PATTERN; -import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; - -/** - * @author Evgeny Gribanov - * @version 26.09.2023 - */ -public record UpdatePermissionDto( - @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) - @Pattern(regexp = PERMISSION_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) - @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) - String permissionName, - - @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) - @Pattern(regexp = PERMISSION_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) - @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) - String newName -) {} diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java index 421dba0..3393cee 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/ResponseDetails.java @@ -31,4 +31,10 @@ public ResponseDetails(ResponseCode responseCode, String message) { this.message = message; this.type = responseCode.getType(); } + + public ResponseDetails(String message) { + this.code = ResponseCode.SEND_MESSAGE.getCode(); + this.type = ResponseCode.SEND_MESSAGE.getType(); + this.message = message; + } } \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java index 0d359cb..402a9d2 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/StatusResponse.java @@ -35,6 +35,10 @@ public static StatusResponse create(Collection responseDetails, return new StatusResponse(LocalDateTime.now(), status, responseDetails); } + public static StatusResponse create(ResponseDetails responseDetails, StatusLevel status) { + return new StatusResponse(LocalDateTime.now(), status, Collections.singletonList(responseDetails)); + } + public static StatusResponse create(ResponseCode responseCode, StatusLevel status) { return new StatusResponse(LocalDateTime.now(), status, Collections.singletonList(new ResponseDetails(responseCode))); diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java deleted file mode 100644 index b439459..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/PermissionsResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.github.gribanoveu.cuddle.dtos.response.auth; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.github.gribanoveu.cuddle.dtos.enums.Role; -import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.springframework.http.HttpStatus; - -import java.time.LocalDateTime; -import java.util.Collection; - -/** - * @author Evgeny Gribanov - * @version 26.09.2023 - */ -@Data -@AllArgsConstructor -@JsonInclude(JsonInclude.Include.NON_NULL) -public class PermissionsResponse { - @Schema(description = "Время выполнения запроса") - @JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Europe/Moscow") - private LocalDateTime timestamp; - - @Schema(description = "Уровень статуса запроса", defaultValue = "INFO") - private StatusLevel status; - - @Schema(description = "Информация о ролях пользователя") - private Collection permissions; - - public static PermissionsResponse create(HttpStatus status, Collection permissions) { - return new PermissionsResponse(LocalDateTime.now(), StatusLevel.SUCCESS, permissions); - } -} diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java index 35d71a8..e3b481a 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.endpoints.anonymous; -import com.github.gribanoveu.cuddle.controllers.anonymous.AuthenticationControllerFacade; -import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; -import com.github.gribanoveu.cuddle.dtos.request.auth.RefreshTokenDto; +import com.github.gribanoveu.cuddle.controllers.anonymous.AuthenticationControllerImpl; +import com.github.gribanoveu.cuddle.dtos.request.LoginDto; +import com.github.gribanoveu.cuddle.dtos.request.RefreshTokenDto; import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -20,17 +20,17 @@ @RequestMapping("/v1/auth") @Tag(name="Аутентификация пользователя", description="Позволяет получить и обновить токен") public class AuthenticationController { - private final AuthenticationControllerFacade authenticationControllerFacade; + private final AuthenticationControllerImpl authenticationControllerImpl; @PostMapping @Operation(summary = "Получить токен", description = "Получение access token и refresh token") public ResponseEntity authenticateUser(@Valid @RequestBody LoginDto request) { - return authenticationControllerFacade.authenticateUser(request); + return authenticationControllerImpl.authenticateUser(request); } @PatchMapping @Operation(summary = "Обновить токен", description = "Получение нового токена на основе refresh token") public ResponseEntity refreshToken(@Valid @RequestBody RefreshTokenDto request) { - return authenticationControllerFacade.refreshToken(request); + return authenticationControllerImpl.refreshToken(request); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java index fbabe36..a77a1b3 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java @@ -1,9 +1,9 @@ package com.github.gribanoveu.cuddle.endpoints.anonymous; -import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; -import com.github.gribanoveu.cuddle.dtos.request.auth.GenerateOtpDto; -import com.github.gribanoveu.cuddle.dtos.request.auth.RegisterDto; -import com.github.gribanoveu.cuddle.dtos.request.auth.RestorePasswordDto; +import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerImpl; +import com.github.gribanoveu.cuddle.dtos.request.GenerateOtpDto; +import com.github.gribanoveu.cuddle.dtos.request.RegisterDto; +import com.github.gribanoveu.cuddle.dtos.request.RestorePasswordDto; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -25,23 +25,23 @@ @RequestMapping("/v1/account") @Tag(name="Управление аккаунтом без авторизации", description="Позволяет управлять данными учетной записи") public class PublicAccountController { - private final PublicAccountControllerFacade publicAccountControllerFacade; + private final PublicAccountControllerImpl publicAccountControllerImpl; @PostMapping("/generate-code") @Operation(summary = "Сгенерировать OTP код") public ResponseEntity generateOtpCode(@Valid @RequestBody GenerateOtpDto request, HttpServletRequest http) { - return publicAccountControllerFacade.generateOtpCode(request, http); + return publicAccountControllerImpl.generateOtpCode(request, http); } @PostMapping("/restore-password") @Operation(summary = "Восстановить пароль через OTP код") public ResponseEntity restorePassword(@Valid @RequestBody RestorePasswordDto request) { - return publicAccountControllerFacade.restorePasswordByOtp(request); + return publicAccountControllerImpl.restorePasswordByOtp(request); } @PostMapping("/create") @Operation(summary = "Регистрация нового пользователя") public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { - return publicAccountControllerFacade.registerUser(request); + return publicAccountControllerImpl.registerUser(request); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java index 7faa6e4..d9a2995 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.controllers.secure.ModeratorControllerFacade; +import com.github.gribanoveu.cuddle.controllers.secure.ModeratorControllerImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; @@ -17,47 +17,47 @@ @RequestMapping("/v1/moderator") @Tag(name="Контроллер для модерации", description="Управляет ограничениями пользователя") public class ModeratorController { - private final ModeratorControllerFacade moderatorControllerFacade; + private final ModeratorControllerImpl moderatorControllerImpl; @Operation(summary = "Получить список всех пользователей") @SecurityRequirement(name = "JWT") @GetMapping("/users-list") public ResponseEntity getAllUsersList(@RequestParam int pageNumber, @RequestParam int pageSize) { - return moderatorControllerFacade.getAllUsersList(pageNumber, pageSize); + return moderatorControllerImpl.getAllUsersList(pageNumber, pageSize); } @Operation(summary = "Удалить пользователя") @SecurityRequirement(name = "JWT") @DeleteMapping("/{userId}") // only admin can delete user public ResponseEntity deleteUser(@PathVariable Long userId) { - return moderatorControllerFacade.deleteUser(userId); + return moderatorControllerImpl.deleteUser(userId); } @Operation(summary = "Отключить пользователя") @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/disable") public ResponseEntity disableUser(@PathVariable Long userId) { - return moderatorControllerFacade.disableUser(userId); + return moderatorControllerImpl.disableUser(userId); } @Operation(summary = "Включить пользователя") @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/enable") public ResponseEntity enableUser(@PathVariable Long userId) { - return moderatorControllerFacade.enabledUser(userId); + return moderatorControllerImpl.enabledUser(userId); } @Operation(summary = "Выдать бан пользователю") @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/ban") public ResponseEntity banUser(@PathVariable Long userId) { - return moderatorControllerFacade.banUser(userId); + return moderatorControllerImpl.banUser(userId); } @Operation(summary = "Снять бан с пользователя") @SecurityRequirement(name = "JWT") @PatchMapping("/{userId}/mercy") public ResponseEntity mercyUser(@PathVariable Long userId) { - return moderatorControllerFacade.mercyUser(userId); + return moderatorControllerImpl.mercyUser(userId); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java index c8b5648..1c46433 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/PrivateAccountController.java @@ -1,8 +1,8 @@ package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerFacade; -import com.github.gribanoveu.cuddle.dtos.request.auth.ChangeEmailDto; -import com.github.gribanoveu.cuddle.dtos.request.auth.ChangePasswordDto; +import com.github.gribanoveu.cuddle.controllers.anonymous.PublicAccountControllerImpl; +import com.github.gribanoveu.cuddle.dtos.request.ChangeEmailDto; +import com.github.gribanoveu.cuddle.dtos.request.ChangePasswordDto; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; @@ -25,7 +25,7 @@ @RequestMapping("/v1/account") @Tag(name="Управление аккаунтом с авторизацией", description="Позволяет управлять данными учетной записи") public class PrivateAccountController { - private final PublicAccountControllerFacade userControllerFacade; + private final PublicAccountControllerImpl userControllerFacade; @Operation(summary = "Сменить Email") @SecurityRequirement(name = "JWT") diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java index 69461ee..640452c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserController.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.controllers.secure.UserControllerFacade; +import com.github.gribanoveu.cuddle.controllers.secure.UserControllerImpl; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.entities.tables.User; import io.swagger.v3.oas.annotations.Operation; @@ -26,19 +26,19 @@ @RequestMapping("/v1/user") @Tag(name="Контроллер пользователя", description="Юзер управляет своим аккаунтом") public class UserController { - private final UserControllerFacade userControllerFacade; + private final UserControllerImpl userControllerImpl; @Operation(summary = "Получить данные текущего пользователя") @SecurityRequirement(name = "JWT") @GetMapping public ResponseEntity getUserData(Authentication authentication) { - return userControllerFacade.getUserData(authentication); + return userControllerImpl.getUserData(authentication); } @Operation(summary = "Удалить текущего авторизованного пользователя") @SecurityRequirement(name = "JWT") @DeleteMapping public ResponseEntity deleteUser(Authentication authentication) { - return userControllerFacade.deleteUser(authentication); + return userControllerImpl.deleteUser(authentication); } } \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java index 5f13920..0834f37 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/UserRoleController.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.endpoints.secure; -import com.github.gribanoveu.cuddle.dtos.response.auth.TokenResponse; +import com.github.gribanoveu.cuddle.controllers.secure.UserRoleControllerImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; @@ -17,25 +17,26 @@ @RequestMapping("/v1/role") @Tag(name="Контроллер для назначения модераторов", description="Управляет ролями пользователя") public class UserRoleController { + private final UserRoleControllerImpl userRoleControllerImpl; @SecurityRequirement(name = "JWT") @Operation(summary = "Получить роль пользователя") @GetMapping("/{userId}") - public ResponseEntity getUserRole(@PathVariable Long userId) { - return null; + public ResponseEntity getUserRole(@PathVariable Long userId) { + return userRoleControllerImpl.getUserRole(userId); } @SecurityRequirement(name = "JWT") @Operation(summary = "Обновить роль до модератора") @PatchMapping("/{userId}") - public ResponseEntity updateToModerator(@PathVariable Long userId) { - return null; + public ResponseEntity updateToModerator(@PathVariable Long userId) { + return userRoleControllerImpl.updateToModerator(userId); } @SecurityRequirement(name = "JWT") @Operation(summary = "Обновить роль до пользователя") @DeleteMapping("/{userId}") - public ResponseEntity updateToUser(@PathVariable Long userId) { - return null; + public ResponseEntity updateToUser(@PathVariable Long userId) { + return userRoleControllerImpl.updateToUser(userId); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java deleted file mode 100644 index ed41cca..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/PermissionRepository.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.github.gribanoveu.cuddle.entities.repositories; - -import com.github.gribanoveu.cuddle.dtos.enums.Role; -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.Optional; - -/** - * @author Evgeny Gribanov - * @version 21.09.2023 - */ -@Repository -public interface PermissionRepository extends CrudRepository { - Optional findByName(String name); - List findAll(Pageable pageable); - Boolean existsByName(String name); - void deleteByName(String name); -} diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java index b64706b..642e6b8 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailService.java @@ -7,6 +7,5 @@ * @version 27.11.2023 */ public interface EmailService { - void sendEmail(String toEmail, String subject, String message); void sendMail(SimpleEmailObject email); } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java index 6550e0e..24202b2 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/email/EmailServiceImpl.java @@ -7,7 +7,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.mail.MailException; -import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; @@ -27,20 +26,6 @@ public class EmailServiceImpl implements EmailService { private final JavaMailSender mailSender; private final TemplateEngine templateEngine; - - @Override - public void sendEmail(String toEmail, String subject, String message) { - var simpleMailMessage = new SimpleMailMessage(); - simpleMailMessage.setTo(toEmail); - simpleMailMessage.setSubject(subject); - simpleMailMessage.setText(message); - try { - mailSender.send(simpleMailMessage); - } catch (MailException e) { - throw new CredentialEx(ResponseCode.EMAIL_NOT_SEND); - } - } - @Override public void sendMail(SimpleEmailObject email) { try { diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java deleted file mode 100644 index 39af974..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/permission/PermissionService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.github.gribanoveu.cuddle.entities.services.permission; - -import com.github.gribanoveu.cuddle.dtos.enums.Role; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -/** - * @author Evgeny Gribanov - * @version 21.09.2023 - */ -public interface PermissionService { - Role getDefaultUserPermission(); - List getAllPermissions(int pageNumber, int pageSize); - Role findPermissionByName(String name); - boolean permissionExistByName(String name); - @Transactional void save(Role permission); - @Transactional void deletePermissionByName(String roleName); - @Transactional - void updatePermissionName(String roleName, String newName); -} diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java index f2a2c35..88bf8da 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java @@ -1,5 +1,6 @@ package com.github.gribanoveu.cuddle.entities.services.user; +import com.github.gribanoveu.cuddle.dtos.enums.Role; import com.github.gribanoveu.cuddle.entities.tables.User; import org.springframework.transaction.annotation.Transactional; @@ -14,10 +15,10 @@ public interface UserService { @Transactional void deleteUserById(Long userId); @Transactional void deleteUserByEmail(String userEmail); @Transactional void updatePasswordByEmail(User user, String password); - @Transactional void updateUserPasswordAndCredentialsExpiredById(User user, String password); @Transactional void updateEmail(User user, String newEmail); @Transactional void updateEnabled(User user, Boolean enabled); @Transactional void updateLocked(User user, Boolean locked); + @Transactional void updateRole(User user, Role role); User findUserByEmail(String email); User findUserById(Long id); Boolean userExistByEmail(String email); diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java index 0c11990..0b8bac2 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java @@ -1,6 +1,7 @@ package com.github.gribanoveu.cuddle.entities.services.user; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; +import com.github.gribanoveu.cuddle.dtos.enums.Role; import com.github.gribanoveu.cuddle.entities.repositories.UserRepository; import com.github.gribanoveu.cuddle.entities.tables.User; import com.github.gribanoveu.cuddle.exeptions.CredentialEx; @@ -65,13 +66,6 @@ public void updatePasswordByEmail(User user, String password) { userRepository.save(user); } - @Override - public void updateUserPasswordAndCredentialsExpiredById(User user, String password) { - user.setPassword(password); - user.setCredentialsNonExpired(false); - userRepository.save(user); - } - @Override public void updateEmail(User user, String newEmail) { user.setEmail(newEmail); @@ -90,4 +84,9 @@ public void updateLocked(User user, Boolean locked) { userRepository.save(user); } + @Override + public void updateRole(User user, Role role) { + user.setRole(role); + userRepository.save(user); + } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java index 6dada94..be3cd2b 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/GlobalExceptionHandler.java @@ -7,6 +7,7 @@ import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.utils.aspects.LogResponse; import jakarta.validation.ConstraintViolationException; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.authentication.BadCredentialsException; @@ -21,12 +22,14 @@ * @author Evgeny Gribanov * @version 07.07.2023 */ +@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @LogResponse @ExceptionHandler(HttpMediaTypeNotSupportedException.class) public ResponseEntity handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) { + log.error(e.getMessage()); var details = StatusResponse.create(ResponseCode.VALIDATION_ERROR, StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.VALIDATION_ERROR.getHttpCode()).body(details); } @@ -34,6 +37,7 @@ public ResponseEntity handleHttpMediaTypeNotSupportedException(HttpMediaTypeN @LogResponse @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { + log.error(e.getMessage()); var details = StatusResponse.create(ResponseCode.VALIDATION_ERROR, StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.VALIDATION_ERROR.getHttpCode()).body(details); } @@ -41,6 +45,7 @@ public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotRea @LogResponse @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException e) { + log.error(e.getMessage()); var details = StatusResponse.create(ResponseCode.RESOURCE_NOT_FOUND, StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.RESOURCE_NOT_FOUND.getHttpCode()).body(details); } @@ -48,6 +53,7 @@ public ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException e @LogResponse @ExceptionHandler(BadCredentialsException.class) public ResponseEntity handleBadCredentialsException(BadCredentialsException e) { + log.error(e.getMessage()); var details = StatusResponse.create( ResponseCode.BAD_CREDENTIAL, e.getMessage(), StatusLevel.ERROR); return ResponseEntity.status(ResponseCode.BAD_CREDENTIAL.getHttpCode()).body(details); @@ -56,6 +62,7 @@ public ResponseEntity handleBadCredentialsException(BadCredentia @LogResponse @ExceptionHandler(CredentialEx.class) public ResponseEntity handleCredentialsException(CredentialEx e) { + log.error(e.getMessage()); var details = StatusResponse.create(e.getError(), StatusLevel.WARNING); return ResponseEntity.status(e.getStatus()).body(details); } @@ -63,6 +70,7 @@ public ResponseEntity handleCredentialsException(CredentialEx e) { @LogResponse(message = "Validation error") @ExceptionHandler(MethodArgumentNotValidException.class) // @Valid handler public ResponseEntity handleValidAnnotationException(MethodArgumentNotValidException e) { + log.error(e.getMessage()); var errors = e.getBindingResult().getFieldErrors().stream() .map(fieldError -> new ResponseDetails( ResponseCode.VALIDATION_ERROR_DETAIL, @@ -76,6 +84,7 @@ public ResponseEntity handleValidAnnotationException(MethodArgumentNotValidEx @LogResponse @ExceptionHandler(ConstraintViolationException.class) // database entity handler public ResponseEntity handleDatabaseValidationException(ConstraintViolationException e) { + log.error(e.getMessage()); var errors = e.getConstraintViolations().stream() .map(violation -> new ResponseDetails(ResponseCode.VALIDATION_ERROR, String.format(ValidationMessages.EXCEPTION_VIOLATION_PATTERN, violation.getPropertyPath(), violation.getMessage()))) @@ -88,6 +97,7 @@ public ResponseEntity handleDatabaseValidationException(ConstraintViolationEx @LogResponse @ExceptionHandler(MissingServletRequestParameterException.class) // query param handler public ResponseEntity handleMissingParamException(MissingServletRequestParameterException e) { + log.error(e.getMessage()); var details = StatusResponse.create(ResponseCode.MISSING_PARAM, StatusLevel.ERROR); return ResponseEntity.badRequest().body(details); } diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java index cd06b4f..9786fde 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/AuthenticationFailureEntryPoint.java @@ -1,6 +1,5 @@ package com.github.gribanoveu.cuddle.exeptions.entrypoint; -import com.github.gribanoveu.cuddle.utils.JsonUtils; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -19,8 +18,8 @@ */ @Component @RequiredArgsConstructor +@SuppressWarnings("RedundantThrows") public class AuthenticationFailureEntryPoint implements AuthenticationFailureHandler { - private final JsonUtils jsonUtils; @Override public void onAuthenticationFailure( diff --git a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java index b142d3c..bad1b00 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java +++ b/src/main/java/com/github/gribanoveu/cuddle/exeptions/entrypoint/ServerErrorEntryPoint.java @@ -31,7 +31,7 @@ public void commence( HttpServletResponse response, AuthenticationException authException ) throws IOException { - StatusResponse error = null; + StatusResponse error; if (authException instanceof DisabledException) { error = StatusResponse.create(ACCOUNT_DISABLED, ACCOUNT_DISABLED.getMessage(), StatusLevel.ERROR); diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java index 0d95f42..2dd1ac0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/RSAEncryptionUtils.java @@ -8,13 +8,18 @@ import java.security.PublicKey; /** - * @author Evgeny Gribanov - * @version 24.10.2023 - * For gen serts: - * openssl genrsa -out keypair.pem 2048 + * Генерация ключевой пары и сертификатов с помощью OpenSSL. + *

+ * Для генерации ключевой пары выполните следующие команды: + *

{@code
+ * openssl genrsa -out keypair.pem 2048
  * openssl rsa -in keypair.pem -pubout -out public.pem
  * openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in keypair.pem -out private.pem
- * place serts in resources/certs
+ * }
+ * Затем поместите сертификаты в папку resources/certs. + * + * @author Evgeny Gribanov + * @version 24.10.2023 */ @Component @RequiredArgsConstructor diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java index 889e85c..a2c6dff 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/aspects/RequestLoggingAspect.java @@ -13,6 +13,8 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import java.util.Objects; + @Aspect @Component @Slf4j @@ -23,7 +25,7 @@ public class RequestLoggingAspect { @Around("@annotation(LogRequest)") public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable { var attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - var request = attributes.getRequest(); + var request = Objects.requireNonNull(attributes).getRequest(); log.info(""" [REQUEST] Incoming request to server: { @@ -43,7 +45,7 @@ public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable { public void logResponse(JoinPoint joinPoint, Object result) { var attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); var annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(LogResponse.class); - var request = attributes.getRequest(); + var request = Objects.requireNonNull(attributes).getRequest(); var message = (""" { "Method":"%1$s", diff --git a/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java b/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java index 580a917..01d7d36 100644 --- a/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java +++ b/src/test/java/com/github/gribanoveu/cuddle/utils/JsonUtilsTest.java @@ -1,6 +1,6 @@ package com.github.gribanoveu.cuddle.utils; -import com.github.gribanoveu.cuddle.dtos.request.auth.LoginDto; +import com.github.gribanoveu.cuddle.dtos.request.LoginDto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; From fc27f4c526ce48c030f6a7c6bc882ea9bba1b189 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 14:23:28 +0300 Subject: [PATCH 25/34] enable https, refactor anonymous controller endpoint Took 30 minutes --- .../cuddle/config/SecurityConfig.java | 6 +- .../dtos/request/admin/PermissionDto.java | 19 ------ .../anonymous/AuthenticationController.java | 2 +- .../anonymous/PublicAccountController.java | 2 +- src/main/resources/application.yml | 60 ++++++++++--------- 5 files changed, 36 insertions(+), 53 deletions(-) delete mode 100644 src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java diff --git a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java index 4108914..852e1f2 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java +++ b/src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java @@ -47,11 +47,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .cors(CorsConfigurer::disable) .authorizeHttpRequests(req -> req // anonymous scope - .requestMatchers( HttpMethod.POST, "*/auth").anonymous() // issue token - .requestMatchers( HttpMethod.PATCH, "*/auth").anonymous() // refresh token - .requestMatchers(HttpMethod.POST, "*/account/create").anonymous() // register - .requestMatchers(HttpMethod.POST, "*/account/generate-code").anonymous() - .requestMatchers(HttpMethod.POST, "*/account/restore-password").anonymous() + .requestMatchers("/open/**").anonymous() // anonymous scope (swagger) .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll() diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java deleted file mode 100644 index 34ff455..0000000 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/admin/PermissionDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.github.gribanoveu.cuddle.dtos.request.admin; - -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.Pattern; -import jakarta.validation.constraints.Size; - -import static com.github.gribanoveu.cuddle.constants.RegexpFormat.PERMISSION_PATTERN; -import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; - -/** - * @author Evgeny Gribanov - * @version 25.09.2023 - */ -public record PermissionDto( - @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) - @Pattern(regexp = PERMISSION_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) - @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) - String permissionName -) {} diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java index e3b481a..2083075 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/AuthenticationController.java @@ -17,7 +17,7 @@ */ @RestController @RequiredArgsConstructor -@RequestMapping("/v1/auth") +@RequestMapping("/open/v1/auth") @Tag(name="Аутентификация пользователя", description="Позволяет получить и обновить токен") public class AuthenticationController { private final AuthenticationControllerImpl authenticationControllerImpl; diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java index a77a1b3..acee722 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java @@ -22,7 +22,7 @@ */ @RestController @RequiredArgsConstructor -@RequestMapping("/v1/account") +@RequestMapping("/open/v1/account") @Tag(name="Управление аккаунтом без авторизации", description="Позволяет управлять данными учетной записи") public class PublicAccountController { private final PublicAccountControllerImpl publicAccountControllerImpl; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7ad4b1a..bfe8041 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,7 +1,12 @@ server: - port: 8189 + port: 8443 + ssl: + key-store: classpath:certs/mykeys.jks + key-store-password: letmein + key-password: letmein servlet: context-path: /api/private + time-variable: accessTokenLifetime: 15m refreshTokenLifetime: 7d @@ -9,20 +14,25 @@ time-variable: rsa: private-key: classpath:certs/private.pem public-key: classpath:certs/public.pem + spring: - mail: - host: localhost - port: 1025 - username: - password: - properties: - mail: - smtp: - auth: false - starttls: - enable: false + application: + name: cuddle-backend mvc: throw-exception-if-no-handler-found: true + jackson: + default-property-inclusion: non_null + serialization: + write-dates-as-timestamps: false + datasource: + url: jdbc:postgresql://${AUTH_SERVICE_DB_DOMAIN}:${AUTH_SERVICE_DB_PORT}/auth_service_db + username: ${AUTH_SERVICE_DB_LOGIN} + password: ${AUTH_SERVICE_DB_PASSWORD} + driver-class-name: org.postgresql.Driver + data: + redis: + host: localhost + port: 6379 web: resources: add-mappings: false @@ -35,18 +45,14 @@ spring: dialect: org.hibernate.dialect.PostgreSQLDialect jdbc: time_zone: Europe/Moscow - datasource: - url: jdbc:postgresql://${AUTH_SERVICE_DB_DOMAIN}:${AUTH_SERVICE_DB_PORT}/auth_service_db - username: ${AUTH_SERVICE_DB_LOGIN} - password: ${AUTH_SERVICE_DB_PASSWORD} - driver-class-name: org.postgresql.Driver - jackson: - default-property-inclusion: non_null - serialization: - write-dates-as-timestamps: false - data: - redis: - host: localhost - port: 6379 - application: - name: cuddle-backend \ No newline at end of file + mail: + host: localhost + port: 1025 + username: + password: + properties: + mail: + smtp: + auth: false + starttls: + enable: false \ No newline at end of file From 9f67c0c4fb27a3cd400b6ba6266173ce13f71e7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 14:29:24 +0300 Subject: [PATCH 26/34] fix email templates Took 6 minutes --- src/main/resources/templates/email-changed.html | 2 +- src/main/resources/templates/otp-code-template.html | 2 +- src/main/resources/templates/successfully-registration.html | 5 ++--- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/resources/templates/email-changed.html b/src/main/resources/templates/email-changed.html index 8a238d5..bfb39cb 100644 --- a/src/main/resources/templates/email-changed.html +++ b/src/main/resources/templates/email-changed.html @@ -40,7 +40,7 @@

Электронная почта изменена

 
Электронная почта на вашем аккаунте успешно изменена.
- Если это были вы, то нет причин для беспокойства, но если это не так, то проверьте безопасность своего аккаунта или обратитесь в службу поддержки. + Если это были вы, то нет причин для беспокойства, но если это не так, то проверьте безопасность своего аккаунта. Для последующего входа в свой аккаунт используйте новый адрес электронной почты.
 
diff --git a/src/main/resources/templates/otp-code-template.html b/src/main/resources/templates/otp-code-template.html index 460a45d..80900f5 100644 --- a/src/main/resources/templates/otp-code-template.html +++ b/src/main/resources/templates/otp-code-template.html @@ -43,7 +43,7 @@

Запрошена смена пароля

Если это сделали не вы, проверьте безопасность своего аккаунта или проигнорируйте это письмо, тогда ничего не изменится. - Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать разные пароли для электронной почты и на данном аккаунте. + Чтобы избежать неправомерного доступа к вашим данным, рекомендуем установить пароль отличающийся от пароля электронной почты.
 
diff --git a/src/main/resources/templates/successfully-registration.html b/src/main/resources/templates/successfully-registration.html index c04af54..ec5cc22 100644 --- a/src/main/resources/templates/successfully-registration.html +++ b/src/main/resources/templates/successfully-registration.html @@ -42,13 +42,12 @@

Успешная регистрация

Добро пожаловать, мы рады вас видеть в нашем приложении.
- Вы почти стали полноправным пользователем нашего приложения для знакомств! 🎉 - Для продолжения, войдите в свою учётную запись и заполните профиль. + 🎉 Для продолжения, войдите в свою учётную запись и заполните профиль.
 

Внимание!

- Продолжая регистрацию, вы подтверждаете своё совершеннолетие (18+) и осознаёте, какую информацию вы публикуете на нашем ресурсе. Если представленная информация в приложении способна вывести вас из состояния душевного равновесия, не продолжайте регистрацию и не используйте приложение! + Продолжая регистрацию, вы подтверждаете своё совершеннолетие (18+) и осознаёте, какую информацию вы публикуете на нашем ресурсе.

Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования. From 3c814e060435318ba597d32ff91cf1a149921acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 14:46:28 +0300 Subject: [PATCH 27/34] refactor get pageable users Took 15 minutes --- .../cuddle/controllers/secure/ModeratorControllerImpl.java | 5 +++-- .../cuddle/endpoints/secure/ModeratorController.java | 6 ++++-- .../cuddle/entities/services/user/UserService.java | 3 ++- .../cuddle/entities/services/user/UserServiceImpl.java | 4 ++-- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java index b948fc9..df8a152 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java @@ -6,6 +6,7 @@ import com.github.gribanoveu.cuddle.dtos.response.auth.UsersResponse; import com.github.gribanoveu.cuddle.entities.services.user.UserService; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @@ -20,8 +21,8 @@ public class ModeratorControllerImpl { private final UserService userService; - public ResponseEntity getAllUsersList(int pageNumber, int pageSize) { - return ResponseEntity.ok(UsersResponse.create(OK, userService.getAllUsers(pageNumber, pageSize))); + public ResponseEntity getAllUsersList(Pageable pageable) { + return ResponseEntity.ok(UsersResponse.create(OK, userService.getAllUsers(pageable))); } public ResponseEntity deleteUser(Long userId) { diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java index d9a2995..632a4a0 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java @@ -5,6 +5,8 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -22,8 +24,8 @@ public class ModeratorController { @Operation(summary = "Получить список всех пользователей") @SecurityRequirement(name = "JWT") @GetMapping("/users-list") - public ResponseEntity getAllUsersList(@RequestParam int pageNumber, @RequestParam int pageSize) { - return moderatorControllerImpl.getAllUsersList(pageNumber, pageSize); + public ResponseEntity getAllUsersList(@PageableDefault(size = 10, page = 0) Pageable pageable) { + return moderatorControllerImpl.getAllUsersList(pageable); } @Operation(summary = "Удалить пользователя") diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java index 88bf8da..09e8858 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java @@ -2,6 +2,7 @@ import com.github.gribanoveu.cuddle.dtos.enums.Role; import com.github.gribanoveu.cuddle.entities.tables.User; +import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; import java.util.List; @@ -22,5 +23,5 @@ public interface UserService { User findUserByEmail(String email); User findUserById(Long id); Boolean userExistByEmail(String email); - List getAllUsers(int pageNumber, int pageSize); + List getAllUsers(Pageable pageable); } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java index 0b8bac2..c9748f7 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java @@ -7,6 +7,7 @@ import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; @@ -55,8 +56,7 @@ public Boolean userExistByEmail(String email) { } @Override - public List getAllUsers(int pageNumber, int pageSize) { - var pageable = PageRequest.of(pageNumber, pageSize); + public List getAllUsers(Pageable pageable) { return userRepository.findAll(pageable); } From 8aeb46cc6cc4ab0c0a1662984919fd4d5d3e00bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 22 Dec 2023 15:56:11 +0300 Subject: [PATCH 28/34] refactor email templates Took 34 minutes --- .../resources/templates/email-changed.html | 7 +- .../templates/otp-code-template.html | 7 +- .../resources/templates/password-changed.html | 7 +- .../templates/successfully-login.html | 7 +- .../templates/successfully-registration.html | 13 ++-- .../templates/user-deleted-moder.html | 73 +++++++++++++++++++ .../resources/templates/user-deleted.html | 8 +- 7 files changed, 106 insertions(+), 16 deletions(-) create mode 100644 src/main/resources/templates/user-deleted-moder.html diff --git a/src/main/resources/templates/email-changed.html b/src/main/resources/templates/email-changed.html index bfb39cb..5928511 100644 --- a/src/main/resources/templates/email-changed.html +++ b/src/main/resources/templates/email-changed.html @@ -1,5 +1,5 @@ - + Электронная почта изменена @@ -23,7 +23,10 @@ } .logoStyle { padding-top: 5px; - padding-left: 10px + padding-left: 10px; + } + h1 { + line-height: 1.1; } diff --git a/src/main/resources/templates/otp-code-template.html b/src/main/resources/templates/otp-code-template.html index 80900f5..6c15742 100644 --- a/src/main/resources/templates/otp-code-template.html +++ b/src/main/resources/templates/otp-code-template.html @@ -1,5 +1,5 @@ - + Запрошена смена пароля @@ -23,7 +23,10 @@ } .logoStyle { padding-top: 5px; - padding-left: 10px + padding-left: 10px; + } + h1 { + line-height: 1.1; } diff --git a/src/main/resources/templates/password-changed.html b/src/main/resources/templates/password-changed.html index 95a5ed2..d92a7f9 100644 --- a/src/main/resources/templates/password-changed.html +++ b/src/main/resources/templates/password-changed.html @@ -1,5 +1,5 @@ - + Пароль изменен @@ -23,7 +23,10 @@ } .logoStyle { padding-top: 5px; - padding-left: 10px + padding-left: 10px; + } + h1 { + line-height: 1.1; } diff --git a/src/main/resources/templates/successfully-login.html b/src/main/resources/templates/successfully-login.html index 034f7ff..d48c53b 100644 --- a/src/main/resources/templates/successfully-login.html +++ b/src/main/resources/templates/successfully-login.html @@ -1,5 +1,5 @@ - + В ваш аккаунт выполнен вход @@ -23,7 +23,10 @@ } .logoStyle { padding-top: 5px; - padding-left: 10px + padding-left: 10px; + } + h1 { + line-height: 1.1; } diff --git a/src/main/resources/templates/successfully-registration.html b/src/main/resources/templates/successfully-registration.html index ec5cc22..2a39105 100644 --- a/src/main/resources/templates/successfully-registration.html +++ b/src/main/resources/templates/successfully-registration.html @@ -1,5 +1,5 @@ - + Успешная регистрация @@ -23,7 +23,10 @@ } .logoStyle { padding-top: 5px; - padding-left: 10px + padding-left: 10px; + } + h1 { + line-height: 1.1; } @@ -39,10 +42,10 @@

Успешная регистрация

 
- Добро пожаловать, мы рады вас видеть в нашем приложении. + Добро пожаловать, мы рады вас видеть в нашем приложении. 🎉
- 🎉 Для продолжения, войдите в свою учётную запись и заполните профиль. + Для продолжения, войдите в свою учётную запись и заполните профиль.
 

Внимание!

@@ -53,7 +56,7 @@

Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования.
 
А так же ознакомьтесь с нашими правилами сообщества, в них вам будет рассказано, какую информацию о себе вы можете публиковать не нарушая правила. - Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать разные пароли для электронной почты и для ваших учетных записей. + Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать пароль отличающийся от пароля электронной почты.

 
Детали запроса:
diff --git a/src/main/resources/templates/user-deleted-moder.html b/src/main/resources/templates/user-deleted-moder.html new file mode 100644 index 0000000..e8aa31e --- /dev/null +++ b/src/main/resources/templates/user-deleted-moder.html @@ -0,0 +1,73 @@ + + + + Ваш аккаунт удален + + + + + + + + + + + + + + +
+
+

Ваш аккаунт удален администрацией

+
 
+
Сожалеем, но ваш аккаунт был удален администрацией. Причиной могло послужить многократное нарушение правил сообщества или ваша личная просьба.
+
+ Напоминаем, что удаление аккаунта это безвозвратная операция и восстановить ваши данные не получится. +
+
 
+
+

Следующие функции и данные были удалены в соответствии с вашей учетной записью:

+
    +
  • Ваш профиль и все связанные с ним данные, включая фотографии и контактную информацию.
  • +
  • Все сообщения и переписки, которые вы создали или участвовали в них.
  • +
  • Ваши настройки и предпочтения, связанные с нашим сервисом.
  • +
+
+
+ Спасибо за использование нашего сервиса. Если вы захотите вернуться, вам потребуется зарегистрироваться снова. +
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/user-deleted.html b/src/main/resources/templates/user-deleted.html index 937b698..bd602b9 100644 --- a/src/main/resources/templates/user-deleted.html +++ b/src/main/resources/templates/user-deleted.html @@ -1,6 +1,5 @@ - + Ваш аккаунт удален @@ -24,7 +23,10 @@ } .logoStyle { padding-top: 5px; - padding-left: 10px + padding-left: 10px; + } + h1 { + line-height: 1.1; } From 4f92bd68f14555c4294c2506cf50446c567751d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Wed, 27 Dec 2023 13:04:15 +0300 Subject: [PATCH 29/34] refactor account disabled logic, ban account, add more swagger Took 7 hours 16 minutes --- .../gribanoveu/cuddle/CuddleApplication.java | 12 +--- .../cuddle/config/SwaggerConfig.java | 25 +++++++ .../cuddle/constants/Constants.java | 7 +- .../cuddle/constants/CronRules.java | 11 +++ .../cuddle/constants/EmailMessages.java | 12 ++++ .../PublicAccountControllerImpl.java | 15 ++++ .../secure/ModeratorControllerImpl.java | 46 ++++++++---- .../cuddle/dtos/enums/BanReason.java | 36 ++++++++++ .../cuddle/dtos/enums/DisableReason.java | 25 +++++++ .../cuddle/dtos/enums/ResponseCode.java | 12 ++++ .../cuddle/dtos/request/RestrictionDto.java | 28 ++++++++ .../anonymous/PublicAccountController.java | 11 +-- .../endpoints/secure/ModeratorController.java | 27 +++---- .../entities/repositories/UserRepository.java | 12 ++++ .../entities/services/user/UserService.java | 8 ++- .../services/user/UserServiceImpl.java | 43 +++++++++-- .../cuddle/entities/tables/User.java | 11 ++- .../entities/tasks/BanExpirationTask.java | 30 ++++++++ .../cuddle/utils/emails/EmailTemplates.java | 12 ++++ src/main/resources/application.yml | 2 +- .../db/migration/V1_0__create_users_table.sql | 4 ++ .../db/migration/V2_0__add_users_data.sql | 8 +-- .../resources/templates/account-banned.html | 72 +++++++++++++++++++ .../resources/templates/account-disabled.html | 66 +++++++++++++++++ .../resources/templates/account-enabled.html | 61 ++++++++++++++++ 25 files changed, 541 insertions(+), 55 deletions(-) create mode 100644 src/main/java/com/github/gribanoveu/cuddle/config/SwaggerConfig.java create mode 100644 src/main/java/com/github/gribanoveu/cuddle/constants/CronRules.java create mode 100644 src/main/java/com/github/gribanoveu/cuddle/dtos/enums/BanReason.java create mode 100644 src/main/java/com/github/gribanoveu/cuddle/dtos/enums/DisableReason.java create mode 100644 src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestrictionDto.java create mode 100644 src/main/java/com/github/gribanoveu/cuddle/entities/tasks/BanExpirationTask.java create mode 100644 src/main/resources/templates/account-banned.html create mode 100644 src/main/resources/templates/account-disabled.html create mode 100644 src/main/resources/templates/account-enabled.html diff --git a/src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java b/src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java index e511208..4082f82 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java +++ b/src/main/java/com/github/gribanoveu/cuddle/CuddleApplication.java @@ -9,17 +9,9 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableScheduling; -@OpenAPIDefinition(info = @Info( - title = "Spring Api", - description = "Описание Api", version = "0.1.0", - contact = @Contact( - name = "Evgeny Gribanov", - email = "egribanov@yandex.com", - url = "https://codecow.pw" - ) -)) -@SecurityScheme(name = "JWT", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer") +@EnableScheduling @EnableConfigurationProperties({RsaProperties.class}) @SpringBootApplication public class CuddleApplication { diff --git a/src/main/java/com/github/gribanoveu/cuddle/config/SwaggerConfig.java b/src/main/java/com/github/gribanoveu/cuddle/config/SwaggerConfig.java new file mode 100644 index 0000000..04ba0fb --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/config/SwaggerConfig.java @@ -0,0 +1,25 @@ +package com.github.gribanoveu.cuddle.config; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.info.Contact; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +/** + * @author Evgeny Gribanov + * @version 25.12.2023 + */ +@Configuration +@OpenAPIDefinition(info = @Info( + title = "Spring Api", + description = "Описание Api", version = "0.1.0", + contact = @Contact( + name = "Evgeny Gribanov", + email = "egribanov@yandex.com", + url = "https://codecow.pw" + ) +)) +@SecurityScheme(name = "JWT", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer") +public class SwaggerConfig { } diff --git a/src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java b/src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java index b6081f2..f10d612 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/Constants.java @@ -1,10 +1,13 @@ package com.github.gribanoveu.cuddle.constants; +import java.time.format.DateTimeFormatter; +import java.util.Locale; + /** * @author Evgeny Gribanov * @version 18.09.2023 */ public class Constants { - public static final String DEFAULT_USER_POSITION = "USER"; - public static final String DEFAULT_PASSWORD = "Qwerty123"; + public static final DateTimeFormatter DEFAULT_TIME_FORMAT = + DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm", Locale.forLanguageTag("ru")); } diff --git a/src/main/java/com/github/gribanoveu/cuddle/constants/CronRules.java b/src/main/java/com/github/gribanoveu/cuddle/constants/CronRules.java new file mode 100644 index 0000000..f218932 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/CronRules.java @@ -0,0 +1,11 @@ +package com.github.gribanoveu.cuddle.constants; + +/** + * @author Evgeny Gribanov + * @version 26.12.2023 + */ +public class CronRules { + public static final String EVERYDAY_3_AM = "0 0 3 * * *"; + public static final String EVERY_HOUR = "0 0 * * * *"; + public static final String EVERY_10_MINUTES = "0 */10 * * * *"; +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java b/src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java index 979f380..8d96175 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java +++ b/src/main/java/com/github/gribanoveu/cuddle/constants/EmailMessages.java @@ -20,4 +20,16 @@ public class EmailMessages { public static final String changeEmailSubject = "Электронная почта изменена"; public static final String changeEmailTemplate = "email-changed"; + + public static final String deleteSubject = "Ваш аккаунт удален"; + public static final String deleteModerTemplate = "user-deleted-moder"; + + public static final String disabledSubject = "Действие вашего аккаунта приостановлено"; + public static final String disabledTemplate = "account-disabled"; + + public static final String enabledSubject = "Действие вашего аккаунта возобновлено"; + public static final String enabledTemplate = "account-enabled"; + + public static final String banSubject = "Ваш аккаунт временно заблокирован"; + public static final String banTemplate = "account-banned"; } diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java index 8d32dd2..467e936 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java @@ -1,10 +1,13 @@ package com.github.gribanoveu.cuddle.controllers.anonymous; +import com.github.gribanoveu.cuddle.constants.Constants; import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.dtos.enums.BanReason; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.Role; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; import com.github.gribanoveu.cuddle.dtos.request.*; +import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.otp.RedisOtpService; @@ -140,4 +143,16 @@ public ResponseEntity restorePasswordByOtp(RestorePasswordDto re } throw new CredentialEx(ResponseCode.PASSWORD_EQUALS); } + + public ResponseEntity getRestrictionsReason(String email) { + var userExist = userService.userExistByEmail(email); + if (!userExist) throw new CredentialEx(ResponseCode.USER_NOT_EXIST); + var user = userService.findUserByEmail(email); + if (user.getBanExpiration() == null) throw new CredentialEx(ResponseCode.NO_RESTRICTIONS); + var reason = BanReason.getBanMessageByCode(user.getRestrictionReason()); + var responseText = String.format("Ваша учетная запись заблокирована по причине: %1$s. Блокировка истекает: %2$s", + reason, user.getBanExpiration().format(Constants.DEFAULT_TIME_FORMAT)); + + return ResponseEntity.ok(StatusResponse.create(new ResponseDetails(responseText), StatusLevel.SUCCESS)); + } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java index df8a152..7e3eb29 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java @@ -1,11 +1,19 @@ package com.github.gribanoveu.cuddle.controllers.secure; +import com.github.gribanoveu.cuddle.constants.Constants; +import com.github.gribanoveu.cuddle.constants.EmailMessages; +import com.github.gribanoveu.cuddle.dtos.enums.BanReason; +import com.github.gribanoveu.cuddle.dtos.enums.DisableReason; import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode; import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel; +import com.github.gribanoveu.cuddle.dtos.request.RestrictionDto; import com.github.gribanoveu.cuddle.dtos.response.StatusResponse; import com.github.gribanoveu.cuddle.dtos.response.auth.UsersResponse; +import com.github.gribanoveu.cuddle.entities.services.email.EmailService; import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @@ -16,41 +24,55 @@ * @author Evgeny Gribanov * @version 26.09.2023 */ +@Slf4j @Service @RequiredArgsConstructor public class ModeratorControllerImpl { private final UserService userService; + private final EmailService emailService; public ResponseEntity getAllUsersList(Pageable pageable) { return ResponseEntity.ok(UsersResponse.create(OK, userService.getAllUsers(pageable))); } public ResponseEntity deleteUser(Long userId) { + var user = userService.findUserById(userId); userService.deleteUserById(userId); + emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(), + EmailMessages.deleteSubject, EmailMessages.deleteModerTemplate)); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS)); } - public ResponseEntity disableUser(Long userId) { - var user = userService.findUserById(userId); - userService.updateEnabled(user, false); + public ResponseEntity disableUser(RestrictionDto request) { + var user = userService.findUserByEmail(request.userEmail()); // todo + var disableReason = DisableReason.getDisableReasonByCode(request.reasonCode()); + userService.disableUser(user, disableReason.getCode()); + emailService.sendMail(EmailTemplates.disableUser(user.getEmail(), disableReason.getMessage())); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DISABLED, StatusLevel.SUCCESS)); } - public ResponseEntity enabledUser(Long userId) { - var user = userService.findUserById(userId); - userService.updateEnabled(user, true); + public ResponseEntity enabledUser(String email) { + var user = userService.findUserByEmail(email); + userService.enabledUser(user); + emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(), + EmailMessages.enabledSubject, EmailMessages.enabledTemplate)); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_ENABLED, StatusLevel.SUCCESS)); } - public ResponseEntity banUser(Long userId) { - var user = userService.findUserById(userId); - userService.updateLocked(user, true); + public ResponseEntity banUser(RestrictionDto request) { + var user = userService.findUserByEmail(request.userEmail()); + var banReason = BanReason.getBanExpirationByCode(request.reasonCode()); + userService.lockUser(user, banReason.getBanExpiration().withNano(0), request.reasonCode()); + emailService.sendMail(EmailTemplates.banUser(user.getEmail(), banReason.getMessage(), + banReason.getBanExpiration().format(Constants.DEFAULT_TIME_FORMAT))); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_BANNED, StatusLevel.SUCCESS)); } - public ResponseEntity mercyUser(Long userId) { - var user = userService.findUserById(userId); - userService.updateLocked(user, false); + public ResponseEntity mercyUser(String email) { + var user = userService.findUserByEmail(email); + userService.unlockUser(user); + emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(), + EmailMessages.enabledSubject, EmailMessages.enabledTemplate)); return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UN_BANNED, StatusLevel.SUCCESS)); } } \ No newline at end of file diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/BanReason.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/BanReason.java new file mode 100644 index 0000000..941e043 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/BanReason.java @@ -0,0 +1,36 @@ +package com.github.gribanoveu.cuddle.dtos.enums; + +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +import java.time.LocalDateTime; + +/** + * @author Evgeny Gribanov + * @version 25.12.2023 + */ +@Getter +@AllArgsConstructor +public enum BanReason { + USERS_ABUSE("CR-1.1", "Оскорбление пользователей", LocalDateTime.now().plusMinutes(10)); + + private final String code; + private final String message; + private final LocalDateTime banExpiration; + + public static BanReason getBanExpirationByCode(String code) { + for (var reason : values()) if (reason.code.equals(code)) return reason; + throw new CredentialEx(ResponseCode.BAN_REASON_NOT_FOUND); + } + + public static String getBanMessageByCode(String code) { + for (var reason : values()) { + if (reason.code.equals(code)) { + return reason.message; + } + } + throw new CredentialEx(ResponseCode.BAN_REASON_NOT_FOUND); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/DisableReason.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/DisableReason.java new file mode 100644 index 0000000..03abdf7 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/DisableReason.java @@ -0,0 +1,25 @@ +package com.github.gribanoveu.cuddle.dtos.enums; + +import com.github.gribanoveu.cuddle.exeptions.CredentialEx; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.time.LocalDateTime; + +/** + * @author Evgeny Gribanov + * @version 27.12.2023 + */ +@Getter +@AllArgsConstructor +public enum DisableReason { + AGE_APPROVE("NA-1.1", "Требуется подтверждение возраста"); + + private final String code; + private final String message; + + public static DisableReason getDisableReasonByCode(String code) { + for (var reason : values()) if (reason.code.equals(code)) return reason; + throw new CredentialEx(ResponseCode.BAN_REASON_NOT_FOUND); + } +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java index cad08ad..35e8f8d 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/enums/ResponseCode.java @@ -77,6 +77,12 @@ public enum ResponseCode { "Your account has been disabled contact support to find out why", HttpStatus.UNAUTHORIZED ), + NO_RESTRICTIONS( + "AUT-111", + "No restrictions", + "There are no restrictions on your account", + HttpStatus.NOT_FOUND + ), PASSWORD_UPDATED( "AUT-200", "Password updated", @@ -196,6 +202,12 @@ public enum ResponseCode { "Information message", "%s", HttpStatus.OK + ), + BAN_REASON_NOT_FOUND( + "MOD-100", + "Warning", + "Restriction reason not exist or not found", + HttpStatus.OK ); private final String code; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestrictionDto.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestrictionDto.java new file mode 100644 index 0000000..b194178 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/request/RestrictionDto.java @@ -0,0 +1,28 @@ +package com.github.gribanoveu.cuddle.dtos.request; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; + +import static com.github.gribanoveu.cuddle.constants.RegexpFormat.EMAIL_PATTERN; +import static com.github.gribanoveu.cuddle.constants.ValidationMessages.*; + +/** + * @author Evgeny Gribanov + * @version 22.12.2023 + */ +@Schema(description = "Сущность для установки ограничений на пользователя") +public record RestrictionDto( + @Schema(description = "Email", example = "user@email.com") + @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) + @Pattern(regexp = EMAIL_PATTERN, message = PATTERN_EXCEPTION_MESSAGE) + @Size(max = 30, message = SIZE_EXCEPTION_MESSAGE) + String userEmail, + + @Schema(description = "Пункт правил причины", example = "CR-1.1") + @Size(max = 15, message = SIZE_EXCEPTION_MESSAGE) + @NotBlank(message = NOT_BLANK_EXCEPTION_MESSAGE) + String reasonCode +) { +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java index acee722..bbef3fa 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/anonymous/PublicAccountController.java @@ -11,10 +11,7 @@ import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -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.RestController; +import org.springframework.web.bind.annotation.*; /** * @author Evgeny Gribanov @@ -44,4 +41,10 @@ public ResponseEntity restorePassword(@Valid @RequestBody Restor public ResponseEntity registerUser(@Valid @RequestBody RegisterDto request) { return publicAccountControllerImpl.registerUser(request); } + + @GetMapping("/restrictions") + @Operation(summary = "Получить причину блокировки") + public ResponseEntity getRestrictionsReason(@RequestParam String email) { + return publicAccountControllerImpl.getRestrictionsReason(email); + } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java index 632a4a0..3adff38 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java +++ b/src/main/java/com/github/gribanoveu/cuddle/endpoints/secure/ModeratorController.java @@ -1,6 +1,7 @@ package com.github.gribanoveu.cuddle.endpoints.secure; import com.github.gribanoveu.cuddle.controllers.secure.ModeratorControllerImpl; +import com.github.gribanoveu.cuddle.dtos.request.RestrictionDto; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; @@ -24,7 +25,7 @@ public class ModeratorController { @Operation(summary = "Получить список всех пользователей") @SecurityRequirement(name = "JWT") @GetMapping("/users-list") - public ResponseEntity getAllUsersList(@PageableDefault(size = 10, page = 0) Pageable pageable) { + public ResponseEntity getAllUsersList(@PageableDefault Pageable pageable) { return moderatorControllerImpl.getAllUsersList(pageable); } @@ -37,29 +38,29 @@ public ResponseEntity deleteUser(@PathVariable Long userId) { @Operation(summary = "Отключить пользователя") @SecurityRequirement(name = "JWT") - @PatchMapping("/{userId}/disable") - public ResponseEntity disableUser(@PathVariable Long userId) { - return moderatorControllerImpl.disableUser(userId); + @PatchMapping("/disable") + public ResponseEntity disableUser(@RequestBody RestrictionDto request) { + return moderatorControllerImpl.disableUser(request); } @Operation(summary = "Включить пользователя") @SecurityRequirement(name = "JWT") - @PatchMapping("/{userId}/enable") - public ResponseEntity enableUser(@PathVariable Long userId) { - return moderatorControllerImpl.enabledUser(userId); + @PatchMapping("/enable") + public ResponseEntity enableUser(@RequestParam String email) { + return moderatorControllerImpl.enabledUser(email); } @Operation(summary = "Выдать бан пользователю") @SecurityRequirement(name = "JWT") - @PatchMapping("/{userId}/ban") - public ResponseEntity banUser(@PathVariable Long userId) { - return moderatorControllerImpl.banUser(userId); + @PatchMapping("/ban") + public ResponseEntity banUserReq(@RequestBody RestrictionDto request) { + return moderatorControllerImpl.banUser(request); } @Operation(summary = "Снять бан с пользователя") @SecurityRequirement(name = "JWT") - @PatchMapping("/{userId}/mercy") - public ResponseEntity mercyUser(@PathVariable Long userId) { - return moderatorControllerImpl.mercyUser(userId); + @PatchMapping("/mercy") + public ResponseEntity mercyUser(@RequestParam String email) { + return moderatorControllerImpl.mercyUser(email); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java index c56c7a8..8ef3851 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/repositories/UserRepository.java @@ -2,9 +2,11 @@ import com.github.gribanoveu.cuddle.entities.tables.User; import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; +import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @@ -19,4 +21,14 @@ public interface UserRepository extends CrudRepository { Optional findUserById(Long id); List findAll(Pageable pageable); void deleteByEmail(String email); + + @Query("SELECT u FROM User u WHERE u.accountNonLocked = false AND u.banExpiration < :now") + List findBannedUsersWithExpiredBan(LocalDateTime now); + + @Query(""" + SELECT u.banExpiration, u.accountNonLocked, u.id + FROM User u + WHERE u.accountNonLocked = false AND u.banExpiration < :now + """) + List findBannedUsers(LocalDateTime now); } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java index 09e8858..e5fa14c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserService.java @@ -5,6 +5,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; +import java.time.LocalDateTime; import java.util.List; /** @@ -17,9 +18,12 @@ public interface UserService { @Transactional void deleteUserByEmail(String userEmail); @Transactional void updatePasswordByEmail(User user, String password); @Transactional void updateEmail(User user, String newEmail); - @Transactional void updateEnabled(User user, Boolean enabled); - @Transactional void updateLocked(User user, Boolean locked); + @Transactional void lockUser(User user, LocalDateTime banExpiration, String banReasonCode); + @Transactional int removeExpiredBans(); @Transactional void updateRole(User user, Role role); + @Transactional void unlockUser(User user); + @Transactional void enabledUser(User user); + @Transactional void disableUser(User user, String disableReasonCode); User findUserByEmail(String email); User findUserById(Long id); Boolean userExistByEmail(String email); diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java index c9748f7..225327e 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/services/user/UserServiceImpl.java @@ -6,10 +6,10 @@ import com.github.gribanoveu.cuddle.entities.tables.User; import com.github.gribanoveu.cuddle.exeptions.CredentialEx; import lombok.RequiredArgsConstructor; -import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import java.time.LocalDateTime; import java.util.List; /** @@ -73,14 +73,30 @@ public void updateEmail(User user, String newEmail) { } @Override - public void updateEnabled(User user, Boolean enabled) { - user.setEnabled(enabled); + public void enabledUser(User user) { + user.setEnabled(true); userRepository.save(user); } @Override - public void updateLocked(User user, Boolean locked) { - user.setAccountNonLocked(locked); + public void disableUser(User user, String disableReasonCode) { + user.setEnabled(false); + user.setRestrictionReason(disableReasonCode); + userRepository.save(user); + } + + @Override + public void unlockUser(User user) { + user.setAccountNonLocked(true); + user.setBanExpiration(null); + userRepository.save(user); + } + + @Override + public void lockUser(User user, LocalDateTime banExpiration, String banReason) { + user.setAccountNonLocked(false); + user.setBanExpiration(banExpiration); + user.setRestrictionReason(banReason); userRepository.save(user); } @@ -89,4 +105,21 @@ public void updateRole(User user, Role role) { user.setRole(role); userRepository.save(user); } + + @Override + public int removeExpiredBans() { + var unbannedUsers = 0; + var now = LocalDateTime.now(); + var bannedUsers = userRepository.findBannedUsersWithExpiredBan(now); + + for (User user : bannedUsers) { + if (user.getBanExpiration() != null && user.getBanExpiration().isBefore(now)) { + user.setAccountNonLocked(true); // Снятие бана + user.setBanExpiration(null); // Сброс времени истечения бана + userRepository.save(user); + unbannedUsers++; + } + } + return unbannedUsers; + } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java index 9233b48..60eef00 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java @@ -16,7 +16,7 @@ @Data @Entity -@Table(name = "users") +@Table(name = "users", indexes = @Index(name = "idx_is_banned", columnList = "ban_expiration")) @AllArgsConstructor @NoArgsConstructor public class User { @@ -41,6 +41,13 @@ public class User { @Column(name = "birth_date") private LocalDate birthDate; + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "ban_expiration") + private LocalDateTime banExpiration; + + @Column(name = "restriction_reason") + private String restrictionReason; + @JsonIgnore @Enumerated(EnumType.STRING) @Column(name = "role") @@ -60,7 +67,7 @@ public class User { @PrePersist private void setDefaultAccountStatus() { - this.registrationDate = LocalDateTime.now(); + this.registrationDate = LocalDateTime.now().withNano(0); } } diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/tasks/BanExpirationTask.java b/src/main/java/com/github/gribanoveu/cuddle/entities/tasks/BanExpirationTask.java new file mode 100644 index 0000000..8da3a60 --- /dev/null +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/tasks/BanExpirationTask.java @@ -0,0 +1,30 @@ +package com.github.gribanoveu.cuddle.entities.tasks; + +import com.github.gribanoveu.cuddle.constants.Constants; +import com.github.gribanoveu.cuddle.constants.CronRules; +import com.github.gribanoveu.cuddle.entities.services.user.UserService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +/** + * @author Evgeny Gribanov + * @version 22.12.2023 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class BanExpirationTask { + private final UserService userService; + + @Scheduled(cron = CronRules.EVERY_HOUR) + public void mercyUser() { + log.info("[ TASK ] USER UNBAN - STARTED: {}]", LocalDateTime.now().format(Constants.DEFAULT_TIME_FORMAT)); + var unbannedUsers = userService.removeExpiredBans(); + log.info("[ TASK ] USER UNBAN - ENDED: unbanned users: {}]", unbannedUsers); + } + +} diff --git a/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java b/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java index d271739..676bf56 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java +++ b/src/main/java/com/github/gribanoveu/cuddle/utils/emails/EmailTemplates.java @@ -40,4 +40,16 @@ public static SimpleEmailObject emailChanged(String oldEmail, String newEmail) { ) ); } + + public static SimpleEmailObject banUser(String sendToEmail, String banReason, String expiredDate) { + return new SimpleEmailObject(EmailMessages.sendFrom,sendToEmail, EmailMessages.banSubject,EmailMessages.banTemplate, + Map.of("email", sendToEmail, "reason", banReason, "expired", expiredDate) + ); + } + + public static SimpleEmailObject disableUser(String sendToEmail, String banReason) { + return new SimpleEmailObject(EmailMessages.sendFrom,sendToEmail, EmailMessages.disabledSubject,EmailMessages.disabledTemplate, + Map.of("email", sendToEmail, "reason", banReason) + ); + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index bfe8041..134b31b 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -5,7 +5,7 @@ server: key-store-password: letmein key-password: letmein servlet: - context-path: /api/private + context-path: /api time-variable: accessTokenLifetime: 15m diff --git a/src/main/resources/db/migration/V1_0__create_users_table.sql b/src/main/resources/db/migration/V1_0__create_users_table.sql index a13ec29..d9d3dd8 100644 --- a/src/main/resources/db/migration/V1_0__create_users_table.sql +++ b/src/main/resources/db/migration/V1_0__create_users_table.sql @@ -6,9 +6,13 @@ CREATE TABLE users password VARCHAR(80) NOT NULL, birth_date DATE NOT NULL, registration_date TIMESTAMP NOT NULL, + ban_expiration TIMESTAMP NULL, + restriction_reason VARCHAR(15) null, role VARCHAR(15) NOT NULL, account_non_expired BOOLEAN NOT NULL, account_non_locked BOOLEAN NOT NULL, credentials_non_expired BOOLEAN NOT NULL, enabled BOOLEAN NOT NULL ); + +CREATE INDEX idx_is_banned on users (ban_expiration); diff --git a/src/main/resources/db/migration/V2_0__add_users_data.sql b/src/main/resources/db/migration/V2_0__add_users_data.sql index 6fdda44..02930aa 100644 --- a/src/main/resources/db/migration/V2_0__add_users_data.sql +++ b/src/main/resources/db/migration/V2_0__add_users_data.sql @@ -1,16 +1,16 @@ INSERT INTO users -(version, email, password, birth_date, registration_date, role, +(version, email, password, birth_date, registration_date, ban_expiration, restriction_reason, role, account_non_expired, account_non_locked, credentials_non_expired, enabled) VALUES (0, 'admin@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', - '2001-01-01', '2023-01-01 00:00:00.000000', + '2001-01-01', '2023-01-01 00:00:00.000000', null, null, 'ADMIN', true, true, true, true), (0, 'moderator@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', - '2001-01-01', '2023-01-01 00:00:00.000000', + '2001-01-01', '2023-01-01 00:00:00.000000', null, null, 'MODERATOR', true, true, true, true), (0, 'user@email.com', '$2a$12$FyLK5s44fub5XpaTRVtiHuPqUJXQplJD261p2jd7AmlDzrSsINH8i', - '2001-01-01', '2023-01-01 00:00:00.000000', + '2001-01-01', '2023-01-01 00:00:00.000000', null, null, 'USER', true, true, true, true); diff --git a/src/main/resources/templates/account-banned.html b/src/main/resources/templates/account-banned.html new file mode 100644 index 0000000..3c9fc3a --- /dev/null +++ b/src/main/resources/templates/account-banned.html @@ -0,0 +1,72 @@ + + + + Ваш аккаунт заблокирован + + + + + + + + + + + + + + +
+
+

Ваша учетная запись заблокирована 😶

+
+

+

+
+

+ Обращаем ваше внимание, что блокировка может быть снята с задержкой. +

+

+ Например, если время блокировки истекает в 16:50, то блокировка будет снята в 17:00. + Если блокировка истекает в 17:05, то она будет снята в 18:00. +

+

Наберитесь терпения и надеемся данная ситуация не повторится вновь.

+

Давайте вместе работать над созданием более приятной обстановки для всех пользователей.

+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/account-disabled.html b/src/main/resources/templates/account-disabled.html new file mode 100644 index 0000000..05af48c --- /dev/null +++ b/src/main/resources/templates/account-disabled.html @@ -0,0 +1,66 @@ + + + + Действие вашего аккаунта приостановлено + + + + + + + + + + + + + + +
+
+

Действие вашей учетной записи приостановлено 🥶

+
+

Что это означает:

+
    +
  • Все ваши данные сохранены.
  • +
  • Ваша учетная запись не отображается в глобальном поиске.
  • +
  • Вы не можете выполнить вход в систему и пользоваться приложением.
  • +
+
+

+

Для возобновления работы потребуется написать в support@cuddle.pw.

+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/account-enabled.html b/src/main/resources/templates/account-enabled.html new file mode 100644 index 0000000..ff05579 --- /dev/null +++ b/src/main/resources/templates/account-enabled.html @@ -0,0 +1,61 @@ + + + + Действие вашего аккаунта возобновлено + + + + + + + + + + + + + + +
+
+

Действие вашего аккаунта возобновлено ❤️

+
Все ограничения с вашего аккаунта сняты.
+
 
+
+ Мы рады, что Вы снова с нами. +
+
 
+
Детали запроса:
+
+
+
+
+
+
 
+
+ + \ No newline at end of file From c0513914f8c4ed51a5b488ee48798e70436486d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Wed, 27 Dec 2023 15:25:01 +0300 Subject: [PATCH 30/34] add missing swagger props Took 10 minutes --- .../gribanoveu/cuddle/dtos/response/auth/TokenResponse.java | 1 + .../gribanoveu/cuddle/dtos/response/auth/UsersResponse.java | 1 + .../com/github/gribanoveu/cuddle/entities/tables/User.java | 4 +++- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java index 6f8bd56..5486dfc 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/TokenResponse.java @@ -15,6 +15,7 @@ @Data @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) +@Schema(description = "Ответ после успешной авторизации") public class TokenResponse { @Schema(description = "Время выполнения запроса") private LocalDateTime timestamp; diff --git a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java index 26c344e..abb3dd5 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java +++ b/src/main/java/com/github/gribanoveu/cuddle/dtos/response/auth/UsersResponse.java @@ -19,6 +19,7 @@ @Data @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) +@Schema(description = "Ответ со списком всех пользователей") public class UsersResponse { @JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Europe/Moscow") @Schema(description = "Время выполнения запроса") diff --git a/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java index 60eef00..004d71c 100644 --- a/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java +++ b/src/main/java/com/github/gribanoveu/cuddle/entities/tables/User.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.gribanoveu.cuddle.dtos.enums.Role; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; @@ -16,9 +17,10 @@ @Data @Entity -@Table(name = "users", indexes = @Index(name = "idx_is_banned", columnList = "ban_expiration")) @AllArgsConstructor @NoArgsConstructor +@Table(name = "users", indexes = @Index(name = "idx_is_banned", columnList = "ban_expiration")) +@Schema(description = "Базовая сущность пользователя") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) From 4aacc1dcb7f83d6dab5c53fb9b246e0613451da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=93=D1=80?= =?UTF-8?q?=D0=B8=D0=B1=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 28 Dec 2023 12:19:09 +0300 Subject: [PATCH 31/34] refactor email templates Took 3 hours 57 minutes --- .../resources/templates/account-banned.html | 6 +- .../resources/templates/account-disabled.html | 5 +- .../resources/templates/account-enabled.html | 12 +-- .../resources/templates/email-changed.html | 7 +- .../templates/otp-code-template.html | 19 +---- .../resources/templates/password-changed.html | 7 +- .../templates/successfully-login.html | 14 +--- .../templates/successfully-registration.html | 76 +++++++++---------- .../templates/user-deleted-moder.html | 17 ++--- .../resources/templates/user-deleted.html | 17 ++--- 10 files changed, 64 insertions(+), 116 deletions(-) diff --git a/src/main/resources/templates/account-banned.html b/src/main/resources/templates/account-banned.html index 3c9fc3a..d7afee2 100644 --- a/src/main/resources/templates/account-banned.html +++ b/src/main/resources/templates/account-banned.html @@ -1,7 +1,7 @@ - Ваш аккаунт заблокирован + Учетная запись заблокирована - - - - - - - - - -
-
-

Успешная регистрация

-
 
-
- Добро пожаловать, мы рады вас видеть в нашем приложении. 🎉 -
-
- Для продолжения, войдите в свою учётную запись и заполните профиль. -
-
 
-

Внимание!

-

- Продолжая регистрацию, вы подтверждаете своё совершеннолетие (18+) и осознаёте, какую информацию вы публикуете на нашем ресурсе. -

-
- Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования. -
 
- А так же ознакомьтесь с нашими правилами сообщества, в них вам будет рассказано, какую информацию о себе вы можете публиковать не нарушая правила. - Чтобы избежать неправомерного доступа к вашим данным, рекомендуем использовать пароль отличающийся от пароля электронной почты. -
-
 
-
Детали запроса:
-
-
-
-
-
-
 
-
+ + + + + + + + + +
+
+

Успешная регистрация

+

Добро пожаловать, мы рады вас видеть в нашем приложении. 🎉

+

Для продолжения, войдите в свою учётную запись и заполните профиль.

+

Внимание!

+

+ Продолжая регистрацию, вы подтверждаете своё совершеннолетие (18+) и осознаёте, какую информацию вы + публикуете на нашем ресурсе. +

+

Перед тем, как начать пользоваться приложением, пожалуйста, прочтите нашу политику конфиденциальности и условия использования.

+

А так же ознакомьтесь с нашими правилами сообщества, в них вам + будет рассказано, какую информацию о себе вы можете публиковать не нарушая правила.

+
Детали запроса:
+
+
+
+
+
+
 
+
diff --git a/src/main/resources/templates/user-deleted-moder.html b/src/main/resources/templates/user-deleted-moder.html index e8aa31e..40236cd 100644 --- a/src/main/resources/templates/user-deleted-moder.html +++ b/src/main/resources/templates/user-deleted-moder.html @@ -1,7 +1,7 @@ - Ваш аккаунт удален + Ваша учетная запись удалена