Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20e1ab321d | ||
|
|
f136ac1f0a |
@@ -1,19 +1,10 @@
|
||||
# Postgres
|
||||
POSTGRES_DB=no_copy_
|
||||
POSTGRES_USER=ncp_db
|
||||
POSTGRES_PASSWORD=ncpDbApp
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=postgres
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_HOST=postgres
|
||||
|
||||
# Redis
|
||||
REDIS_HOST=redis
|
||||
REDIS_PORT=6379
|
||||
|
||||
# Backend server
|
||||
SERVER_PORT=8080
|
||||
|
||||
# Postfix
|
||||
MAIL_HOST_PROD=postfix-production
|
||||
MAIL_PORT_PROD=25
|
||||
MAIL_USERNAME_PROD=noreply@nocopy.com
|
||||
SMTP_PASSWORD_PROD=nocopy!nocopy!
|
||||
@@ -1,78 +0,0 @@
|
||||
Создаем сеть:
|
||||
docker network create app-network
|
||||
|
||||
Войти в БД:
|
||||
docker exec -it postgres psql -U ncp_db -d no_copy_
|
||||
|
||||
Выполнить команду:
|
||||
\du
|
||||
|
||||
Должен быть один пользователь:
|
||||
List of roles
|
||||
Role name | Attributes
|
||||
-----------+------------------------------------------------------------
|
||||
ncp_db | Superuser, Create role, Create DB, Replication, Bypass RLS
|
||||
|
||||
суперпользователь БД:
|
||||
postgres/postgres
|
||||
пользователь бд для бэка
|
||||
ncp_db / ncpDbApp
|
||||
|
||||
Подключение к БД для приложения,если volume не существует :
|
||||
|
||||
Создаться автоматически.
|
||||
|
||||
Если уже существует volume :
|
||||
|
||||
docker exec -it postgres psql -U postgres -d postgres
|
||||
|
||||
CREATE USER ncp_db WITH PASSWORD 'ncpDbApp';
|
||||
|
||||
GRANT ALL PRIVILEGES ON DATABASE no_copy_ TO ncp_db;
|
||||
|
||||
\du
|
||||
|
||||
\q
|
||||
|
||||
-------
|
||||
|
||||
psql -U postgres -d no_copy_
|
||||
|
||||
-- база
|
||||
|
||||
GRANT CONNECT ON DATABASE no_copy_ TO ncp_db;
|
||||
|
||||
-- схема
|
||||
|
||||
GRANT USAGE ON SCHEMA public TO ncp_db;
|
||||
|
||||
-- существующие таблицы
|
||||
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ncp_db;
|
||||
|
||||
-- существующие sequence (очень важно для id)
|
||||
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ncp_db;
|
||||
|
||||
-- будущие таблицы
|
||||
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
GRANT ALL ON TABLES TO ncp_db;
|
||||
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
GRANT ALL ON SEQUENCES TO ncp_db;
|
||||
|
||||
|
||||
Зайти в контейнер:
|
||||
docker exec -it {name} bash
|
||||
|
||||
------
|
||||
|
||||
Создать для сущности FileEntity sequence для икремента индетификатора
|
||||
|
||||
CREATE SEQUENCE IF NOT EXISTS file_support_id_seq START 1;
|
||||
|
||||
ALTER TABLE file_entities
|
||||
ALTER COLUMN support_id
|
||||
SET DEFAULT nextval('file_support_id_seq');
|
||||
|
||||
|
||||
+15
-5
@@ -13,6 +13,13 @@ java {
|
||||
}
|
||||
}
|
||||
|
||||
//dependencyManagement {
|
||||
// imports {
|
||||
// mavenBom "org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4"
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
configurations {
|
||||
compileOnly {
|
||||
extendsFrom annotationProcessor
|
||||
@@ -21,6 +28,9 @@ configurations {
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
flatDir {
|
||||
dirs 'libs'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -30,11 +40,6 @@ dependencies {
|
||||
implementation 'org.springframework.security:spring-security-crypto:6.5.3'
|
||||
implementation 'org.mapstruct:mapstruct:1.5.5.Final'
|
||||
implementation 'commons-validator:commons-validator:1.7'
|
||||
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-mail', version: '4.0.1'
|
||||
|
||||
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.17.0'
|
||||
implementation 'tools.jackson.core:jackson-core:3.0.3'
|
||||
implementation 'jakarta.xml.bind:jakarta.xml.bind-api:4.0.0'
|
||||
|
||||
annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
@@ -50,6 +55,11 @@ dependencies {
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testImplementation 'org.mockito:mockito-core:5.3.1'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
|
||||
// implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.8.21'
|
||||
// implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
|
||||
// implementation 'io.insert-koin:koin-core:3.5.0'
|
||||
implementation name: 'testlib-fat-0.1.2-all (1)'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
|
||||
+7
-51
@@ -17,31 +17,8 @@ services:
|
||||
command: tail -f /dev/null
|
||||
restart: unless-stopped
|
||||
|
||||
# postfix:
|
||||
# image: boky/postfix:latest
|
||||
# container_name: postfix-production
|
||||
# hostname: ${DOMAIN:-no-copy.ru}
|
||||
# environment:
|
||||
# - DOMAIN=${DOMAIN:-no-copy.ru}
|
||||
# - ALLOWED_SENDER_DOMAINS=*
|
||||
# - RELAYHOST=
|
||||
# - DISABLE_SMTP_AUTH=
|
||||
# - SMTP_USERNAME=${MAIL_USERNAME:-noreply@no-copy.ru}
|
||||
# - SMTP_PASSWORD=${SMTP_PASSWORD:-nocopy!nocopy!}
|
||||
# - RELAY_NETWORKS=172.16.0.0/12
|
||||
# - POSTFIX_mynetworks=127.0.0.0/8 172.17.0.0/16 172.16.0.0/12
|
||||
# - POSTFIX_smtpd_relay_restrictions=permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
|
||||
# - POSTFIX_smtpd_recipient_restrictions=permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
|
||||
# - DISABLE_SIGNING=true
|
||||
# ports:
|
||||
# - "25:25"
|
||||
# - "587:587"
|
||||
# networks:
|
||||
# - app-network
|
||||
# restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: postgres:17.7
|
||||
image: postgres:17
|
||||
restart: always
|
||||
deploy:
|
||||
resources:
|
||||
@@ -53,17 +30,14 @@ services:
|
||||
memory: 1G
|
||||
environment:
|
||||
POSTGRES_DB: no_copy_
|
||||
# POSTGRES_USER: postgres
|
||||
# POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_SHARED_BUFFERS: 512MB
|
||||
POSTGRES_EFFECTIVE_CACHE_SIZE: 1536MB
|
||||
ports:
|
||||
- "54320:5432"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./init-scripts:/docker-entrypoint-initdb.d:ro
|
||||
container_name: postgres
|
||||
networks:
|
||||
app-network:
|
||||
@@ -84,27 +58,13 @@ services:
|
||||
environment:
|
||||
FILE_STORAGE_PATH: /data/uploads
|
||||
MAX_FILE_SIZE: 10737418240
|
||||
# FILE_CHUNK_SIZE: 1048576
|
||||
FILE_CHUNK_SIZE: 1000000
|
||||
FILE_CHUNK_SIZE: 1048576
|
||||
POSTGRES_DB: no_copy_
|
||||
# POSTGRES_USER: postgres
|
||||
# POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_PORT: 5432
|
||||
POSTGRES_HOST: db
|
||||
STORAGE_SERVICE_URL: http://storage:8081
|
||||
SPRING_PROFILES_ACTIVE: docker
|
||||
YANDEX_API_KEY: AQVNyaVaUmgUb1GMCtf5zSEqFxy0woXrcMOOB43q
|
||||
YANDEX_FOLDER_ID: b1gokpdbm6qfpsou8pcd
|
||||
YANDEX_SEARCH_URL: "https://searchapi.api.cloud.yandex.net/v2/image/search_by_image"
|
||||
# MAIL_HOST: postfix
|
||||
# MAIL_PORT: 25
|
||||
# MAIL_USERNAME: noreply@no-copy.ru
|
||||
# SMTP_PASSWORD: nocopy!nocopy!
|
||||
# SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE: "false"
|
||||
# SPRING_MAIL_PROPERTIES_MAIL_SMTP_AUTH: "false"
|
||||
# SPRING_MAIL_PROPERTIES_MAIL_DEBUG: "true"
|
||||
depends_on:
|
||||
- db
|
||||
ports:
|
||||
@@ -117,10 +77,6 @@ services:
|
||||
- api
|
||||
volumes:
|
||||
- uploads_data:/data/uploads:rw
|
||||
healthcheck:
|
||||
test: [ "CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d no_copy_" ]
|
||||
interval: 10s
|
||||
retries: 5
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:10.3.1
|
||||
@@ -273,7 +229,7 @@ volumes:
|
||||
loki_rules:
|
||||
uploads_data:
|
||||
prometheus_data:
|
||||
# postfix-data:
|
||||
|
||||
networks:
|
||||
app-network:
|
||||
external: true
|
||||
|
||||
@@ -30,7 +30,6 @@ pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
stage('Deploy with docker-compose') {
|
||||
steps {
|
||||
script {
|
||||
@@ -39,9 +38,7 @@ pipeline {
|
||||
credentialsId: 'server-root-password',
|
||||
usernameVariable: 'SSH_USER',
|
||||
passwordVariable: 'SSH_PASS'
|
||||
),
|
||||
string(credentialsId: 'DB_USER', variable: 'DB_USER'),
|
||||
string(credentialsId: 'DB_PASSWORD', variable: 'DB_PASSWORD')
|
||||
)
|
||||
]) {
|
||||
sh """
|
||||
echo "Deploying branch: ${params.BRANCH}"
|
||||
@@ -80,8 +77,8 @@ pipeline {
|
||||
-p 80:8080 \\
|
||||
-v uploads_data:/data/uploads:rw \\
|
||||
-e POSTGRES_DB=no_copy_ \\
|
||||
-e POSTGRES_USER=$DB_USER \\
|
||||
-e POSTGRES_PASSWORD=$DB_PASSWORD \\
|
||||
-e POSTGRES_USER=postgres \\
|
||||
-e POSTGRES_PASSWORD=postgres \\
|
||||
-e POSTGRES_PORT=5432 \\
|
||||
-e POSTGRES_HOST=db \\
|
||||
--restart unless-stopped \\
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'ncp_db') THEN
|
||||
CREATE USER ncp_db WITH PASSWORD 'ncpDbApp';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
GRANT CONNECT ON DATABASE no_copy_ TO ncp_db;
|
||||
GRANT USAGE ON SCHEMA public TO ncp_db;
|
||||
|
||||
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ncp_db;
|
||||
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ncp_db;
|
||||
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
GRANT ALL ON TABLES TO ncp_db;
|
||||
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
GRANT ALL ON SEQUENCES TO ncp_db;
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,17 +1,35 @@
|
||||
package ru.soune.nocopy.configuration;
|
||||
|
||||
import com.vrt.fileprotection.FileProtector;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@AllArgsConstructor
|
||||
public class ApplicationConfig {
|
||||
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public com.vrt.NoCopyFileService noCopyFileService(
|
||||
FileProtector.FileProvider fileProvider,
|
||||
FileProtector.ProcessingListener processingListener) {
|
||||
|
||||
return new com.vrt.NoCopyFileService(
|
||||
Collections.emptyList(),
|
||||
fileProvider,
|
||||
processingListener
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,11 +16,7 @@ public class HandlerConfig {
|
||||
LoginRequestHandler login,
|
||||
FileUploadHandler upload,
|
||||
FileEntityHandler file,
|
||||
LogoutRequestHandler logoutHandler,
|
||||
ImageFoundRequestHandler imageFoundRequestHandler,
|
||||
VerifyRegisterUserHandler verifyRegisterUser,
|
||||
AuthRequestHandler authRequestHandler,
|
||||
ResetPasswordHandler resetPasswordHandler
|
||||
LogoutRequestHandler logoutHandler
|
||||
) {
|
||||
Map<Integer, RequestHandler> map = new HashMap<>();
|
||||
map.put(20001, login);
|
||||
@@ -28,10 +24,6 @@ public class HandlerConfig {
|
||||
map.put(20004, upload);
|
||||
map.put(20005, file);
|
||||
map.put(20006, logoutHandler);
|
||||
map.put(20007, imageFoundRequestHandler);
|
||||
map.put(20008, authRequestHandler);
|
||||
map.put(20009, verifyRegisterUser);
|
||||
map.put(20010, resetPasswordHandler);
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -35,8 +35,6 @@ public class JacksonConfig {
|
||||
|
||||
mapper.registerModule(javaTimeModule);
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
mapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
|
||||
return mapper;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package ru.soune.nocopy.configuration.file;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.service.file.FileProcessingOrchestrator;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class NoCopyInitializer {
|
||||
|
||||
private final FileProcessingOrchestrator orchestrator;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void initializeOnStartup() {
|
||||
orchestrator.initializeProcessingQueue();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package ru.soune.nocopy.controller;
|
||||
|
||||
import com.vrt.NoCopyFileService;
|
||||
import com.vrt.fileprotection.FileProtector;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -14,16 +16,20 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.soune.nocopy.dto.BaseRequest;
|
||||
import ru.soune.nocopy.dto.BaseResponse;
|
||||
import ru.soune.nocopy.dto.MessageCode;
|
||||
import ru.soune.nocopy.dto.register.RegAnswer;
|
||||
import ru.soune.nocopy.dto.RegAnswer;
|
||||
import ru.soune.nocopy.dto.file.ChunkUploadResponse;
|
||||
import ru.soune.nocopy.dto.file.CompleteUploadResponse;
|
||||
import ru.soune.nocopy.dto.file.FileEntityResponse;
|
||||
import ru.soune.nocopy.dto.file.UploadProgress;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.entity.file.FileStatus;
|
||||
import ru.soune.nocopy.entity.file.ProtectionStatus;
|
||||
import ru.soune.nocopy.entity.file.UploadStatus;
|
||||
import ru.soune.nocopy.exception.*;
|
||||
import ru.soune.nocopy.handler.*;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
import ru.soune.nocopy.service.file.FileEntityService;
|
||||
import ru.soune.nocopy.service.file.FileUploadService;
|
||||
|
||||
@@ -34,6 +40,7 @@ import java.nio.file.Paths;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -47,7 +54,11 @@ public class ApiController {
|
||||
|
||||
private final FileEntityService fileEntityService;
|
||||
|
||||
private final AuthService authService;
|
||||
private final AuthTokenRepository authTokenRepository;
|
||||
|
||||
private final FileEntityRepository fileEntityRepository;
|
||||
|
||||
private final NoCopyFileService noCopyFileService;
|
||||
|
||||
@PostMapping("/v{version}/data")
|
||||
public ResponseEntity<?> handlePostRequest(@RequestBody BaseRequest request,
|
||||
@@ -70,12 +81,6 @@ public class ApiController {
|
||||
return ResponseEntity.ok().body(response);
|
||||
} catch (ValidationException e) {
|
||||
return createValidationErrorResponse(e.getBindingResult(), e.getMsgId());
|
||||
} catch (UserNotFoundException e) {
|
||||
return ResponseEntity.ok().body(new BaseResponse(msgId, MessageCode.USER_NOT_FOUND.getCode(),
|
||||
MessageCode.USER_NOT_FOUND.getDescription(), new HashMap<>()));
|
||||
} catch (NotFoundAuthToken e) {
|
||||
return ResponseEntity.ok().body(new BaseResponse(msgId, MessageCode.AUTH_TOKEN_NOT_FOUND.getCode(),
|
||||
MessageCode.AUTH_TOKEN_NOT_FOUND.getDescription(), new HashMap<>()));
|
||||
} catch (NotValidFieldException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
@@ -262,7 +267,7 @@ public class ApiController {
|
||||
errorData));
|
||||
}
|
||||
|
||||
Long userId = authService.useUserAuthToken(tokenHeader);
|
||||
Long userId = getUserIdFromToken(tokenHeader);
|
||||
FileEntityResponse entityResponse = fileEntityService.getById(fileId, version);
|
||||
|
||||
if (!entityResponse.getUserId().equals(userId)) {
|
||||
@@ -337,6 +342,47 @@ public class ApiController {
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/protect/{fileId}")
|
||||
public ResponseEntity<?> protect( @PathVariable(required = false) String fileId) {
|
||||
Optional<FileEntity> fileEntity = fileEntityRepository.findById(fileId);
|
||||
|
||||
if (!fileEntity.isPresent()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
FileProtector.FileInfo fileInfo = createFileInfo(fileEntity.get());
|
||||
|
||||
noCopyFileService.addFile(fileInfo);
|
||||
|
||||
fileEntity.get().setProtectionStatus(ProtectionStatus.PROCESSING);
|
||||
|
||||
fileEntityRepository.save(fileEntity.get());
|
||||
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
private FileProtector.FileInfo createFileInfo(FileEntity fileEntity) {
|
||||
FileProtector.Type type = determineFileType(fileEntity.getMimeType());
|
||||
|
||||
return new FileProtector.FileInfo(type, fileEntity.getId(), String.valueOf(fileEntity.getUserId()));
|
||||
}
|
||||
|
||||
private FileProtector.Type determineFileType(String mimeType) {
|
||||
if (mimeType == null) {
|
||||
return FileProtector.Type.IMAGE;
|
||||
}
|
||||
|
||||
if (mimeType.startsWith("image")) {
|
||||
return FileProtector.Type.IMAGE;
|
||||
} else if (mimeType.startsWith("video")) {
|
||||
return FileProtector.Type.VIDEO;
|
||||
} else if (mimeType.startsWith("audio")) {
|
||||
return FileProtector.Type.AUDIO;
|
||||
} else {
|
||||
return FileProtector.Type.IMAGE;
|
||||
}
|
||||
}
|
||||
|
||||
private ResponseEntity<BaseResponse> createValidationErrorResponse(BindingResult bindingResult, Integer msgId) {
|
||||
List<Map<String, String>> fieldErrors = bindingResult.getFieldErrors()
|
||||
.stream()
|
||||
@@ -373,15 +419,10 @@ public class ApiController {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
private boolean isPreviewSupported(String mimeType) {
|
||||
if (mimeType == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mimeType.startsWith("image") ||
|
||||
mimeType.startsWith("text") ||
|
||||
mimeType.equals("pdf") ||
|
||||
mimeType.startsWith("video") ||
|
||||
mimeType.startsWith("audio");
|
||||
private Long getUserIdFromToken(String tokenHeader) {
|
||||
String token = tokenHeader.replace("Bearer ", "");
|
||||
AuthToken authToken = authTokenRepository.findByToken(token)
|
||||
.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
||||
return authToken.getUser().getId();
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,17 @@ package ru.soune.nocopy.controller;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.soune.nocopy.dto.register.ChangePasswordRequest;
|
||||
import ru.soune.nocopy.dto.user.UserDTO;
|
||||
import ru.soune.nocopy.dto.user.UserRequest;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.dto.ChangePasswordRequest;
|
||||
import ru.soune.nocopy.dto.UserDTO;
|
||||
import ru.soune.nocopy.dto.UserRequest;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
import ru.soune.nocopy.exception.InvalidUserEmail;
|
||||
import ru.soune.nocopy.exception.NotFoundAuthToken;
|
||||
import ru.soune.nocopy.mapper.UserMapper;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
import ru.soune.nocopy.service.user.UserService;
|
||||
import ru.soune.nocopy.service.UserService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -34,7 +34,7 @@ public class UserController {
|
||||
@GetMapping("/all")
|
||||
public ResponseEntity<List<UserDTO>> getAllUsers() {
|
||||
List<UserDTO> allUsers = userRepository.findAll().stream()
|
||||
.map(u -> new UserDTO(u.getFullName(), u.getCompany(), u.getEmail(), u.isActive(),
|
||||
.map(u -> new UserDTO(u.getFullName(), u.getCompany(), u.getEmail(), u.getIsActive(),
|
||||
u.getPhone(), u.getGenderType(),
|
||||
u.getBirthday(), u.getCreatedAt(), u.getSubscriptionType()))
|
||||
.toList();
|
||||
@@ -52,19 +52,19 @@ public class UserController {
|
||||
AuthToken authToken = tokenOptional.orElseThrow(() -> new NotFoundAuthToken("Token: " + token + "not found"));
|
||||
|
||||
if (authToken != null) {
|
||||
User user = userRepository.findByEmail(email);
|
||||
Optional<User> user = userRepository.findByEmail(email);
|
||||
//TODO add mapper
|
||||
if (user != null) {
|
||||
UserDTO userDTO = userMapper.toDTO(user);
|
||||
if (user.isPresent()) {
|
||||
UserDTO userDTO = userMapper.toDTO(user.get());
|
||||
userDTO.setEmail(email);
|
||||
userDTO.setFullName(user.getFullName());
|
||||
userDTO.setCompany(user.getCompany());
|
||||
userDTO.setPhone(user.getPhone());
|
||||
userDTO.setGenderType(user.getGenderType());
|
||||
userDTO.setBirthday(user.getBirthday());
|
||||
userDTO.setCreatedAt(user.getCreatedAt());
|
||||
userDTO.setSubscriptionType(user.getSubscriptionType());
|
||||
userDTO.setActive(user.isActive());
|
||||
userDTO.setFullName(user.get().getFullName());
|
||||
userDTO.setCompany(user.get().getCompany());
|
||||
userDTO.setPhone(user.get().getPhone());
|
||||
userDTO.setGenderType(user.get().getGenderType());
|
||||
userDTO.setBirthday(user.get().getBirthday());
|
||||
userDTO.setCreatedAt(user.get().getCreatedAt());
|
||||
userDTO.setSubscriptionType(user.get().getSubscriptionType());
|
||||
userDTO.setActive(user.get().getIsActive());
|
||||
|
||||
return ResponseEntity.ok(userDTO);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record AuthResponse (
|
||||
boolean success,
|
||||
String message,
|
||||
String token,
|
||||
LocalDateTime expiresAt
|
||||
) {}
|
||||
@@ -1,11 +1,9 @@
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
|
||||
public class BaseRequest {
|
||||
@JsonProperty("version")
|
||||
Integer version;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
|
||||
public class BaseResponse {
|
||||
@JsonProperty("msg_id")
|
||||
private Integer msgId;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
+1
-5
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
@@ -13,9 +13,5 @@ import java.util.Map;
|
||||
public class LoginAnswer {
|
||||
private String Token;
|
||||
|
||||
private boolean isActive;
|
||||
|
||||
private boolean isVerified;
|
||||
|
||||
private List<Map<String, String>> fieldErrors;
|
||||
}
|
||||
+1
-3
@@ -1,6 +1,5 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
@@ -11,7 +10,6 @@ import lombok.NoArgsConstructor;
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
|
||||
public class LoginRequest {
|
||||
|
||||
@NotBlank(message = "error.not.blank") @Email(message = "error.not.email") @Size(max = 128)
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
@@ -6,14 +6,10 @@ public enum MessageCode {
|
||||
REG_EMAIL_OR_PHONE_EXISTS(1, "Email or phone already registered"),
|
||||
INVALID_FIELD(2, "Invalid field"),
|
||||
INVALID_TOKEN(2, "Invalid token"),
|
||||
TOKEN_IS_ALIVE(2, "Token is alive"),
|
||||
INVALID_ACTION(2, "Invalid action"),
|
||||
FILE_UPLOAD_ERROR(2, "File upload error"),
|
||||
FILE_DOWNLOAD_ERROR(2, "File download error"),
|
||||
USER_NOT_VERIFIED(2, "User not verified"),
|
||||
USER_NOT_FOUND(2, "User not found"),
|
||||
FILE_DOWNLOAD_ERROR_NOT_CORRECT_FIELD(2, "Not correct field"),
|
||||
IMAGE_FOUND_ERROR(2, "Image found error"),
|
||||
INVALID_JSON_BODY(2, "Invalid fields in JSON object"),
|
||||
INCOMPLETE_UPLOAD(2, "Not load all chunks"),
|
||||
MSG_ID_NOT_FOUND(4, "Message id not found"),
|
||||
@@ -22,10 +18,8 @@ public enum MessageCode {
|
||||
AUTH_EMAIL_NOT_FOUND(4, "Email not found"),
|
||||
AUTH_EMAIL_OR_TOKEN_NOT_FOUND(4, "Email or Token not found "),
|
||||
AUTH_TOKEN_MISMATCH(4, "Token mismatch"),
|
||||
AUTH_TOKEN_NOT_FOUND(4, "Token not found"),
|
||||
FILE_NOT_FOUND(4, "File not found"),
|
||||
AUTH_PASSWORD_NOT_MATCHES(2, "Password does not match"),
|
||||
USER_NOT_ACTIVE(2, "User not active");
|
||||
AUTH_PASSWORD_NOT_MATCHES(2, "Password does not match");
|
||||
|
||||
private final Integer code;
|
||||
|
||||
|
||||
+1
-5
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
@@ -13,9 +13,5 @@ import java.util.Map;
|
||||
public class RegAnswer {
|
||||
private String Token;
|
||||
|
||||
private boolean isActive;
|
||||
|
||||
private boolean isVerified;
|
||||
|
||||
private List<Map<String, String>> fieldErrors;
|
||||
}
|
||||
+1
-3
@@ -1,12 +1,10 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import jakarta.validation.constraints.*;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Data
|
||||
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
|
||||
public class RegRequest {
|
||||
@NotEmpty(message = "Full name is required")
|
||||
private String fullName;
|
||||
@@ -1,11 +0,0 @@
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class TokenProcessRequest {
|
||||
|
||||
@JsonProperty("token")
|
||||
private String token;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UserContentDTO {
|
||||
String fileName;
|
||||
String originalFilename;
|
||||
String fileType;
|
||||
String fileExtension;
|
||||
Long fileSize;
|
||||
String filePath;
|
||||
Integer protectionLevel;
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.user;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
@@ -0,0 +1,17 @@
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import ru.soune.nocopy.entity.ContentStatus;
|
||||
import ru.soune.nocopy.entity.file.FileType;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record UserContentResponse(
|
||||
Long id,
|
||||
String filename,
|
||||
String originalFilename,
|
||||
FileType fileType,
|
||||
long fileSize,
|
||||
String filePath,
|
||||
ContentStatus status,
|
||||
LocalDateTime uploadDate
|
||||
) {}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.dto.user;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
package ru.soune.nocopy.dto.user;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import ru.soune.nocopy.entity.user.GenderType;
|
||||
import ru.soune.nocopy.entity.user.SubscriptionType;
|
||||
import ru.soune.nocopy.entity.GenderType;
|
||||
import ru.soune.nocopy.entity.SubscriptionType;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
+2
-3
@@ -1,16 +1,15 @@
|
||||
package ru.soune.nocopy.dto.user;
|
||||
package ru.soune.nocopy.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.Past;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import ru.soune.nocopy.entity.user.GenderType;
|
||||
import ru.soune.nocopy.entity.GenderType;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
|
||||
public class UserRequest {
|
||||
@Size(min = 2)
|
||||
private String fullName;
|
||||
@@ -0,0 +1,41 @@
|
||||
package ru.soune.nocopy.dto.file;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class FileApiResponse<T> {
|
||||
|
||||
private boolean success;
|
||||
private String message;
|
||||
private T data;
|
||||
private String error;
|
||||
|
||||
public static <T> FileApiResponse<T> success(T data) {
|
||||
return FileApiResponse.<T>builder()
|
||||
.success(true)
|
||||
.message("Operation completed successfully")
|
||||
.data(data)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static <T> FileApiResponse<T> success(String message, T data) {
|
||||
return FileApiResponse.<T>builder()
|
||||
.success(true)
|
||||
.message(message)
|
||||
.data(data)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static <T> FileApiResponse<T> error(String error) {
|
||||
return FileApiResponse.<T>builder()
|
||||
.success(false)
|
||||
.error(error)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -30,5 +30,4 @@ public class FileEntityResponse {
|
||||
private String formattedSize;
|
||||
private String downloadUrl;
|
||||
private boolean existsOnDisk;
|
||||
private Integer supportId;
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package ru.soune.nocopy.dto.file;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ImageSearchRequest {
|
||||
@JsonProperty("file_id")
|
||||
private String fileId;
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package ru.soune.nocopy.dto.file;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class YandexSearchResponse {
|
||||
|
||||
@JsonProperty("images")
|
||||
private List<ImageResult> images;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class ImageResult {
|
||||
@JsonProperty("url")
|
||||
private String url;
|
||||
|
||||
@JsonProperty("pageUrl")
|
||||
private String pageUrl;
|
||||
|
||||
@JsonProperty("pageTitle")
|
||||
private String pageTitle;
|
||||
|
||||
@JsonProperty("width")
|
||||
private Integer width;
|
||||
|
||||
@JsonProperty("height")
|
||||
private Integer height;
|
||||
|
||||
@JsonProperty("host")
|
||||
private String host;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ResetPasswordRequest {
|
||||
|
||||
@JsonProperty("email")
|
||||
private String email;
|
||||
|
||||
@JsonProperty("verifyToken")
|
||||
private String verifyToken;
|
||||
|
||||
@JsonProperty("action")
|
||||
private String action;
|
||||
|
||||
@JsonProperty("password")
|
||||
private String password;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ResetPasswordResponse {
|
||||
@JsonProperty("user_id")
|
||||
private Long userId;
|
||||
|
||||
@JsonProperty("authToken")
|
||||
private String authToken;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package ru.soune.nocopy.dto.register;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class VerifyUserRequest {
|
||||
@JsonProperty("verify_token")
|
||||
private String verifyToken;
|
||||
|
||||
@JsonProperty("user_id")
|
||||
private Long userId;
|
||||
|
||||
@JsonProperty("resend")
|
||||
private Integer resend;
|
||||
}
|
||||
+6
-2
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
@@ -30,7 +30,7 @@ public class AuthToken {
|
||||
private String token;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private LocalDateTime expiresAt = LocalDateTime.now().plusHours(1);
|
||||
private LocalDateTime expiresAt = LocalDateTime.now().plusDays(30);
|
||||
|
||||
@CreatedDate
|
||||
@Column(name = "created_at", updatable = false, nullable = false)
|
||||
@@ -41,4 +41,8 @@ public class AuthToken {
|
||||
|
||||
@Column(name = "is_active")
|
||||
private Boolean isActive = true;
|
||||
|
||||
public boolean isValid() {
|
||||
return Boolean.TRUE.equals(isActive) && expiresAt.isAfter(LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.entity.file;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
public enum GenderType {
|
||||
MALE, FEMALE
|
||||
+1
-3
@@ -1,11 +1,9 @@
|
||||
package ru.soune.nocopy.entity.file;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.entity.user.UserContent;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
+7
-17
@@ -1,14 +1,11 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
import ru.soune.nocopy.entity.file.ImageProtection;
|
||||
import ru.soune.nocopy.entity.file.Violation;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -36,9 +33,6 @@ public class User {
|
||||
@Column(name = "email", nullable = false, length = 1024, unique = true)
|
||||
private String email;
|
||||
|
||||
@Column(name = "email_verified")
|
||||
private boolean emailVerified = false;
|
||||
|
||||
@Column(name = "company")
|
||||
private String company;
|
||||
|
||||
@@ -70,23 +64,23 @@ public class User {
|
||||
private LocalDateTime lastLoginAt;
|
||||
|
||||
@Column(name = "is_active")
|
||||
private boolean isActive = false;
|
||||
private Boolean isActive = true;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
private List<AuthToken> tokens = new ArrayList<>();
|
||||
|
||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
private UserNotActive userNotActive;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
private List<UserContent> userContents = new ArrayList<>();
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
private List<UserAction> userActions = new ArrayList<>();
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
@@ -96,8 +90,4 @@ public class User {
|
||||
@JsonIgnore
|
||||
@ToString.Exclude
|
||||
private List<ImageProtection> imageProtections = new ArrayList<>();
|
||||
|
||||
@Column(name = "failed_login_attempts")
|
||||
@ColumnDefault("0")
|
||||
private Integer failedLoginAttempts = 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "user_actions")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@ToString
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class UserAction {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long actionId;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
@ToString.Exclude
|
||||
private User user;
|
||||
|
||||
@Column(name = "action", nullable = false, length = 100)
|
||||
private String action;
|
||||
|
||||
@Column(name = "details", columnDefinition = "TEXT")
|
||||
private String details;
|
||||
|
||||
@Column(name = "ip_address", length = 45)
|
||||
private String ipAddress;
|
||||
|
||||
@Column(name = "user_agent", columnDefinition = "TEXT")
|
||||
private String userAgent;
|
||||
|
||||
@CreatedDate
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+1
-2
@@ -1,10 +1,9 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
import ru.soune.nocopy.entity.file.ContentStatus;
|
||||
import ru.soune.nocopy.entity.file.FileType;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
+1
-2
@@ -1,10 +1,9 @@
|
||||
package ru.soune.nocopy.entity.file;
|
||||
package ru.soune.nocopy.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@@ -2,13 +2,10 @@ package ru.soune.nocopy.entity.file;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.GenerationTime;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@@ -19,13 +16,11 @@ import java.time.LocalDateTime;
|
||||
@Table(name = "file_entities")
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class FileEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private String id;
|
||||
|
||||
@Column(name = "support_id", unique = true, updatable = false)
|
||||
private Integer supportId;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@@ -65,14 +60,34 @@ public class FileEntity {
|
||||
@Column(name = "updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@Column(name = "protected_file_path")
|
||||
private String protectedFilePath;
|
||||
|
||||
@Column(name = "protection_status")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private ProtectionStatus protectionStatus;
|
||||
|
||||
@Column(name = "protected_at")
|
||||
private LocalDateTime protectedAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
if (this.status == null) {
|
||||
this.status = FileStatus.ACTIVE;
|
||||
}
|
||||
|
||||
if (this.protectionStatus == null) {
|
||||
this.protectionStatus = ProtectionStatus.NOT_PROTECTED;
|
||||
}
|
||||
|
||||
if (this.createdAt == null) {
|
||||
this.createdAt = LocalDateTime.now();
|
||||
}
|
||||
this.updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
this.updatedAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.soune.nocopy.entity.file;
|
||||
|
||||
public enum ProtectionStatus {
|
||||
NOT_PROTECTED,
|
||||
PROCESSING,
|
||||
PROTECTED,
|
||||
FAILED,
|
||||
FAILED_SAVE
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "email_verification_tokens")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class EmailVerificationToken {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@Column(name = "token", nullable = false, length = 6)
|
||||
private String token;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private LocalDateTime expiresAt = LocalDateTime.now().plusMinutes(15);
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public boolean isExpired() {
|
||||
return LocalDateTime.now().isAfter(expiresAt);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package ru.soune.nocopy.entity.user;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "user_not_active")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@ToString
|
||||
@Builder
|
||||
public class UserNotActive {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
private User user;
|
||||
|
||||
@CreatedDate
|
||||
@Column(name = "created_at", updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "blocked_until")
|
||||
private LocalDateTime blockedUntil;
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package ru.soune.nocopy.handler;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.BaseRequest;
|
||||
import ru.soune.nocopy.dto.BaseResponse;
|
||||
import ru.soune.nocopy.dto.MessageCode;
|
||||
import ru.soune.nocopy.dto.TokenProcessRequest;
|
||||
import ru.soune.nocopy.exception.NotFoundAuthToken;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuthRequestHandler implements RequestHandler {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@Override
|
||||
public BaseResponse handle(BaseRequest request) throws NotFoundAuthToken {
|
||||
TokenProcessRequest tokenProcessRequest = objectMapper.convertValue(request.getMessageBody(),
|
||||
TokenProcessRequest.class);
|
||||
|
||||
authService.useUserAuthToken(tokenProcessRequest.getToken());
|
||||
|
||||
return new BaseResponse(request.getMsgId(),
|
||||
MessageCode.SUCCESS.getCode(),
|
||||
"Token processed successfully",
|
||||
Map.of("token", tokenProcessRequest.getToken()));
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,13 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.*;
|
||||
import ru.soune.nocopy.dto.file.*;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.entity.file.FileStatus;
|
||||
import ru.soune.nocopy.exception.FileEntityNotFoundException;
|
||||
import ru.soune.nocopy.exception.NotFoundAuthToken;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.service.file.FileEntityService;
|
||||
import ru.soune.nocopy.service.file.FileStatsService;
|
||||
|
||||
@@ -26,10 +26,10 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private final FileEntityService fileEntityService;
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
private final FileStatsService fileStatsService;
|
||||
|
||||
private final AuthTokenRepository authTokenRepository;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final FileEntityRepository fileEntityRepository;
|
||||
@@ -62,8 +62,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
.action(action)
|
||||
.availableActions(Arrays.asList(
|
||||
"file_info", "file_by_session", "user_files",
|
||||
"search_files", "storage_usage", "delete_file",
|
||||
"user_files_info"))
|
||||
"search_files", "storage_usage", "delete_file"))
|
||||
.build();
|
||||
|
||||
return new BaseResponse(request.getMsgId(),
|
||||
@@ -81,7 +80,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
}
|
||||
|
||||
private BaseResponse handleGetFilesUserInfo(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
FileInfoUserResponse userFileStats = fileStatsService.getUserFileStats(userId);
|
||||
|
||||
return new BaseResponse(request.getMsgId(),
|
||||
@@ -92,7 +91,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private BaseResponse handleGetFileInfo(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
try {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
FileEntityResponse fileInfo = fileEntityService.getById(fileRequest.getFileId(), request.getVersion());
|
||||
|
||||
if (!fileInfo.getUserId().equals(userId)) {
|
||||
@@ -123,7 +122,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private BaseResponse handleGetFileBySession(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
try {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
FileEntityResponse fileInfo = fileEntityService.getByUploadSessionId(fileRequest.getUploadSessionId(),
|
||||
request.getVersion());
|
||||
|
||||
@@ -155,7 +154,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private BaseResponse handleGetUserFiles(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
try {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
int page = fileRequest.getPage() != null ? fileRequest.getPage() : 1;
|
||||
int pageSize = fileRequest.getPageSize() != null ? fileRequest.getPageSize() : 20;
|
||||
|
||||
@@ -182,7 +181,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private BaseResponse handleSearchFiles(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
try {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
int page = fileRequest.getPage() != null ? fileRequest.getPage() : 1;
|
||||
int pageSize = fileRequest.getPageSize() != null ? fileRequest.getPageSize() : 20;
|
||||
|
||||
@@ -229,7 +228,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private BaseResponse handleGetStorageUsage(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
try {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
long usage = fileEntityService.getUserStorageUsed(userId);
|
||||
|
||||
StorageUsageResponse response = StorageUsageResponse.builder()
|
||||
@@ -259,7 +258,7 @@ public class FileEntityHandler implements RequestHandler {
|
||||
|
||||
private BaseResponse handleDeleteFile(BaseRequest request, FileEntityRequest fileRequest) {
|
||||
try {
|
||||
Long userId = authService.useUserAuthToken(fileRequest.getToken());
|
||||
Long userId = getUserIdFromToken(fileRequest.getToken());
|
||||
String fileId = fileRequest.getFileId();
|
||||
FileEntityResponse fileInfo = fileEntityService.getById(fileId, request.getVersion());
|
||||
DeleteFileResponse response;
|
||||
@@ -306,6 +305,20 @@ public class FileEntityHandler implements RequestHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private Long getUserIdFromToken(String token) {
|
||||
if (token == null || token.isBlank()) {
|
||||
throw new NotFoundAuthToken("Token is required");
|
||||
}
|
||||
|
||||
if (token.startsWith("Bearer ")) {
|
||||
token = token.replace("Bearer ", "");
|
||||
}
|
||||
|
||||
AuthToken authToken = authTokenRepository.findByToken(token)
|
||||
.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
||||
return authToken.getUser().getId();
|
||||
}
|
||||
|
||||
private String formatFileSize(long size) {
|
||||
if (size < 1024) return size + " B";
|
||||
int exp = (int) (Math.log(size) / Math.log(1024));
|
||||
|
||||
@@ -10,14 +10,13 @@ import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.FieldError;
|
||||
import ru.soune.nocopy.dto.*;
|
||||
import ru.soune.nocopy.dto.file.*;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.file.FileType;
|
||||
import ru.soune.nocopy.entity.file.FileUploadSession;
|
||||
import ru.soune.nocopy.exception.*;
|
||||
import ru.soune.nocopy.handler.validator.FileUploadRequestValidator;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.FileUploadSessionRepository;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.service.file.FileUploadService;
|
||||
|
||||
import java.util.*;
|
||||
@@ -29,8 +28,6 @@ import java.util.stream.Collectors;
|
||||
public class FileUploadHandler implements RequestHandler {
|
||||
private final FileUploadService fileUploadService;
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
private final AuthTokenRepository authTokenRepository;
|
||||
|
||||
private final FileUploadSessionRepository fileUploadSessionRepository;
|
||||
@@ -89,7 +86,8 @@ public class FileUploadHandler implements RequestHandler {
|
||||
MessageCode.INVALID_TOKEN.getDescription(), Map.of("token", token));
|
||||
}
|
||||
|
||||
Long userId = authService.useUserAuthToken(token);
|
||||
AuthToken authToken = tokenOptional.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
||||
|
||||
BindingResult bindingResult = new BeanPropertyBindingResult(fileRequest, "fileRequest");
|
||||
fileUploadRequestValidator.validate(fileRequest, bindingResult);
|
||||
|
||||
@@ -107,7 +105,7 @@ public class FileUploadHandler implements RequestHandler {
|
||||
}
|
||||
|
||||
FileUploadSession session = fileUploadService.initUpload(
|
||||
userId,
|
||||
authToken.getUser().getId(),
|
||||
fileRequest.getFileName(),
|
||||
fileRequest.getFileType(),
|
||||
fileRequest.getExtension(),
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package ru.soune.nocopy.handler;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.BaseRequest;
|
||||
import ru.soune.nocopy.dto.BaseResponse;
|
||||
import ru.soune.nocopy.dto.MessageCode;
|
||||
import ru.soune.nocopy.dto.file.ImageSearchRequest;
|
||||
import ru.soune.nocopy.dto.file.YandexSearchResponse;
|
||||
import ru.soune.nocopy.service.search.YandexSearchService;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ImageFoundRequestHandler implements RequestHandler {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final YandexSearchService yandexSearchService;
|
||||
|
||||
@Override
|
||||
public BaseResponse handle(BaseRequest request) throws Exception {
|
||||
ImageSearchRequest imageSearchRequest = objectMapper.convertValue(request.getMessageBody(),
|
||||
ImageSearchRequest.class);
|
||||
|
||||
String fileId = imageSearchRequest.getFileId();
|
||||
|
||||
YandexSearchResponse response = yandexSearchService.searchByFileEntity(fileId);
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
|
||||
MessageCode.SUCCESS.getDescription(), response);
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,10 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.*;
|
||||
import ru.soune.nocopy.dto.register.LoginAnswer;
|
||||
import ru.soune.nocopy.dto.register.LoginRequest;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.service.AuthService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
@@ -20,17 +17,14 @@ import java.util.Map;
|
||||
public class LoginRequestHandler implements RequestHandler {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public BaseResponse handle(BaseRequest request) {
|
||||
LoginRequest loginRequest = objectMapper.convertValue(request.getMessageBody(), LoginRequest.class);
|
||||
User user = userRepository.findByEmail(loginRequest.getEmail());
|
||||
|
||||
if (user == null) {
|
||||
if (!userRepository.existsByEmail(loginRequest.getEmail())) {
|
||||
LoginAnswer loginAnswer = new LoginAnswer();
|
||||
loginAnswer.setFieldErrors(Arrays.asList(Map.of("email", loginRequest.getEmail())));
|
||||
|
||||
@@ -39,24 +33,10 @@ public class LoginRequestHandler implements RequestHandler {
|
||||
MessageCode.AUTH_EMAIL_NOT_FOUND.getDescription(), loginAnswer));
|
||||
}
|
||||
|
||||
if (!user.isActive() && !user.isEmailVerified()) {
|
||||
LoginAnswer loginAnswer = new LoginAnswer();
|
||||
|
||||
loginAnswer.setFieldErrors(Arrays.asList(Map.of(
|
||||
"verified", String.valueOf(user.isEmailVerified()),
|
||||
"isActive", String.valueOf(user.isActive()))));
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.USER_NOT_VERIFIED.getCode(),
|
||||
MessageCode.USER_NOT_VERIFIED.getDescription(), loginAnswer);
|
||||
}
|
||||
|
||||
AuthToken authToken = authService.login(loginRequest);
|
||||
String token = authToken.getToken();
|
||||
|
||||
LoginAnswer loginAnswer = new LoginAnswer();
|
||||
loginAnswer.setToken(token);
|
||||
|
||||
authService.useUserAuthToken(token);
|
||||
loginAnswer.setToken(authToken.getToken());
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
|
||||
MessageCode.SUCCESS.getDescription(), loginAnswer);
|
||||
|
||||
@@ -4,14 +4,12 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.*;
|
||||
import ru.soune.nocopy.dto.register.LogOutAnswer;
|
||||
import ru.soune.nocopy.dto.register.LogoutRequest;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.service.AuthService;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
@@ -33,16 +31,16 @@ public class LogoutRequestHandler implements RequestHandler {
|
||||
LogoutRequest logoutRequest = objectMapper.convertValue(request.getMessageBody(), LogoutRequest.class);
|
||||
|
||||
Optional<AuthToken> opToken = authTokenRepository.findByToken(logoutRequest.getToken());
|
||||
User user = userRepository.findByEmail(logoutRequest.getEmail());
|
||||
Optional<User> user = userRepository.findByEmail(logoutRequest.getEmail());
|
||||
|
||||
if (opToken.isEmpty() || user == null) {
|
||||
if (opToken.isEmpty() || user.isEmpty()) {
|
||||
throw new NotValidFieldException("User with email or token not found",
|
||||
new BaseResponse(request.getMsgId(), MessageCode.AUTH_EMAIL_OR_TOKEN_NOT_FOUND.getCode(),
|
||||
MessageCode.AUTH_EMAIL_OR_TOKEN_NOT_FOUND.getDescription(),
|
||||
new LogoutRequest(logoutRequest.getEmail(), logoutRequest.getToken())));
|
||||
}
|
||||
|
||||
if (!Objects.equals(opToken.get().getUser().getId(), user.getId())) {
|
||||
if (!Objects.equals(opToken.get().getUser().getId(), user.get().getId())) {
|
||||
throw new NotValidFieldException("User token mismatch with user",
|
||||
new BaseResponse(request.getMsgId(), MessageCode.AUTH_TOKEN_MISMATCH.getCode(),
|
||||
MessageCode.AUTH_TOKEN_MISMATCH.getDescription(),
|
||||
|
||||
@@ -7,16 +7,12 @@ import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.BeanPropertyBindingResult;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import ru.soune.nocopy.dto.*;
|
||||
import ru.soune.nocopy.dto.register.RegAnswer;
|
||||
import ru.soune.nocopy.dto.register.RegRequest;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.EmailVerificationToken;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.exception.ValidationException;
|
||||
import ru.soune.nocopy.handler.validator.RegRequestValidator;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.service.mail.EmailService;
|
||||
import ru.soune.nocopy.service.AuthService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
@@ -33,8 +29,6 @@ public class RegRequestHandler implements RequestHandler {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final EmailService emailService;
|
||||
|
||||
@Override
|
||||
public BaseResponse handle(BaseRequest request) throws ValidationException {
|
||||
RegRequest regRequest = objectMapper.convertValue(request.getMessageBody(), RegRequest.class);
|
||||
@@ -51,7 +45,6 @@ public class RegRequestHandler implements RequestHandler {
|
||||
}
|
||||
|
||||
BindingResult bindingResult = new BeanPropertyBindingResult(regRequest, "regRequest");
|
||||
|
||||
regRequestValidator.validate(regRequest, bindingResult);
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
@@ -59,16 +52,9 @@ public class RegRequestHandler implements RequestHandler {
|
||||
}
|
||||
|
||||
AuthToken authToken = authService.register(regRequest);
|
||||
EmailVerificationToken emailToken = emailService.createEmailVerificationToken(authToken);
|
||||
|
||||
emailService.sendVerificationEmail(authToken.getUser(), emailToken.getToken());
|
||||
String token = authToken.getToken();
|
||||
authService.useUserAuthToken(token);
|
||||
|
||||
RegAnswer regAnswer = new RegAnswer();
|
||||
regAnswer.setToken(token);
|
||||
regAnswer.setVerified(false);
|
||||
regAnswer.setActive(false);
|
||||
regAnswer.setToken(authToken.getToken());
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
|
||||
MessageCode.SUCCESS.getDescription(), regAnswer);
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
package ru.soune.nocopy.handler;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.BaseRequest;
|
||||
import ru.soune.nocopy.dto.BaseResponse;
|
||||
import ru.soune.nocopy.dto.MessageCode;
|
||||
import ru.soune.nocopy.dto.file.ActionResponse;
|
||||
import ru.soune.nocopy.dto.register.ResetPasswordRequest;
|
||||
import ru.soune.nocopy.dto.register.ResetPasswordResponse;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.EmailVerificationToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.exception.UserNotFoundException;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.EmailVerificationTokenRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
import ru.soune.nocopy.service.mail.EmailService;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class ResetPasswordHandler implements RequestHandler{
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final EmailService emailService;
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final EmailVerificationTokenRepository emailVerificationTokenRepository;
|
||||
|
||||
private final AuthTokenRepository authTokenRepository;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public BaseResponse handle(BaseRequest request) throws Exception {
|
||||
ResetPasswordRequest resetPasswordRequest = objectMapper.convertValue(request.getMessageBody(),
|
||||
ResetPasswordRequest.class);
|
||||
String action = resetPasswordRequest.getAction();
|
||||
User user = userRepository.findByEmail(resetPasswordRequest.getEmail());
|
||||
AuthToken authToken;
|
||||
|
||||
if (user == null) {
|
||||
throw new UserNotFoundException("User not found with email: " + resetPasswordRequest.getEmail());
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "resetPassword":
|
||||
authToken = authService.generateAuthToken(user);
|
||||
|
||||
EmailVerificationToken emailToken = emailService.createEmailVerificationToken(authToken);
|
||||
|
||||
emailService.sendResetPasswordEmail(authToken.getUser(), emailToken.getToken());
|
||||
|
||||
return successResponse(request, authToken, user, MessageCode.SUCCESS.getDescription());
|
||||
case "confirmVerification":
|
||||
String verifyToken = resetPasswordRequest.getVerifyToken();
|
||||
|
||||
EmailVerificationToken verificationToken =
|
||||
emailVerificationTokenRepository.findByUserIdAndToken(user.getId(), verifyToken);
|
||||
|
||||
if (verificationToken == null) {
|
||||
throw new NotValidFieldException("Verification token not found",
|
||||
new BaseResponse(request.getMsgId(), MessageCode.INVALID_TOKEN.getCode(),
|
||||
MessageCode.INVALID_TOKEN.getDescription(), Map.of("verifyToken", verifyToken)));
|
||||
}
|
||||
List<AuthToken> authTokens = authTokenRepository.findByUserId(user.getId());
|
||||
|
||||
authToken = authTokens.isEmpty() ? authService.generateAuthToken(user): authTokens.getFirst();
|
||||
|
||||
user.setPassword(passwordEncoder.encode(resetPasswordRequest.getPassword()));
|
||||
user.setActive(true);
|
||||
|
||||
emailVerificationTokenRepository.delete(verificationToken);
|
||||
|
||||
User saveUser = userRepository.save(user);
|
||||
|
||||
return successResponse(request, authToken, saveUser, MessageCode.SUCCESS.getDescription());
|
||||
default:
|
||||
ActionResponse response = ActionResponse.builder()
|
||||
.action(action)
|
||||
.availableActions(Arrays.asList("confirmVerification", "resetPassword"))
|
||||
.build();
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.INVALID_ACTION.getCode(),
|
||||
"Invalid action: " + action, response);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private BaseResponse successResponse(BaseRequest request, AuthToken authToken, User user, String message) {
|
||||
ResetPasswordResponse resetPasswordResponse = new ResetPasswordResponse();
|
||||
resetPasswordResponse.setAuthToken(authToken.getToken());
|
||||
resetPasswordResponse.setUserId(user.getId());
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(), message, resetPasswordResponse);
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package ru.soune.nocopy.handler;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.dto.BaseRequest;
|
||||
import ru.soune.nocopy.dto.BaseResponse;
|
||||
import ru.soune.nocopy.dto.MessageCode;
|
||||
import ru.soune.nocopy.dto.register.RegAnswer;
|
||||
import ru.soune.nocopy.dto.register.VerifyUserRequest;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.EmailVerificationToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.exception.UserNotFoundException;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.EmailVerificationTokenRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
import ru.soune.nocopy.service.mail.EmailService;
|
||||
import ru.soune.nocopy.service.register.AuthService;
|
||||
import ru.soune.nocopy.service.user.UserService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class VerifyRegisterUserHandler implements RequestHandler {
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final EmailVerificationTokenRepository emailVerificationTokenRepository;
|
||||
|
||||
private final EmailService emailService;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
private final AuthTokenRepository authTokenRepository;
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@Override
|
||||
public BaseResponse handle(BaseRequest request) {
|
||||
VerifyUserRequest verifyUserRequest = objectMapper.convertValue(request.getMessageBody(), VerifyUserRequest.class);
|
||||
|
||||
Long userId = verifyUserRequest.getUserId();
|
||||
|
||||
User user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new UserNotFoundException("User not found with id: " + userId));
|
||||
|
||||
List<AuthToken> authTokens = authTokenRepository.findByUserId(user.getId());
|
||||
|
||||
AuthToken authToken = authTokens.isEmpty() ? authService.generateAuthToken(user): authTokens.getFirst();
|
||||
|
||||
if (verifyUserRequest.getResend() != null && verifyUserRequest.getResend() == 1) {
|
||||
return handleResend(request, user, authToken);
|
||||
}
|
||||
|
||||
return handleVerify(request, user, authToken, verifyUserRequest.getVerifyToken());
|
||||
}
|
||||
|
||||
private BaseResponse handleResend(BaseRequest request, User user, AuthToken authToken) {
|
||||
|
||||
EmailVerificationToken token = emailVerificationTokenRepository.findByUserId(user.getId());
|
||||
|
||||
if (token != null && !token.isExpired()) {
|
||||
emailService.sendVerificationEmail(user, token.getToken());
|
||||
|
||||
log.info("Verification token resent for user {}", user.getEmail());
|
||||
return successResponse(request, authToken, "Verification code has been resent", false, false);
|
||||
}
|
||||
|
||||
if (token != null) {
|
||||
emailVerificationTokenRepository.delete(token);
|
||||
}
|
||||
|
||||
EmailVerificationToken newToken = emailService.createEmailVerificationToken(authToken);
|
||||
|
||||
emailService.sendVerificationEmail(user, newToken.getToken());
|
||||
|
||||
log.info("New verification token generated for user {}", user.getEmail());
|
||||
|
||||
return successResponse(request, authToken, "New verification code has been sent",
|
||||
false, false);
|
||||
}
|
||||
|
||||
|
||||
private BaseResponse handleVerify(BaseRequest request, User user, AuthToken authToken, String providedToken) {
|
||||
|
||||
EmailVerificationToken token = emailVerificationTokenRepository.findByUserIdAndToken(user.getId(), providedToken);
|
||||
|
||||
if (token == null || token.isExpired()) {
|
||||
throw new NotValidFieldException("Invalid or expired token",
|
||||
new BaseResponse(request.getMsgId(), MessageCode.INVALID_TOKEN.getCode(),
|
||||
MessageCode.INVALID_TOKEN.getDescription(), Map.of("userId", user.getId())));
|
||||
}
|
||||
|
||||
User updateUser = userService.activateAndVerifyUser(user.getId());
|
||||
emailVerificationTokenRepository.delete(token);
|
||||
|
||||
return successResponse(request, authToken, MessageCode.SUCCESS.getDescription(), updateUser.isActive(),
|
||||
updateUser.isEmailVerified());
|
||||
}
|
||||
|
||||
private BaseResponse successResponse(BaseRequest request, AuthToken authToken, String message, boolean isActive,
|
||||
boolean isVerified) {
|
||||
|
||||
RegAnswer regAnswer = new RegAnswer();
|
||||
regAnswer.setToken(authToken.getToken());
|
||||
regAnswer.setVerified(isVerified);
|
||||
regAnswer.setActive(isActive);
|
||||
|
||||
return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(), message, regAnswer);
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,13 @@ import org.apache.commons.validator.routines.EmailValidator;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
import ru.soune.nocopy.dto.register.RegRequest;
|
||||
import ru.soune.nocopy.dto.RegRequest;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Component
|
||||
public class RegRequestValidator implements Validator {
|
||||
private static final String COMPANY_REGEX = "^[a-zA-Zа-яА-ЯёЁ0-9\\s\\-&.,'()\"\"«»„‟”“”‘'’‹›❛❜❝❞〝〞〟]{1,200}$";
|
||||
private static final String COMPANY_REGEX = "^[a-zA-Zа-яА-ЯёЁ0-9\\s\\-&.,'()]{0,200}$";
|
||||
|
||||
private static final String NAME_REGEX = "^[a-zA-Zа-яА-ЯёЁ\\s\\-'.]{2,100}$";
|
||||
|
||||
@@ -71,6 +71,21 @@ public class RegRequestValidator implements Validator {
|
||||
errors.rejectValue("companyName", "companyName.invalid.chars",
|
||||
"Company name contains invalid characters");
|
||||
}
|
||||
|
||||
validateForbiddenWords(trimmedCompany, "companyName", errors,
|
||||
Arrays.asList("admin", "root", "system", "test"));
|
||||
}
|
||||
|
||||
private void validateForbiddenWords(String text, String fieldName,
|
||||
Errors errors, List<String> forbiddenWords) {
|
||||
String lowerText = text.toLowerCase();
|
||||
for (String word : forbiddenWords) {
|
||||
if (lowerText.contains(word)) {
|
||||
errors.rejectValue(fieldName, fieldName + ".forbidden.word",
|
||||
"Contains forbidden word: " + word);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateEmail(String email, Errors errors) {
|
||||
@@ -138,15 +153,6 @@ public class RegRequestValidator implements Validator {
|
||||
errors.rejectValue("password", "password.contains.spaces",
|
||||
"Password cannot contain spaces");
|
||||
}
|
||||
|
||||
// recomment if need complexity
|
||||
// checkPasswordComplexity(password, errors);
|
||||
|
||||
// reccoment if need check simply standart password
|
||||
// checkCommonPasswords(password, errors);
|
||||
|
||||
// reccoment if need check simply standart password
|
||||
// checkForSequences(password, errors);
|
||||
}
|
||||
|
||||
private void checkPasswordComplexity(String password, Errors errors) {
|
||||
|
||||
@@ -4,8 +4,8 @@ import org.mapstruct.Mapper;
|
||||
import org.mapstruct.MappingTarget;
|
||||
import org.mapstruct.NullValuePropertyMappingStrategy;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
import ru.soune.nocopy.dto.user.UserContentUpdateRequest;
|
||||
import ru.soune.nocopy.entity.user.UserContent;
|
||||
import ru.soune.nocopy.dto.UserContentUpdateRequest;
|
||||
import ru.soune.nocopy.entity.UserContent;
|
||||
|
||||
@Mapper(componentModel = "spring",
|
||||
nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
|
||||
|
||||
@@ -3,8 +3,8 @@ package ru.soune.nocopy.mapper;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.NullValuePropertyMappingStrategy;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
import ru.soune.nocopy.dto.user.UserDTO;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.dto.UserDTO;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
|
||||
@Mapper(componentModel = "spring",
|
||||
nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
|
||||
|
||||
@@ -2,17 +2,13 @@ package ru.soune.nocopy.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AuthTokenRepository extends JpaRepository<AuthToken, Long> {
|
||||
List<AuthToken> findByExpiresAtBefore(LocalDateTime expiresAtBefore);
|
||||
Optional<AuthToken> findByLastUsedAtBefore(LocalDateTime lastUsedAt);
|
||||
Optional<AuthToken> findByTokenAndExpiresAtAfter(String token, LocalDate expiresAtAfter);
|
||||
Optional<AuthToken> findByToken(String token);
|
||||
Optional<AuthToken> findByUserIdAndIsActive(Long userId, boolean isActive);
|
||||
List<AuthToken> findByUserId(Long userId);
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package ru.soune.nocopy.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.soune.nocopy.entity.user.EmailVerificationToken;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface EmailVerificationTokenRepository extends JpaRepository<EmailVerificationToken, Long> {
|
||||
Optional<EmailVerificationToken> findByToken(String token);
|
||||
EmailVerificationToken findByUserIdAndToken(Long userId, String token);
|
||||
List<EmailVerificationToken> findByExpiresAtBefore(LocalDateTime expiresAtBefore);
|
||||
EmailVerificationToken findByUserId(Long userId);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.entity.file.FileStatus;
|
||||
import ru.soune.nocopy.entity.file.ProtectionStatus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -14,7 +15,6 @@ import java.util.Optional;
|
||||
public interface FileEntityRepository extends JpaRepository<FileEntity, String> {
|
||||
|
||||
List<FileEntity> findByUserId(Long userId);
|
||||
Optional<FileEntity> findByUserIdAndChecksum(Long userId, String imageHash);
|
||||
|
||||
List<FileEntity> findByUserIdAndStatus(Long userId, FileStatus status);
|
||||
|
||||
@@ -22,11 +22,17 @@ public interface FileEntityRepository extends JpaRepository<FileEntity, String>
|
||||
|
||||
Optional<FileEntity> findByUploadSessionId(String uploadSessionId);
|
||||
|
||||
List<FileEntity> findByProtectionStatus(ProtectionStatus protectionStatus);
|
||||
|
||||
boolean existsByFilePath(String filePath);
|
||||
|
||||
@Query("SELECT SUM(f.fileSize) FROM FileEntity f WHERE f.userId = :userId AND f.status = 'ACTIVE'")
|
||||
Long getTotalSizeByUserId(@Param("userId") Long userId);
|
||||
|
||||
@Query("SELECT f FROM FileEntity f WHERE f.protectionStatus = null AND f.status = 'ACTIVE' OR " +
|
||||
"f.protectionStatus = 'NOT_PROTECTED' AND f.status = 'ACTIVE'")
|
||||
List<FileEntity> findAllActiveFilesAndNotProtected();
|
||||
|
||||
@Query("SELECT f FROM FileEntity f WHERE f.userId = :userId AND f.originalFileName LIKE %:keyword%")
|
||||
List<FileEntity> searchByFileName(@Param("userId") Long userId, @Param("keyword") String keyword);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ package ru.soune.nocopy.repository;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.soune.nocopy.entity.file.FileType;
|
||||
import ru.soune.nocopy.entity.user.UserContent;
|
||||
import ru.soune.nocopy.entity.UserContent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package ru.soune.nocopy.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import ru.soune.nocopy.entity.user.UserNotActive;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface UserNotActiveRepository extends JpaRepository<UserNotActive, Long> {
|
||||
Optional<UserNotActive> findByUserId(Long userId);
|
||||
List<UserNotActive> findByBlockedUntilBefore(LocalDateTime now);
|
||||
|
||||
}
|
||||
@@ -2,12 +2,12 @@ package ru.soune.nocopy.repository;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
User findByEmail(String email);
|
||||
Optional<User> findByEmail(String email);
|
||||
boolean existsByEmail(String email);
|
||||
boolean existsByPhone(@Size(min = 11, max = 14) String phone);
|
||||
}
|
||||
|
||||
+13
-81
@@ -1,4 +1,4 @@
|
||||
package ru.soune.nocopy.service.register;
|
||||
package ru.soune.nocopy.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.MessageSource;
|
||||
@@ -6,21 +6,18 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.dto.*;
|
||||
import ru.soune.nocopy.dto.register.LoginAnswer;
|
||||
import ru.soune.nocopy.dto.register.LoginRequest;
|
||||
import ru.soune.nocopy.dto.register.RegRequest;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.entity.user.UserNotActive;
|
||||
import ru.soune.nocopy.exception.NotFoundAuthToken;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.UserNotActiveRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -32,7 +29,7 @@ public class AuthService {
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final UserNotActiveRepository userNotActiveRepository;
|
||||
private final MessageSource messageSource;
|
||||
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
@@ -53,55 +50,21 @@ public class AuthService {
|
||||
|
||||
User savedUser = userRepository.save(user);
|
||||
|
||||
AuthToken authToken = genereateAuthToken(savedUser);
|
||||
AuthToken authToken = new AuthToken();
|
||||
authToken.setToken(generateAuthToken());
|
||||
authToken.setUser(savedUser);
|
||||
|
||||
return authTokenRepository.save(authToken);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Long useUserAuthToken(String token) {
|
||||
if (token == null || token.isBlank()) {
|
||||
throw new NotFoundAuthToken("Token is required");
|
||||
}
|
||||
|
||||
if (token.startsWith("Bearer ")) {
|
||||
token = token.replace("Bearer ", "");
|
||||
}
|
||||
|
||||
AuthToken authToken = authTokenRepository.findByToken(token)
|
||||
.orElseThrow(() -> new NotFoundAuthToken("Token not found"));
|
||||
authToken.setLastUsedAt(LocalDateTime.now());
|
||||
authToken.setExpiresAt(LocalDateTime.now().plusHours(1));
|
||||
|
||||
authTokenRepository.save(authToken);
|
||||
|
||||
return authToken.getUser().getId();
|
||||
}
|
||||
|
||||
public AuthToken login(LoginRequest request) {
|
||||
User user = userRepository.findByEmail(request.getEmail());
|
||||
|
||||
if (!user.isActive()) {
|
||||
throw new NotValidFieldException("User not active", new BaseResponse(20003,
|
||||
MessageCode.USER_NOT_ACTIVE.getCode(),
|
||||
MessageCode.USER_NOT_ACTIVE.getDescription(), Map.of("userId", user.getId())));
|
||||
}
|
||||
Optional<User> userOpt = userRepository.findByEmail(request.getEmail());
|
||||
User user = userOpt.get();
|
||||
|
||||
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
LoginAnswer loginAnswer = new LoginAnswer();
|
||||
loginAnswer.setFieldErrors(Arrays.asList(Map.of("password", request.getPassword())));
|
||||
loginAnswer.setVerified(user.isEmailVerified());
|
||||
loginAnswer.setActive(user.isActive());
|
||||
|
||||
int attempts = user.getFailedLoginAttempts() + 1;
|
||||
user.setFailedLoginAttempts(attempts);
|
||||
|
||||
if (attempts >= 5) {
|
||||
user.setActive(false);
|
||||
blockUser(user);
|
||||
}
|
||||
|
||||
userRepository.save(user);
|
||||
|
||||
throw new NotValidFieldException("Invalid password", new BaseResponse(20003,
|
||||
MessageCode.AUTH_PASSWORD_NOT_MATCHES.getCode(),
|
||||
@@ -109,9 +72,6 @@ public class AuthService {
|
||||
}
|
||||
|
||||
user.setLastLoginAt(LocalDateTime.now());
|
||||
user.setFailedLoginAttempts(0);
|
||||
user.setActive(true);
|
||||
|
||||
User savedUser = userRepository.save(user);
|
||||
|
||||
AuthToken authToken = new AuthToken();
|
||||
@@ -127,37 +87,9 @@ public class AuthService {
|
||||
.ifPresent(authTokenRepository::delete);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthToken generateAuthToken(User user) {
|
||||
return authTokenRepository.save(genereateAuthToken(user));
|
||||
}
|
||||
|
||||
private AuthToken genereateAuthToken(User user) {
|
||||
AuthToken authToken = new AuthToken();
|
||||
authToken.setToken(generateAuthToken());
|
||||
authToken.setUser(user);
|
||||
|
||||
return authToken;
|
||||
}
|
||||
|
||||
private String generateAuthToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
public void blockUser(User user) {
|
||||
Optional<UserNotActive> existing = userNotActiveRepository.findByUserId(user.getId());
|
||||
if (existing.isEmpty()) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
UserNotActive notActive = UserNotActive.builder()
|
||||
.user(user)
|
||||
.createdAt(now)
|
||||
.blockedUntil(now.plusMinutes(15))
|
||||
.build();
|
||||
|
||||
userNotActiveRepository.save(notActive);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package ru.soune.nocopy.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.dto.UserContentRequest;
|
||||
import ru.soune.nocopy.dto.UserContentUpdateRequest;
|
||||
import ru.soune.nocopy.entity.file.FileType;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
import ru.soune.nocopy.entity.UserContent;
|
||||
import ru.soune.nocopy.exception.ContentNotFoundException;
|
||||
import ru.soune.nocopy.exception.UserNotFoundException;
|
||||
import ru.soune.nocopy.mapper.UserContentMapper;
|
||||
import ru.soune.nocopy.repository.UserContentRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class UserContentService {
|
||||
|
||||
private final UserContentRepository userContentRepository;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final UserContentMapper userContentMapper;
|
||||
|
||||
public List<UserContent> findByUser(long userId) {
|
||||
return userContentRepository.findByUserId(userId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserContent addUserContent(UserContentRequest userContentRequest) {
|
||||
UserContent userContent = new UserContent();
|
||||
|
||||
Optional<User> byEmail = userRepository.findByEmail(userContentRequest.userEmail());
|
||||
User user = byEmail.orElseThrow(() -> new UserNotFoundException(userContentRequest.userEmail()));
|
||||
|
||||
userContent.setUser(user);
|
||||
userContent.setFilename(userContentRequest.fileName());
|
||||
userContent.setFileExtension(userContentRequest.fileExtension());
|
||||
userContent.setFilePath(userContentRequest.filePath());
|
||||
userContent.setFileType(FileType.valueOf(userContentRequest.fileType()));
|
||||
userContent.setOriginalFilename(userContentRequest.originalFilename());
|
||||
userContent.setProtectionLevel(userContentRequest.protectionLevel());
|
||||
userContent.setFileSize(userContentRequest.fileSize());
|
||||
|
||||
//TODO add
|
||||
// @Column(name = "protection_hash", length = 64)
|
||||
// private String protectionHash;
|
||||
// @Column(name = "watermark_id", length = 50)
|
||||
// private String watermarkId;
|
||||
|
||||
return userContentRepository.save(userContent);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserContent updateUserContent(UserContentUpdateRequest userContentRequest) {
|
||||
UserContent entity = userContentRepository.findById(userContentRequest.id())
|
||||
.orElseThrow(() -> new ContentNotFoundException("Content not found with: " + userContentRequest.id()));
|
||||
|
||||
userContentMapper.updateEntityFromDto(userContentRequest, entity);
|
||||
|
||||
return userContentRepository.save(entity);
|
||||
}
|
||||
|
||||
public void deleteUserContent(long userContentId) {
|
||||
userContentRepository.deleteById(userContentId);
|
||||
}
|
||||
}
|
||||
+5
-17
@@ -1,20 +1,18 @@
|
||||
package ru.soune.nocopy.service.user;
|
||||
package ru.soune.nocopy.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.dto.register.ChangePasswordRequest;
|
||||
import ru.soune.nocopy.dto.user.UserDTO;
|
||||
import ru.soune.nocopy.dto.user.UserRequest;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.dto.ChangePasswordRequest;
|
||||
import ru.soune.nocopy.dto.UserDTO;
|
||||
import ru.soune.nocopy.dto.UserRequest;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
import ru.soune.nocopy.exception.InvalidUserEmail;
|
||||
import ru.soune.nocopy.exception.NotValidationPasswordException;
|
||||
import ru.soune.nocopy.exception.UserNotFoundException;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class UserService {
|
||||
@@ -46,16 +44,6 @@ public class UserService {
|
||||
return mapToDTO(updatedUser);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User activateAndVerifyUser(long userId) {
|
||||
Optional<User> users = userRepository.findById(userId);
|
||||
User user = users.orElseThrow(() -> new UserNotFoundException("User not found with id: " + userId));
|
||||
user.setActive(true);
|
||||
user.setEmailVerified(true);
|
||||
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
private void updateUserFromRequest(User user, UserRequest request) {
|
||||
if (request.getFullName() != null) {
|
||||
user.setFullName(request.getFullName());
|
||||
@@ -1,48 +0,0 @@
|
||||
package ru.soune.nocopy.service.auth;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.entity.user.UserNotActive;
|
||||
import ru.soune.nocopy.repository.UserNotActiveRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class CleanUpNotActiveUser {
|
||||
|
||||
@Autowired
|
||||
private UserNotActiveRepository userNotActiveRepository;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Transactional
|
||||
@Scheduled(fixedDelay = 600000)
|
||||
public void cleanupNotActiveUsers() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
List<UserNotActive> expiredTokens = userNotActiveRepository.findByBlockedUntilBefore(now);
|
||||
|
||||
for (UserNotActive userNotActive : expiredTokens) {
|
||||
User user = userNotActive.getUser();
|
||||
user.setActive(true);
|
||||
user.setFailedLoginAttempts(0);
|
||||
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
if (!expiredTokens.isEmpty()) {
|
||||
userNotActiveRepository.deleteAll(expiredTokens);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package ru.soune.nocopy.service.auth;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class CleanupTokenSessionsService {
|
||||
@Autowired
|
||||
private AuthTokenRepository authTokenRepository;
|
||||
|
||||
@Value("${file.storage.auth-token-life-hours}")
|
||||
private int authTokenLife;
|
||||
|
||||
@Transactional
|
||||
@Scheduled(fixedDelay = 30000)
|
||||
public void cleanupExpiredTokens() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
List<AuthToken> expiredTokens = authTokenRepository.findByExpiresAtBefore(now);
|
||||
|
||||
if (!expiredTokens.isEmpty()) {
|
||||
authTokenRepository.deleteAll(expiredTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -222,7 +223,6 @@ public class FileEntityService {
|
||||
.formattedSize(formatFileSize(fileEntity.getFileSize()))
|
||||
.downloadUrl("/api/v" + version + "/files/download/" + fileEntity.getId())
|
||||
.existsOnDisk(existsOnDisk)
|
||||
.supportId(fileEntity.getSupportId())
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package ru.soune.nocopy.service.file;
|
||||
|
||||
import com.vrt.NoCopyFileService;
|
||||
import com.vrt.fileprotection.FileProtector;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.entity.file.ProtectionStatus;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FileProcessingOrchestrator {
|
||||
|
||||
private final NoCopyFileService noCopyFileService;
|
||||
|
||||
private final FileEntityRepository fileRepository;
|
||||
|
||||
public void initializeProcessingQueue() {
|
||||
List<FileEntity> filesToProtect = fileRepository.findByProtectionStatus(ProtectionStatus.NOT_PROTECTED);
|
||||
|
||||
for (FileEntity fileEntity : filesToProtect) {
|
||||
try {
|
||||
FileProtector.FileInfo fileInfo = createFileInfo(fileEntity);
|
||||
|
||||
noCopyFileService.addFile(fileInfo);
|
||||
|
||||
log.info("Add to query: {}", fileEntity.getOriginalFileName());
|
||||
} catch (Exception e) {
|
||||
log.error("Fail add to query: {}", fileEntity.getId(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 120000)
|
||||
public void checkNewFilesForProtection() {
|
||||
List<FileEntity> newFiles = fileRepository.findAllActiveFilesAndNotProtected();
|
||||
|
||||
for (FileEntity fileEntity : newFiles) {
|
||||
FileProtector.FileInfo fileInfo = createFileInfo(fileEntity);
|
||||
|
||||
noCopyFileService.addFile(fileInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private FileProtector.FileInfo createFileInfo(FileEntity fileEntity) {
|
||||
FileProtector.Type type = determineFileType(fileEntity.getMimeType());
|
||||
|
||||
return new FileProtector.FileInfo(type, fileEntity.getId(), String.valueOf(fileEntity.getUserId()));
|
||||
}
|
||||
|
||||
private FileProtector.Type determineFileType(String mimeType) {
|
||||
if (mimeType == null) {
|
||||
return FileProtector.Type.IMAGE;
|
||||
}
|
||||
|
||||
if (mimeType.startsWith("image")) {
|
||||
return FileProtector.Type.IMAGE;
|
||||
} else if (mimeType.startsWith("video")) {
|
||||
return FileProtector.Type.VIDEO;
|
||||
} else if (mimeType.startsWith("audio")) {
|
||||
return FileProtector.Type.AUDIO;
|
||||
} else {
|
||||
return FileProtector.Type.IMAGE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,7 +102,7 @@ public class FileUploadServiceImpl implements FileUploadService {
|
||||
int totalChunks = (int) Math.ceil((double) fileSize / chunkSize);
|
||||
log.debug("File will be split into {} chunks (chunk size: {} bytes)",
|
||||
totalChunks, chunkSize);
|
||||
Long chunkSize = totalChunks == 1 ? fileSize : 1000000L;
|
||||
Long chunkSize = totalChunks == 1 ? fileSize : 1048576L;
|
||||
|
||||
FileUploadSession session = FileUploadSession.builder()
|
||||
.userId(userId)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package ru.soune.nocopy.service.file;
|
||||
|
||||
import com.vrt.fileprotection.FileProtector;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.entity.file.ProtectionStatus;
|
||||
import ru.soune.nocopy.exception.FileEntityNotFoundException;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class NoCopyProcessingListener implements FileProtector.ProcessingListener {
|
||||
|
||||
private final FileEntityRepository fileEntityRepository;
|
||||
|
||||
@Override
|
||||
public void onStartProcessing(FileProtector.FileInfo fileInfo) {
|
||||
changeStatus(ProtectionStatus.PROCESSING, fileInfo.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProcessingFailed(FileProtector.FileInfo fileInfo) {
|
||||
changeStatus(ProtectionStatus.FAILED, fileInfo.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSavingFailed(FileProtector.FileInfo fileInfo) {
|
||||
changeStatus(ProtectionStatus.FAILED_SAVE, fileInfo.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinish(FileProtector.FileInfo fileInfo) {
|
||||
changeStatus(ProtectionStatus.PROTECTED, fileInfo.getId());;
|
||||
}
|
||||
|
||||
private void changeStatus(ProtectionStatus newStatus, String fileId) {
|
||||
FileEntity fileEntity = fileEntityRepository.findById(fileId)
|
||||
.orElseThrow(() -> new FileEntityNotFoundException(fileId));
|
||||
fileEntity.setProtectionStatus(newStatus);
|
||||
|
||||
fileEntityRepository.save(fileEntity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package ru.soune.nocopy.service.file;
|
||||
|
||||
import com.vrt.fileprotection.FileProtector;
|
||||
import com.vrt.fileprotection.OperationResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ProtectionFileProvider implements FileProtector.FileProvider {
|
||||
|
||||
|
||||
private final FileEntityRepository fileRepository;
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public File getImageFile(@NotNull String id) {
|
||||
return getFileById(id);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public File getVideoFile(@NotNull String id) {
|
||||
return getFileById(id);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public File getAudioFile(@NotNull String id) {
|
||||
return getFileById(id);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public com.vrt.fileprotection.OperationResult writeSignature(@NotNull String s, @NotNull byte[] bytes) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public com.vrt.fileprotection.OperationResult writeAudioFile(@NotNull String id, @NotNull byte[] data, @Nullable String fileExt) {
|
||||
try {
|
||||
writeProtectedFile(id, data, fileExt);
|
||||
return OperationResult.Companion.success();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create protected file: {}", id, e);
|
||||
return OperationResult.Companion.failure("Failed to create protected file");
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public com.vrt.fileprotection.OperationResult writeVideoFile(@NotNull String id, @NotNull byte[] data, @Nullable String fileExt) {
|
||||
try {
|
||||
writeProtectedFile(id, data, fileExt);
|
||||
return OperationResult.Companion.success();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create protected file: {}", id, e);
|
||||
return OperationResult.Companion.failure("Failed to create protected file");
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public com.vrt.fileprotection.OperationResult writeImageFile(@NotNull String id, @NotNull byte[] data, @Nullable String fileExt) {
|
||||
try {
|
||||
writeProtectedFile(id, data, fileExt);
|
||||
return OperationResult.Companion.success();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create protected file: {}", id, e);
|
||||
return OperationResult.Companion.failure("Failed to create protected file");
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public File getSignature(@NotNull String s) {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void writeProtectedFile(String id, byte[] data, String fileExt) throws IOException {
|
||||
FileEntity fileEntity = fileRepository.findById(id)
|
||||
.orElseThrow(() -> new RuntimeException("File not found: " + id));
|
||||
|
||||
String extension = determineFileExtension(fileExt, fileEntity);
|
||||
Path protectedFilePath = prepareProtectedPath(fileEntity, extension);
|
||||
|
||||
if (Files.exists(protectedFilePath)) {
|
||||
Files.delete(protectedFilePath);
|
||||
}
|
||||
|
||||
Files.write(protectedFilePath, data);
|
||||
|
||||
fileEntity.setProtectedFilePath(protectedFilePath.toString());
|
||||
fileEntity.setProtectedAt(LocalDateTime.now());
|
||||
fileEntity.setUpdatedAt(LocalDateTime.now());
|
||||
fileEntity.setFileExtension(extension);
|
||||
|
||||
fileRepository.save(fileEntity);
|
||||
}
|
||||
|
||||
|
||||
private File getFileById(String id) {
|
||||
try {
|
||||
FileEntity fileEntity = fileRepository.findById(id).orElseThrow(() ->
|
||||
new RuntimeException("File not found: " + id));
|
||||
|
||||
File file = new File(fileEntity.getFilePath());
|
||||
|
||||
if (!file.exists()) {
|
||||
throw new RuntimeException("File not found on disk: " + fileEntity.getFilePath());
|
||||
}
|
||||
|
||||
return file;
|
||||
} catch (Exception e) {
|
||||
log.error("Error getting file: {}", id, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String determineFileExtension(String fileExt, FileEntity fileEntity) {
|
||||
if (fileExt != null && !fileExt.trim().isEmpty()) {
|
||||
return fileExt;
|
||||
} else {
|
||||
return fileEntity.getFileExtension();
|
||||
}
|
||||
}
|
||||
|
||||
private Path prepareProtectedPath(FileEntity fileEntity, String extension) throws IOException {
|
||||
Path originalPath = Paths.get(fileEntity.getFilePath());
|
||||
|
||||
String pathStr = originalPath.toString();
|
||||
pathStr = pathStr.replaceFirst("/uploads/uploads/", "/uploads/protected/");
|
||||
|
||||
Path protectedPath = Paths.get(pathStr);
|
||||
String fileName = protectedPath.getFileName().toString();
|
||||
|
||||
if (extension != null) {
|
||||
String nameWithoutExt = fileName;
|
||||
int lastDotIndex = fileName.lastIndexOf('.');
|
||||
if (lastDotIndex > 0) {
|
||||
nameWithoutExt = fileName.substring(0, lastDotIndex);
|
||||
}
|
||||
fileName = nameWithoutExt + "." + extension;
|
||||
|
||||
protectedPath = protectedPath.getParent().resolve(fileName);
|
||||
}
|
||||
|
||||
Files.createDirectories(protectedPath.getParent());
|
||||
|
||||
return protectedPath;
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package ru.soune.nocopy.service.mail;
|
||||
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.entity.user.AuthToken;
|
||||
import ru.soune.nocopy.entity.user.EmailVerificationToken;
|
||||
import ru.soune.nocopy.entity.user.User;
|
||||
import ru.soune.nocopy.repository.EmailVerificationTokenRepository;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class EmailService {
|
||||
|
||||
private final JavaMailSender mailSender;
|
||||
|
||||
private final EmailVerificationTokenRepository emailVerificationTokenRepository;
|
||||
|
||||
@Value("${app.email.verification.standart-subject}")
|
||||
private String standartSubject;
|
||||
|
||||
@Value("${app.email.verification.drop-password-subject}")
|
||||
private String dropPasswordSubject;
|
||||
|
||||
@Value("${app.email.verification.standart-address-from}")
|
||||
private String standartAdressFrom;
|
||||
|
||||
@Value("${app.email.verification.user}")
|
||||
private String user;
|
||||
|
||||
public void sendVerificationEmail(User user, String code) {
|
||||
try {
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
|
||||
helper.setFrom(standartAdressFrom);
|
||||
helper.setTo(user.getEmail());
|
||||
helper.setSubject(standartSubject);
|
||||
|
||||
String htmlContent = loadAndProcessTemplate(user.getFullName(), code,
|
||||
"templates/email-verification.html");
|
||||
helper.setText(htmlContent, true);
|
||||
|
||||
mailSender.send(message);
|
||||
|
||||
log.info("Email sent to: {}", user.getEmail());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to send email: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void sendResetPasswordEmail(User user, String code) {
|
||||
try {
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
|
||||
helper.setFrom(standartAdressFrom);
|
||||
helper.setTo(user.getEmail());
|
||||
helper.setSubject(dropPasswordSubject);
|
||||
|
||||
String htmlContent = loadAndProcessTemplate(user.getFullName(), code,
|
||||
"templates/reset-password.html");
|
||||
helper.setText(htmlContent, true);
|
||||
|
||||
mailSender.send(message);
|
||||
|
||||
log.info("Email sent to: {}", user.getEmail());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to send email: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailVerificationToken createEmailVerificationToken(AuthToken authToken) {
|
||||
EmailVerificationToken emailToken = new EmailVerificationToken();
|
||||
emailToken.setUser(authToken.getUser());
|
||||
emailToken.setToken(generateVerificationCode());
|
||||
emailToken.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
return emailVerificationTokenRepository.save(emailToken);
|
||||
}
|
||||
|
||||
private String generateVerificationCode() {
|
||||
SecureRandom random = new SecureRandom();
|
||||
int code = 100000 + random.nextInt(900000);
|
||||
|
||||
return String.valueOf(code);
|
||||
}
|
||||
|
||||
private String loadAndProcessTemplate(String username, String code, String templatePath) throws IOException {
|
||||
ClassPathResource resource = new ClassPathResource(templatePath);
|
||||
String template = new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
String safeUsername = escapeHtml(username != null ? username : user);
|
||||
String safeCode = escapeHtml(code);
|
||||
|
||||
return template
|
||||
.replace("{{username}}", safeUsername)
|
||||
.replace("{{code}}", safeCode);
|
||||
}
|
||||
|
||||
private String escapeHtml(String text) {
|
||||
if (text == null) return "";
|
||||
return text
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package ru.soune.nocopy.service.register;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.soune.nocopy.entity.user.EmailVerificationToken;
|
||||
import ru.soune.nocopy.repository.EmailVerificationTokenRepository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CleanUpVerifyTokens {
|
||||
|
||||
private final EmailVerificationTokenRepository emailVerificationTokenRepository;
|
||||
|
||||
@Transactional
|
||||
@Scheduled(fixedDelay = 30000)
|
||||
public void cleanupExpiredTokens() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
|
||||
List<EmailVerificationToken> expiredTokens = emailVerificationTokenRepository.findByExpiresAtBefore(now);
|
||||
|
||||
if (!expiredTokens.isEmpty()) {
|
||||
emailVerificationTokenRepository.deleteAll(expiredTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package ru.soune.nocopy.service.search;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.soune.nocopy.dto.BaseResponse;
|
||||
import ru.soune.nocopy.dto.MessageCode;
|
||||
import ru.soune.nocopy.dto.file.YandexSearchResponse;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.exception.NotValidFieldException;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class YandexSearchService {
|
||||
private final FileEntityRepository fileEntityRepository;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Value("${yandex.api-key}")
|
||||
private String apiKey;
|
||||
|
||||
@Value("${yandex.folder-id}")
|
||||
private String folderId;
|
||||
|
||||
@Value("${yandex.search-url}")
|
||||
private String searchUrl;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
|
||||
}
|
||||
|
||||
public YandexSearchResponse searchByFileEntity(String fileId) throws IOException {
|
||||
FileEntity fileEntity = fileEntityRepository.findById(fileId)
|
||||
.orElseThrow(() -> {
|
||||
throw new NotValidFieldException("File not found", new BaseResponse(20007,
|
||||
MessageCode.FILE_NOT_FOUND.getCode(), MessageCode.FILE_NOT_FOUND.getDescription(),
|
||||
Map.of("fileId",fileId)));
|
||||
});
|
||||
byte[] fileBytes;
|
||||
|
||||
if (!isImageFile(fileEntity)) {
|
||||
log.error("File not image: {}", fileEntity.getMimeType());
|
||||
throw new NotValidFieldException("File not image", new BaseResponse(20007,
|
||||
MessageCode.INVALID_FIELD.getCode(), MessageCode.INVALID_FIELD.getDescription(),
|
||||
Map.of("file_type", fileEntity.getMimeType())));
|
||||
}
|
||||
|
||||
try {
|
||||
fileBytes = readFileFromDisk(fileEntity);
|
||||
} catch (IOException e) {
|
||||
throw new NotValidFieldException("File not found or cannot read file", new BaseResponse(20007,
|
||||
MessageCode.FILE_NOT_FOUND.getCode(), MessageCode.FILE_NOT_FOUND.getDescription(),
|
||||
Map.of("fileId", fileId,
|
||||
"filePath", fileEntity.getFilePath())));
|
||||
}
|
||||
|
||||
return callYandexApi(fileBytes);
|
||||
}
|
||||
|
||||
private boolean isImageFile(FileEntity fileEntity) {
|
||||
String mimeType = fileEntity.getMimeType();
|
||||
return mimeType != null && mimeType.startsWith("image");
|
||||
}
|
||||
|
||||
private byte[] readFileFromDisk(FileEntity fileEntity) throws IOException {
|
||||
Path filePath = Path.of(fileEntity.getFilePath());
|
||||
|
||||
if (!Files.exists(filePath)) {
|
||||
throw new IOException("File not found: " + fileEntity.getFilePath());
|
||||
}
|
||||
|
||||
if (!Files.isReadable(filePath)) {
|
||||
throw new IOException("Cannot read file: " + fileEntity.getFilePath());
|
||||
}
|
||||
|
||||
return Files.readAllBytes(filePath);
|
||||
}
|
||||
|
||||
private YandexSearchResponse callYandexApi(byte[] imageBytes) throws IOException {
|
||||
String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
|
||||
String jsonRequest = String.format("{\"folderId\":\"%s\",\"data\":\"%s\",\"page\":0,\"showSimilarImages\":true}",
|
||||
folderId, imageBase64);
|
||||
|
||||
URL url = new URL(searchUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
|
||||
try {
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Authorization", "Api-Key " + apiKey);
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setConnectTimeout(30000);
|
||||
connection.setReadTimeout(30000);
|
||||
connection.setDoOutput(true);
|
||||
|
||||
try (OutputStream os = connection.getOutputStream()) {
|
||||
byte[] input = jsonRequest.getBytes("utf-8");
|
||||
os.write(input, 0, input.length);
|
||||
os.flush();
|
||||
}
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
|
||||
String responseBody;
|
||||
if (responseCode == HttpURLConnection.HTTP_OK) {
|
||||
try (BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
|
||||
responseBody = readAll(br);
|
||||
}
|
||||
} else {
|
||||
try (BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(connection.getErrorStream(), "utf-8"))) {
|
||||
responseBody = readAll(br);
|
||||
}
|
||||
throw new IOException("Error Yandex API: " + responseCode + " - " + responseBody);
|
||||
}
|
||||
|
||||
return parseJsonResponse(responseBody);
|
||||
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private String readAll(BufferedReader reader) throws IOException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private YandexSearchResponse parseJsonResponse(String json) {
|
||||
YandexSearchResponse response = null;
|
||||
try {
|
||||
response = objectMapper.readValue(json, YandexSearchResponse.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,4 @@
|
||||
spring:
|
||||
mail:
|
||||
host: smtp.gmail.com
|
||||
port: 587
|
||||
username: vlad.popovtsev@gmail.com
|
||||
password: gocjwvrqrzlaatsr
|
||||
properties:
|
||||
mail:
|
||||
smtp:
|
||||
auth: true
|
||||
starttls:
|
||||
enable: true
|
||||
|
||||
# mail:
|
||||
# host: postfix
|
||||
# port: 25
|
||||
# username: noreply@nocopy.com
|
||||
# password: nocopy!nocopy!
|
||||
# properties:
|
||||
# mail.smtp.auth: false
|
||||
# mail.smtp.starttls.enable: false
|
||||
# mail.debug: true
|
||||
|
||||
datasource:
|
||||
url: jdbc:postgresql://${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
|
||||
username: ${POSTGRES_USER}
|
||||
@@ -46,12 +24,12 @@ spring:
|
||||
file:
|
||||
storage:
|
||||
base-path: ${FILE_STORAGE_PATH:/data/uploads}
|
||||
chunk-size: ${FILE_CHUNK_SIZE:1000000} # 1MB
|
||||
# chunk-size: ${FILE_CHUNK_SIZE:5242880} # 5MB
|
||||
chunk-size: ${FILE_CHUNK_SIZE:1048576} # 1MB
|
||||
max-file-size: ${MAX_FILE_SIZE:10737418240} # 10GB
|
||||
max-retry-attempts: ${MAX_RETRY_ATTEMPTS:3}
|
||||
chunk-timeout-ms: ${CHUNK_TIMEOUT_MS:300000} # 5 минут
|
||||
temp-ttl-hours: ${TEMP_TTL_HOURS:72} # 3 дня
|
||||
auth-token-life-hours: ${AUTH_TOKEN_LIFE:1} # 1 час
|
||||
session-expiry-hours: ${SESSION_EXPIRY_HOURS:24}
|
||||
|
||||
security:
|
||||
@@ -73,16 +51,3 @@ logging:
|
||||
name: logs/application.log
|
||||
pattern:
|
||||
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
|
||||
|
||||
yandex:
|
||||
api-key: ${YANDEX_API_KEY:AQVNyaVaUmgUb1GMCtf5zSEqFxy0woXrcMOOB43q}
|
||||
folder-id: ${YANDEX_FOLDER_ID:b1gokpdbm6qfpsou8pcd}
|
||||
search-url: ${YANDEX_SEARCH_URL:https://searchapi.api.cloud.yandex.net/v2/image/search_by_image}
|
||||
|
||||
app:
|
||||
email:
|
||||
verification:
|
||||
standart-subject: NO COPY - Подтверждение email адреса
|
||||
drop-password-subject: NO COPY - сброс пароля
|
||||
standart-address-from: NO COPY <noreply@nocopy.com>
|
||||
user: Пользователь
|
||||
@@ -1,127 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Подтверждение email</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 6px 20px rgba(0,0,0,0.1);
|
||||
}
|
||||
.header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 40px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.logo {
|
||||
font-size: 32px;
|
||||
font-weight: 800;
|
||||
margin-bottom: 10px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
.content {
|
||||
padding: 40px 30px;
|
||||
}
|
||||
.greeting {
|
||||
font-size: 18px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.username {
|
||||
color: #667eea;
|
||||
font-weight: bold;
|
||||
}
|
||||
.code-container {
|
||||
background: #f8f9fa;
|
||||
border: 2px dashed #667eea;
|
||||
border-radius: 10px;
|
||||
padding: 25px;
|
||||
text-align: center;
|
||||
margin: 30px 0;
|
||||
}
|
||||
.verification-code {
|
||||
font-size: 42px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 8px;
|
||||
color: #333;
|
||||
margin: 0;
|
||||
}
|
||||
.info-text {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
.warning {
|
||||
background: #fff3cd;
|
||||
border: 1px solid #ffeaa7;
|
||||
color: #856404;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin: 25px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
.footer {
|
||||
text-align: center;
|
||||
padding: 25px;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
border-top: 1px solid #eee;
|
||||
background: #f9f9f9;
|
||||
}
|
||||
.highlight {
|
||||
color: #764ba2;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="logo">NO COPY</div>
|
||||
<h1>Подтверждение email адреса</h1>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<p class="greeting">
|
||||
Здравствуйте, <span class="username">{{username}}</span>!
|
||||
</p>
|
||||
|
||||
<p>Спасибо за регистрацию на платформе NO COPY.
|
||||
Для завершения регистрации, пожалуйста, введите код подтверждения:</p>
|
||||
|
||||
<div class="code-container">
|
||||
<p class="verification-code">{{code}}</p>
|
||||
<p class="info-text">Код подтверждения</p>
|
||||
</div>
|
||||
|
||||
<p class="info-text">
|
||||
Код действителен в течение <span class="highlight">15 минут</span>
|
||||
</p>
|
||||
|
||||
<div class="warning">
|
||||
<strong>Важно:</strong> Если вы не регистрировались на NO COPY,
|
||||
просто проигнорируйте это письмо.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>© 2024 NO COPY. Все права защищены.</p>
|
||||
<p>Это письмо отправлено автоматически, пожалуйста, не отвечайте на него.</p>
|
||||
<p>Если у вас возникли вопросы, обратитесь в службу поддержки.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,201 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Восстановление пароля</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 6px 20px rgba(0,0,0,0.1);
|
||||
}
|
||||
.header {
|
||||
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
|
||||
color: white;
|
||||
padding: 40px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.logo {
|
||||
font-size: 32px;
|
||||
font-weight: 800;
|
||||
margin-bottom: 10px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
.content {
|
||||
padding: 40px 30px;
|
||||
}
|
||||
.greeting {
|
||||
font-size: 18px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.username {
|
||||
color: #ee5a52;
|
||||
font-weight: bold;
|
||||
}
|
||||
.code-container {
|
||||
background: #f8f9fa;
|
||||
border: 2px dashed #ff6b6b;
|
||||
border-radius: 10px;
|
||||
padding: 25px;
|
||||
text-align: center;
|
||||
margin: 30px 0;
|
||||
}
|
||||
.verification-code {
|
||||
font-size: 42px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 8px;
|
||||
color: #333;
|
||||
margin: 0;
|
||||
}
|
||||
.info-text {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
.warning {
|
||||
background: #fff3cd;
|
||||
border: 1px solid #ffeaa7;
|
||||
color: #856404;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin: 25px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
.action-button {
|
||||
display: inline-block;
|
||||
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
|
||||
color: white;
|
||||
padding: 14px 32px;
|
||||
text-decoration: none;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
.action-button:hover {
|
||||
background: linear-gradient(135deg, #ee5a52 0%, #d64541 100%);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(238, 90, 82, 0.3);
|
||||
}
|
||||
.steps {
|
||||
margin: 30px 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
.steps li {
|
||||
margin-bottom: 10px;
|
||||
padding-left: 5px;
|
||||
}
|
||||
.footer {
|
||||
text-align: center;
|
||||
padding: 25px;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
border-top: 1px solid #eee;
|
||||
background: #f9f9f9;
|
||||
}
|
||||
.highlight {
|
||||
color: #ee5a52;
|
||||
font-weight: 600;
|
||||
}
|
||||
.urgent {
|
||||
color: #d63031;
|
||||
font-weight: 700;
|
||||
}
|
||||
.link-fallback {
|
||||
margin-top: 15px;
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
}
|
||||
.timer {
|
||||
background: #ffebee;
|
||||
border-left: 4px solid #ff6b6b;
|
||||
padding: 12px 15px;
|
||||
margin: 20px 0;
|
||||
border-radius: 0 8px 8px 0;
|
||||
}
|
||||
.timer-text {
|
||||
color: #d32f2f;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="logo">NO COPY</div>
|
||||
<h1>Восстановление пароля</h1>
|
||||
<p>Безопасный доступ к вашему аккаунту</p>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<p class="greeting">
|
||||
Здравствуйте, <span class="username">{{username}}</span>!
|
||||
</p>
|
||||
|
||||
<p>Мы получили запрос на восстановление пароля для вашего аккаунта NO COPY.</p>
|
||||
<p>Для продолжения восстановления доступа, пожалуйста, используйте следующий код подтверждения:</p>
|
||||
|
||||
<div class="code-container">
|
||||
<p class="verification-code">{{code}}</p>
|
||||
<p class="info-text">Код для восстановления пароля</p>
|
||||
</div>
|
||||
|
||||
<div class="timer">
|
||||
<p class="timer-text">Код действителен в течение 15 минут</p>
|
||||
</div>
|
||||
|
||||
<h3>Как использовать этот код:</h3>
|
||||
<ol class="steps">
|
||||
<li>Вернитесь на страницу восстановления пароля</li>
|
||||
<li>Введите полученный код в поле подтверждения</li>
|
||||
<li>Создайте новый надежный пароль</li>
|
||||
<li>Войдите в аккаунт с новым паролем</li>
|
||||
</ol>
|
||||
|
||||
<div style="text-align: center;">
|
||||
<a href="{{resetLink}}" class="action-button">Перейти к восстановлению пароля</a>
|
||||
</div>
|
||||
|
||||
<p class="link-fallback">
|
||||
Если кнопка не работает, скопируйте и вставьте эту ссылку в браузер:<br>
|
||||
<span style="color: #3498db; word-break: break-all;">{{resetLink}}</span>
|
||||
</p>
|
||||
|
||||
<div class="warning">
|
||||
<strong>Важная информация:</strong><br>
|
||||
1. Если вы не запрашивали восстановление пароля, проигнорируйте это письмо.<br>
|
||||
2. Никому не сообщайте этот код, включая сотрудников поддержки.<br>
|
||||
3. После успешного восстановления старый пароль будет недействителен.
|
||||
</div>
|
||||
|
||||
<p style="font-size: 13px; color: #7f8c8d;">
|
||||
<strong>Совет по безопасности:</strong> Используйте пароль длиной не менее 8 символов,
|
||||
содержащий буквы (заглавные и строчные), цифры и специальные символы.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>© 2024 NO COPY. Все права защищены.</p>
|
||||
<p>Это письмо отправлено автоматически, пожалуйста, не отвечайте на него.</p>
|
||||
<p>Если у вас возникли вопросы или вы не запрашивали восстановление пароля,
|
||||
<a href="mailto:support@nocopy.com" style="color: #ee5a52;">свяжитесь со службой поддержки</a>.</p>
|
||||
<p style="font-size: 11px; margin-top: 10px;">
|
||||
IP запроса: {{ipAddress}} • Время: {{timestamp}} • Устройство: {{deviceInfo}}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,101 @@
|
||||
package ru.soune.nocopy.service;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import ru.soune.nocopy.dto.LoginRequest;
|
||||
import ru.soune.nocopy.entity.AuthToken;
|
||||
import ru.soune.nocopy.entity.User;
|
||||
import ru.soune.nocopy.exception.NotValidationPasswordException;
|
||||
import ru.soune.nocopy.exception.UserNotFoundException;
|
||||
import ru.soune.nocopy.repository.AuthTokenRepository;
|
||||
import ru.soune.nocopy.repository.UserRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class AuthServiceTest {
|
||||
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Mock
|
||||
private AuthTokenRepository authTokenRepository;
|
||||
|
||||
@Mock
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Mock
|
||||
private MessageSource messageSource;
|
||||
|
||||
@InjectMocks
|
||||
private AuthService authService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
void login_success() {
|
||||
LoginRequest request = new LoginRequest("test@mail.com", "password");
|
||||
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
user.setEmail("test@mail.com");
|
||||
user.setPassword("encoded_pass");
|
||||
|
||||
when(userRepository.findByEmail("test@mail.com"))
|
||||
.thenReturn(Optional.of(user));
|
||||
when(passwordEncoder.matches("password", "encoded_pass"))
|
||||
.thenReturn(true);
|
||||
when(authTokenRepository.save(any(AuthToken.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
AuthToken token = authService.login(request);
|
||||
|
||||
assertNotNull(token);
|
||||
assertNotNull(token.getToken());
|
||||
// assertEquals(user.getTokens().get(0), token.getUser());
|
||||
|
||||
ArgumentCaptor<AuthToken> captor = ArgumentCaptor.forClass(AuthToken.class);
|
||||
verify(authTokenRepository).save(captor.capture());
|
||||
|
||||
// assertEquals(user, captor.getValue().getUser());
|
||||
assertNotNull(captor.getValue().getToken());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void login_userNotFound() {
|
||||
LoginRequest request = new LoginRequest("missing@mail.com", "pwd");
|
||||
|
||||
when(userRepository.findByEmail("missing@mail.com")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(UserNotFoundException.class, () -> authService.login(request));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void login_invalidPassword() {
|
||||
LoginRequest request = new LoginRequest("test@mail.com", "wrong");
|
||||
|
||||
User user = new User();
|
||||
user.setEmail("test@mail.com");
|
||||
user.setPassword("encoded_pass");
|
||||
|
||||
when(userRepository.findByEmail("test@mail.com")).thenReturn(Optional.of(user));
|
||||
when(passwordEncoder.matches("wrong", "encoded_pass")).thenReturn(false);
|
||||
|
||||
assertThrows(NotValidationPasswordException.class, () -> authService.login(request));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user