Compare commits
6 Commits
f73f164fae
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47bd3a30a0 | ||
|
|
2bd14f3d7b | ||
|
|
6ba56d6694 | ||
|
|
f64d577120 | ||
|
|
2955bb4071 | ||
|
|
e02f8cdb6b |
25
.gitea/workflows/deploy-prod.yml
Normal file
25
.gitea/workflows/deploy-prod.yml
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
name: deploy-backend-prod
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: prod
|
||||||
|
steps:
|
||||||
|
- name: Backup DB
|
||||||
|
run: |
|
||||||
|
set -eo pipefail
|
||||||
|
docker compose -f /opt/nakhodka/docker-compose.yml exec -T postgres \
|
||||||
|
sh -c 'pg_dump -U "$POSTGRES_USER" nahodka' \
|
||||||
|
| gzip > /opt/nakhodka/backups/db-$(date +%F-%H%M).sql.gz
|
||||||
|
- name: Pull tested image
|
||||||
|
run: |
|
||||||
|
IMG=git.nahodka-test.online/admin/nakhodka-backend
|
||||||
|
docker pull $IMG:${{ github.sha }}
|
||||||
|
docker tag $IMG:${{ github.sha }} nakhodka-backend:latest
|
||||||
|
docker tag $IMG:${{ github.sha }} nakhodka-backend:${{ github.ref_name }}
|
||||||
|
- name: Restart backend
|
||||||
|
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d backend
|
||||||
|
- name: Cleanup
|
||||||
|
run: docker image prune -f
|
||||||
@@ -12,5 +12,10 @@ jobs:
|
|||||||
run: docker build -t nakhodka-backend:latest -t nakhodka-backend:${{ github.sha }} .
|
run: docker build -t nakhodka-backend:latest -t nakhodka-backend:${{ github.sha }} .
|
||||||
- name: Restart backend
|
- name: Restart backend
|
||||||
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d backend
|
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d backend
|
||||||
|
- name: Push image to registry
|
||||||
|
run: |
|
||||||
|
IMG=git.nahodka-test.online/admin/nakhodka-backend
|
||||||
|
docker tag nakhodka-backend:${{ github.sha }} $IMG:${{ github.sha }}
|
||||||
|
docker push $IMG:${{ github.sha }}
|
||||||
- name: Cleanup
|
- name: Cleanup
|
||||||
run: docker image prune -f
|
run: docker image prune -f
|
||||||
@@ -10,7 +10,8 @@ Spring Boot бэкенд сервиса объявлений «Потерял /
|
|||||||
- [docs/redis.md](docs/redis.md) — что и как хранится в Redis;
|
- [docs/redis.md](docs/redis.md) — что и как хранится в Redis;
|
||||||
- [docs/images-storage.md](docs/images-storage.md) — картинки, MinIO, сжатие, presigned URL, удаление, AI-модерация картинок;
|
- [docs/images-storage.md](docs/images-storage.md) — картинки, MinIO, сжатие, presigned URL, удаление, AI-модерация картинок;
|
||||||
- [docs/chats.md](docs/chats.md) — чаты: сообщения, фото и видео во вложениях, обработка видео, доступ к файлам;
|
- [docs/chats.md](docs/chats.md) — чаты: сообщения, фото и видео во вложениях, обработка видео, доступ к файлам;
|
||||||
- [docs/phone-protection.md](docs/phone-protection.md) — номер телефона: согласие автора и защита от массового сбора.
|
- [docs/phone-protection.md](docs/phone-protection.md) — номер телефона: согласие автора и защита от массового сбора;
|
||||||
|
- [docs/anti-fraud.md](docs/anti-fraud.md) — защита от мошенников: контрольные вопросы у находок, предупреждения о предоплате.
|
||||||
|
|
||||||
## Содержание
|
## Содержание
|
||||||
|
|
||||||
|
|||||||
70
docs/anti-fraud.md
Normal file
70
docs/anti-fraud.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
# Защита от мошенников
|
||||||
|
|
||||||
|
Две типичные схемы на сервисе находок:
|
||||||
|
|
||||||
|
- **«Это моё»** — человек видит фото находки и пишет автору, что вещь его, а потом просит
|
||||||
|
«выслать доставкой» или забирает чужую вещь.
|
||||||
|
- **Предоплата** — «нашёл вашу вещь, оплатите доставку / залог / переведите на карту»,
|
||||||
|
«продиктуйте код из СМС».
|
||||||
|
|
||||||
|
## Контрольные вопросы
|
||||||
|
|
||||||
|
Автор любого объявления может задать до 3 вопросов (до 200 символов):
|
||||||
|
|
||||||
|
- у **потери** — то, что знает только тот, у кого вещь в руках: что выгравировано, какая
|
||||||
|
наклейка на обороте. «Нашедший», который вещь не видел, не ответит и не дойдёт до просьбы
|
||||||
|
о предоплате — это главная схема, от которой закрывались похожие сервисы;
|
||||||
|
- у **находки** — то, что знает только владелец: что внутри, сколько денег в кошельке.
|
||||||
|
|
||||||
|
Вопросы хранятся в `post_verification_questions` и видны всем в
|
||||||
|
`PostResponse.verificationQuestions`; ответов на сервере нет — их проверяет сам автор.
|
||||||
|
|
||||||
|
Форма объявления присылает вопросы JSON-массивом в поле `verificationQuestions`
|
||||||
|
(создание и правка; при правке без поля вопросы не меняются, `[]` — убрать).
|
||||||
|
|
||||||
|
### Заявка
|
||||||
|
|
||||||
|
1. `POST /api/v1/posts/{id}/claim` `{answers: [...]}` — ответы в порядке вопросов → `ChatDto`
|
||||||
|
(201). Создаётся чат с `verificationStatus: PENDING`, `claimantId` и первым сообщением
|
||||||
|
`kind: CLAIM` (`claimAnswers: [{question, answer}]`; в `content` — то же текстом для превью).
|
||||||
|
2. Обычный `POST /api/v1/chats/with/{ownerId}/messages?postId=…` к такому объявлению отвечает
|
||||||
|
**403 `VERIFICATION_REQUIRED`**: первое сообщение — только ответы. Автор объявления может
|
||||||
|
написать первым как обычно.
|
||||||
|
3. Пока заявка `PENDING` или `REJECTED`, заявитель не может писать в чат (текст, фото, видео —
|
||||||
|
403 `VERIFICATION_REQUIRED`), а номер автора ему не отдаётся (`/phone/challenge` и
|
||||||
|
`/phone` — 403 без штрафа IP). Автор писать может — например, чтобы задать уточняющий вопрос.
|
||||||
|
4. `POST /api/v1/chats/{chatId}/verification` `{approved: true|false}` — решение автора.
|
||||||
|
Обоим приходит по `/topic/chat/{chatId}` сообщение `kind: VERIFICATION` с
|
||||||
|
`verificationStatus`. Отклонённую заявку можно потом подтвердить, подтверждённую — нет (409).
|
||||||
|
5. `GET /api/v1/chats/{chatId}` — один чат: `verificationStatus`, `claimantId`,
|
||||||
|
`otherUserCreatedAt`, `post.phoneVisible`.
|
||||||
|
|
||||||
|
### Лимиты (`anti-fraud.*`)
|
||||||
|
|
||||||
|
- 5 заявок в сутки с аккаунта (`ANTI_FRAUD_CLAIM_DAILY_LIMIT`), 2 попытки на одно объявление
|
||||||
|
за 30 дней (удалив отклонённый чат, ответы заново не подобрать), 10 в час с IP
|
||||||
|
(`rate-limit.rules`, `post-claim`). Сверх — 429 с `Retry-After`.
|
||||||
|
|
||||||
|
## Предупреждения в переписке
|
||||||
|
|
||||||
|
`FraudSignals` ищет в тексте сообщения (регулярки, без хранения — работает и для старой
|
||||||
|
переписки) и ставит `MessageDto.fraudSignal`:
|
||||||
|
|
||||||
|
| сигнал | что ищет |
|
||||||
|
|---|---|
|
||||||
|
| `SMS_CODE` | код из СМС/пуша, «продиктуйте код», Госуслуги |
|
||||||
|
| `CARD_DATA` | номер карты (13–19 цифр с проверкой Луна), CVV/CVC, срок действия |
|
||||||
|
| `PREPAYMENT` | предоплата, «переведите», «скиньте», залог, СБП, оплата доставки/курьера/СДЭК, «на карту» |
|
||||||
|
|
||||||
|
Сообщение не блокируется: фронт показывает предупреждение только получателю. Ложные
|
||||||
|
срабатывания допустимы — предупреждение ничего не запрещает.
|
||||||
|
|
||||||
|
Кроме того, фронт показывает в форме объявления блок «Как не попасться мошенникам»
|
||||||
|
(не переводить предоплату, вознаграждение — только при встрече), в каждом чате плашку «не переводите предоплату» (скрывается
|
||||||
|
в конкретном чате), отметку «новый аккаунт», если собеседник зарегистрирован меньше недели
|
||||||
|
назад (`ChatDto.otherUserCreatedAt`), и подсказку под открытым номером.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
Вопросы не модерируются ИИ (как и текст вознаграждения). Ответы проверяет человек: если
|
||||||
|
автор подтвердит неверные ответы, система это не исправит.
|
||||||
@@ -22,7 +22,9 @@
|
|||||||
|
|
||||||
Задача подписана HMAC, привязана к объявлению, живёт 2 минуты и принимается один раз.
|
Задача подписана HMAC, привязана к объявлению, живёт 2 минуты и принимается один раз.
|
||||||
Номер отдаётся только у активных объявлений с согласием. Оба эндпоинта публичные,
|
Номер отдаётся только у активных объявлений с согласием. Оба эндпоинта публичные,
|
||||||
регистрация не нужна.
|
регистрация не нужна. Исключение — объявление с контрольными вопросами: номер получает только
|
||||||
|
автор и заявитель, чьи ответы автор подтвердил, остальным — 403 `VERIFICATION_REQUIRED`
|
||||||
|
([anti-fraud.md](anti-fraud.md)).
|
||||||
|
|
||||||
Время решения (JS, худший случай, десктоп; телефон в 3–5 раз медленнее, в среднем — вдвое быстрее):
|
Время решения (JS, худший случай, десктоп; телефон в 3–5 раз медленнее, в среднем — вдвое быстрее):
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import com.krylov.refound.config.MinioProperties;
|
|||||||
import com.krylov.refound.ratelimit.RateLimitProperties;
|
import com.krylov.refound.ratelimit.RateLimitProperties;
|
||||||
import com.krylov.refound.search.SearchProperties;
|
import com.krylov.refound.search.SearchProperties;
|
||||||
import com.krylov.refound.service.advertising.AdsProperties;
|
import com.krylov.refound.service.advertising.AdsProperties;
|
||||||
|
import com.krylov.refound.service.antifraud.AntiFraudProperties;
|
||||||
import com.krylov.refound.service.phone.PhoneRevealProperties;
|
import com.krylov.refound.service.phone.PhoneRevealProperties;
|
||||||
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
|
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
@@ -20,7 +21,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
|||||||
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
|
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
|
||||||
)@EnableScheduling
|
)@EnableScheduling
|
||||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
|
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
|
||||||
SearchProperties.class, RateLimitProperties.class, AdsProperties.class, PhoneRevealProperties.class})
|
SearchProperties.class, RateLimitProperties.class, AdsProperties.class, PhoneRevealProperties.class,
|
||||||
|
AntiFraudProperties.class})
|
||||||
@EnableRetry
|
@EnableRetry
|
||||||
public class ReFoundApplication {
|
public class ReFoundApplication {
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import com.krylov.refound.dto.MessageAttachmentDto;
|
|||||||
import com.krylov.refound.dto.MessageDto;
|
import com.krylov.refound.dto.MessageDto;
|
||||||
import com.krylov.refound.dto.SendVideoRequest;
|
import com.krylov.refound.dto.SendVideoRequest;
|
||||||
import com.krylov.refound.dto.StartChatRequest;
|
import com.krylov.refound.dto.StartChatRequest;
|
||||||
|
import com.krylov.refound.dto.VerificationDecisionRequest;
|
||||||
import com.krylov.refound.dto.VideoUploadRequest;
|
import com.krylov.refound.dto.VideoUploadRequest;
|
||||||
|
import com.krylov.refound.service.ChatClaimService;
|
||||||
import com.krylov.refound.service.ChatService;
|
import com.krylov.refound.service.ChatService;
|
||||||
import com.krylov.refound.service.ChatVideoUploadService;
|
import com.krylov.refound.service.ChatVideoUploadService;
|
||||||
import com.krylov.refound.service.UserService;
|
import com.krylov.refound.service.UserService;
|
||||||
@@ -37,6 +39,7 @@ public class ChatController {
|
|||||||
|
|
||||||
private final UserService userService;
|
private final UserService userService;
|
||||||
private final ChatService chatService;
|
private final ChatService chatService;
|
||||||
|
private final ChatClaimService chatClaimService;
|
||||||
|
|
||||||
// Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
|
// Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
|
||||||
@GetMapping("/with/{otherUserId}")
|
@GetMapping("/with/{otherUserId}")
|
||||||
@@ -55,6 +58,25 @@ public class ChatController {
|
|||||||
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
|
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Один чат: статус проверки ответов на вопросы объявления, собеседник, объявление
|
||||||
|
@GetMapping("/{chatId}")
|
||||||
|
public ChatDto getChat(@PathVariable Long chatId, Authentication auth) {
|
||||||
|
Long currentUserId = extractUserId(auth);
|
||||||
|
return chatService.getChat(chatId, currentUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Автор объявления подтверждает или отклоняет ответы заявителя. Решение придёт
|
||||||
|
* обоим по /topic/chat/{chatId} сообщением kind = VERIFICATION.
|
||||||
|
*/
|
||||||
|
@PostMapping("/{chatId}/verification")
|
||||||
|
public MessageDto decideVerification(@PathVariable Long chatId, @RequestBody VerificationDecisionRequest request,
|
||||||
|
Authentication auth) {
|
||||||
|
Long currentUserId = extractUserId(auth);
|
||||||
|
log.info("decideVerification chatId {} by user {}: approved={}", chatId, currentUserId, request.approved());
|
||||||
|
return chatClaimService.decide(currentUserId, chatId, request.approved());
|
||||||
|
}
|
||||||
|
|
||||||
// Список всех чатов текущего пользователя
|
// Список всех чатов текущего пользователя
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public List<ChatDto> getMyChats(Authentication auth) {
|
public List<ChatDto> getMyChats(Authentication auth) {
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ public class PhoneRevealController {
|
|||||||
public ResponseEntity<ProofOfWorkService.Challenge> challenge(@PathVariable Long id, HttpServletRequest request) {
|
public ResponseEntity<ProofOfWorkService.Challenge> challenge(@PathVariable Long id, HttpServletRequest request) {
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.cacheControl(CacheControl.noStore())
|
.cacheControl(CacheControl.noStore())
|
||||||
.body(phoneRevealService.challenge(id, request.getRemoteAddr()));
|
.body(phoneRevealService.challenge(id, request.getRemoteAddr(), currentUserId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.krylov.refound.controller;
|
||||||
|
|
||||||
|
import com.krylov.refound.dto.ChatDto;
|
||||||
|
import com.krylov.refound.dto.ClaimRequest;
|
||||||
|
import com.krylov.refound.service.ChatClaimService;
|
||||||
|
import com.krylov.refound.service.UserService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ответы на контрольные вопросы объявления: «нашёл вашу вещь» к потере,
|
||||||
|
* «это моё» к находке. Создаёт чат-заявку с ответами первым сообщением;
|
||||||
|
* писать дальше и увидеть номер заявитель сможет,
|
||||||
|
* когда автор объявления подтвердит ответы (POST /api/v1/chats/{chatId}/verification).
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/v1/posts/{id:\\d+}/claim")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PostClaimController {
|
||||||
|
|
||||||
|
private final ChatClaimService chatClaimService;
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public ChatDto claim(@PathVariable Long id, @RequestBody ClaimRequest request) {
|
||||||
|
Long userId = userService.getCurrentUser().getId();
|
||||||
|
log.info("claim post {} by user {}", id, userId);
|
||||||
|
return chatClaimService.claim(userId, id, request.answers());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -93,10 +93,11 @@ public class PostController {
|
|||||||
@RequestParam(required = false) String category, @RequestParam(required = false) String phone,
|
@RequestParam(required = false) String category, @RequestParam(required = false) String phone,
|
||||||
@RequestParam(required = false) Boolean phoneVisible, @RequestParam(required = false) Boolean reward,
|
@RequestParam(required = false) Boolean phoneVisible, @RequestParam(required = false) Boolean reward,
|
||||||
@RequestParam(required = false) String rewardText,
|
@RequestParam(required = false) String rewardText,
|
||||||
@RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) {
|
@RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson,
|
||||||
|
@RequestParam(value = "verificationQuestions", required = false) String verificationQuestionsJson) {
|
||||||
log.info("update post {}", id);
|
log.info("update post {}", id);
|
||||||
return service.update(id, type, title, address, latitude, longitude, description, category, phone, phoneVisible, reward, rewardText, images,
|
return service.update(id, type, title, address, latitude, longitude, description, category, phone, phoneVisible, reward, rewardText, images,
|
||||||
existingImagesJson);
|
existingImagesJson, verificationQuestionsJson);
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.dto;
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
import com.krylov.refound.enums.AttachmentKind;
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
@@ -19,4 +20,10 @@ public class ChatDto {
|
|||||||
/** Тип вложений последнего сообщения (PHOTO/VIDEO) или null. */
|
/** Тип вложений последнего сообщения (PHOTO/VIDEO) или null. */
|
||||||
private AttachmentKind lastMessageAttachmentKind;
|
private AttachmentKind lastMessageAttachmentKind;
|
||||||
private long unreadCount;
|
private long unreadCount;
|
||||||
|
/** Когда зарегистрировался собеседник: фронт помечает недавние аккаунты. */
|
||||||
|
private LocalDateTime otherUserCreatedAt;
|
||||||
|
/** Проверка ответов на контрольные вопросы объявления; null — обычный чат. */
|
||||||
|
private ChatVerificationStatus verificationStatus;
|
||||||
|
/** Кто отвечал на вопросы: пока ответы не подтверждены, ему писать нельзя. */
|
||||||
|
private Long claimantId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,4 +18,6 @@ public class ChatPostDto {
|
|||||||
private PostType type;
|
private PostType type;
|
||||||
private PostStatus status;
|
private PostStatus status;
|
||||||
private String city;
|
private String city;
|
||||||
|
/** Автор разрешил показ номера: после подтверждения ответов чат предлагает его открыть. */
|
||||||
|
private boolean phoneVisible;
|
||||||
}
|
}
|
||||||
|
|||||||
5
src/main/java/com/krylov/refound/dto/ClaimAnswerDto.java
Normal file
5
src/main/java/com/krylov/refound/dto/ClaimAnswerDto.java
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
/** Вопрос автора объявления и ответ заявителя — в сообщении kind = CLAIM. */
|
||||||
|
public record ClaimAnswerDto(String question, String answer) {
|
||||||
|
}
|
||||||
7
src/main/java/com/krylov/refound/dto/ClaimRequest.java
Normal file
7
src/main/java/com/krylov/refound/dto/ClaimRequest.java
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Ответы на контрольные вопросы объявления, в том же порядке (POST /api/v1/posts/{id}/claim). */
|
||||||
|
public record ClaimRequest(List<String> answers) {
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.krylov.refound.dto;
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
|
import com.krylov.refound.enums.FraudSignal;
|
||||||
|
import com.krylov.refound.enums.MessageKind;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
@@ -14,4 +17,15 @@ public class MessageDto {
|
|||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
/** Фото сообщения; пустой список, если вложений нет. */
|
/** Фото сообщения; пустой список, если вложений нет. */
|
||||||
private List<MessageAttachmentDto> attachments = List.of();
|
private List<MessageAttachmentDto> attachments = List.of();
|
||||||
|
/** TEXT — обычное, CLAIM — ответы на контрольные вопросы, VERIFICATION — решение автора. */
|
||||||
|
private MessageKind kind = MessageKind.TEXT;
|
||||||
|
/** У CLAIM: вопросы автора и ответы заявителя; иначе пустой список. */
|
||||||
|
private List<ClaimAnswerDto> claimAnswers = List.of();
|
||||||
|
/** У VERIFICATION: новый статус чата — фронт по нему снимает или ставит блокировку ввода. */
|
||||||
|
private ChatVerificationStatus verificationStatus;
|
||||||
|
/**
|
||||||
|
* Похоже на мошенническую просьбу (предоплата, данные карты, код из СМС);
|
||||||
|
* фронт показывает предупреждение получателю. null — ничего не найдено.
|
||||||
|
*/
|
||||||
|
private FraudSignal fraudSignal;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ public class PostRequest {
|
|||||||
private String phone;
|
private String phone;
|
||||||
/** Явное согласие на показ номера другим пользователям; без него номер не сохраняется. */
|
/** Явное согласие на показ номера другим пользователям; без него номер не сохраняется. */
|
||||||
private Boolean phoneVisible;
|
private Boolean phoneVisible;
|
||||||
|
/**
|
||||||
|
* Контрольные вопросы объявления — JSON-массив строк (как existingImages в правке).
|
||||||
|
* null — не менять (при правке), "[]" — убрать.
|
||||||
|
*/
|
||||||
|
private String verificationQuestions;
|
||||||
private String imageUrl;
|
private String imageUrl;
|
||||||
private Double latitude;
|
private Double latitude;
|
||||||
private Double longitude;
|
private Double longitude;
|
||||||
|
|||||||
@@ -37,6 +37,12 @@ public class PostResponse {
|
|||||||
private String phone;
|
private String phone;
|
||||||
/** Автор разрешил показ номера: фронт показывает кнопку «Показать номер». */
|
/** Автор разрешил показ номера: фронт показывает кнопку «Показать номер». */
|
||||||
private boolean phoneVisible;
|
private boolean phoneVisible;
|
||||||
|
/**
|
||||||
|
* Контрольные вопросы автора (без ответов). Если они есть, написать автору
|
||||||
|
* можно только ответив на них (POST /api/v1/posts/{id}/claim), а номер
|
||||||
|
* открывается после того, как автор подтвердит ответы.
|
||||||
|
*/
|
||||||
|
private List<String> verificationQuestions = List.of();
|
||||||
private List<String> images;
|
private List<String> images;
|
||||||
private Long userId;
|
private Long userId;
|
||||||
private Role userRole;
|
private Role userRole;
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
/** Решение автора объявления по ответам заявителя (POST /api/v1/chats/{chatId}/verification). */
|
||||||
|
public record VerificationDecisionRequest(boolean approved) {
|
||||||
|
}
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
import com.krylov.refound.util.TimeZoneContext;
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.EnumType;
|
||||||
|
import jakarta.persistence.Enumerated;
|
||||||
import jakarta.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import jakarta.persistence.GenerationType;
|
import jakarta.persistence.GenerationType;
|
||||||
import jakarta.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
@@ -41,6 +44,24 @@ public class Chat {
|
|||||||
@Column(name = "created_at", nullable = false)
|
@Column(name = "created_at", nullable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
// Чат-заявка к объявлению с контрольными вопросами (ChatClaimService): статус
|
||||||
|
// проверки ответов автором; null — обычный чат без проверки
|
||||||
|
@Enumerated(EnumType.STRING)
|
||||||
|
@Column(name = "verification_status", length = 16)
|
||||||
|
private ChatVerificationStatus verificationStatus;
|
||||||
|
|
||||||
|
@Column(name = "claimant_id")
|
||||||
|
private Long claimantId; // кто ответил на вопросы (не автор объявления)
|
||||||
|
|
||||||
|
@Column(name = "verified_at")
|
||||||
|
private LocalDateTime verifiedAt;
|
||||||
|
|
||||||
|
/** Заявитель ещё не может писать: ответы не проверены или отклонены. */
|
||||||
|
public boolean isLockedFor(Long userId) {
|
||||||
|
return verificationStatus != null && verificationStatus != ChatVerificationStatus.APPROVED
|
||||||
|
&& Objects.equals(claimantId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
protected void onCreate() {
|
protected void onCreate() {
|
||||||
createdAt = TimeZoneContext.now();
|
createdAt = TimeZoneContext.now();
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.MessageKind;
|
||||||
import com.krylov.refound.util.TimeZoneContext;
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.EnumType;
|
||||||
|
import jakarta.persistence.Enumerated;
|
||||||
import jakarta.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import jakarta.persistence.GenerationType;
|
import jakarta.persistence.GenerationType;
|
||||||
import jakarta.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
@@ -31,6 +34,14 @@ public class Message {
|
|||||||
@Column(nullable = false, columnDefinition = "TEXT")
|
@Column(nullable = false, columnDefinition = "TEXT")
|
||||||
private String content;
|
private String content;
|
||||||
|
|
||||||
|
@Enumerated(EnumType.STRING)
|
||||||
|
@Column(nullable = false, length = 16)
|
||||||
|
private MessageKind kind = MessageKind.TEXT;
|
||||||
|
|
||||||
|
// CLAIM — JSON вопросов и ответов, VERIFICATION — статус решения; у TEXT null
|
||||||
|
@Column(columnDefinition = "TEXT")
|
||||||
|
private String payload;
|
||||||
|
|
||||||
@Column(name = "is_read", nullable = false)
|
@Column(name = "is_read", nullable = false)
|
||||||
private boolean isRead = false;
|
private boolean isRead = false;
|
||||||
|
|
||||||
|
|||||||
@@ -5,16 +5,20 @@ import com.krylov.refound.enums.PostCategory;
|
|||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
import com.krylov.refound.enums.PostType;
|
import com.krylov.refound.enums.PostType;
|
||||||
import jakarta.persistence.CascadeType;
|
import jakarta.persistence.CascadeType;
|
||||||
|
import jakarta.persistence.CollectionTable;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.ElementCollection;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import jakarta.persistence.EnumType;
|
import jakarta.persistence.EnumType;
|
||||||
import jakarta.persistence.Enumerated;
|
import jakarta.persistence.Enumerated;
|
||||||
import jakarta.persistence.GeneratedValue;
|
import jakarta.persistence.GeneratedValue;
|
||||||
import jakarta.persistence.GenerationType;
|
import jakarta.persistence.GenerationType;
|
||||||
import jakarta.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.JoinColumn;
|
||||||
import jakarta.persistence.ManyToOne;
|
import jakarta.persistence.ManyToOne;
|
||||||
import jakarta.persistence.OneToMany;
|
import jakarta.persistence.OneToMany;
|
||||||
import jakarta.persistence.OrderBy;
|
import jakarta.persistence.OrderBy;
|
||||||
|
import jakarta.persistence.OrderColumn;
|
||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -80,6 +84,21 @@ public class Post {
|
|||||||
@OrderBy("id ASC")
|
@OrderBy("id ASC")
|
||||||
private List<Image> images = new ArrayList<>();
|
private List<Image> images = new ArrayList<>();
|
||||||
|
|
||||||
|
// Контрольные вопросы автора (до 3): у потери их отвечает тот, кто пишет «нашёл»,
|
||||||
|
// у находки — тот, кто пишет «это моё». Заявитель отвечает до чата, автор
|
||||||
|
// подтверждает ответы — только тогда открываются чат и номер.
|
||||||
|
// Ведутся в PostService.applyVerificationQuestions
|
||||||
|
@ElementCollection
|
||||||
|
@CollectionTable(name = "post_verification_questions", joinColumns = @JoinColumn(name = "post_id"))
|
||||||
|
@OrderColumn(name = "position")
|
||||||
|
@Column(name = "question", length = 200, nullable = false)
|
||||||
|
private List<String> verificationQuestions = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Написать автору и увидеть номер можно только после проверки ответов на вопросы. */
|
||||||
|
public boolean requiresVerification() {
|
||||||
|
return !verificationQuestions.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Меняет статус и ведёт closedAt: переход в CLOSED ставит время закрытия,
|
* Меняет статус и ведёт closedAt: переход в CLOSED ставит время закрытия,
|
||||||
* уход из CLOSED (переоткрытие, правка с повторной модерацией) его сбрасывает.
|
* уход из CLOSED (переоткрытие, правка с повторной модерацией) его сбрасывает.
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.krylov.refound.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверка заявки к объявлению с контрольными вопросами. Пока заявка
|
||||||
|
* PENDING или REJECTED, заявитель не может писать в чат и не видит номер автора.
|
||||||
|
*/
|
||||||
|
public enum ChatVerificationStatus {
|
||||||
|
PENDING,
|
||||||
|
APPROVED,
|
||||||
|
REJECTED
|
||||||
|
}
|
||||||
@@ -9,5 +9,7 @@ public enum ErrorCode {
|
|||||||
FORBIDDEN,
|
FORBIDDEN,
|
||||||
CONTENT_BLOCKED,
|
CONTENT_BLOCKED,
|
||||||
INVALID_STATUS_TRANSITION,
|
INVALID_STATUS_TRANSITION,
|
||||||
TOO_MANY_REQUESTS
|
TOO_MANY_REQUESTS,
|
||||||
|
// Находка с контрольными вопросами: сначала ответы, автор их подтверждает
|
||||||
|
VERIFICATION_REQUIRED
|
||||||
}
|
}
|
||||||
|
|||||||
11
src/main/java/com/krylov/refound/enums/FraudSignal.java
Normal file
11
src/main/java/com/krylov/refound/enums/FraudSignal.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package com.krylov.refound.enums;
|
||||||
|
|
||||||
|
/** Признак типичной мошеннической просьбы в сообщении чата (см. FraudSignals). */
|
||||||
|
public enum FraudSignal {
|
||||||
|
/** Просят код из СМС или пуша, доступ к Госуслугам. */
|
||||||
|
SMS_CODE,
|
||||||
|
/** В сообщении номер карты, CVV или срок действия. */
|
||||||
|
CARD_DATA,
|
||||||
|
/** Просят предоплату, залог, перевод или оплату доставки. */
|
||||||
|
PREPAYMENT
|
||||||
|
}
|
||||||
10
src/main/java/com/krylov/refound/enums/MessageKind.java
Normal file
10
src/main/java/com/krylov/refound/enums/MessageKind.java
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package com.krylov.refound.enums;
|
||||||
|
|
||||||
|
public enum MessageKind {
|
||||||
|
/** Обычное сообщение собеседника. */
|
||||||
|
TEXT,
|
||||||
|
/** Ответы заявителя на контрольные вопросы объявления — первое сообщение чата-заявки. */
|
||||||
|
CLAIM,
|
||||||
|
/** Решение автора по заявке: подтвердил или отклонил ответы. */
|
||||||
|
VERIFICATION
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@ public interface PostMapper {
|
|||||||
@Mapping(target = "phone", ignore = true)
|
@Mapping(target = "phone", ignore = true)
|
||||||
@Mapping(target = "phoneVisible", ignore = true)
|
@Mapping(target = "phoneVisible", ignore = true)
|
||||||
@Mapping(target = "phoneConsentAt", ignore = true)
|
@Mapping(target = "phoneConsentAt", ignore = true)
|
||||||
|
// Вопросы приходят JSON-строкой; разбирает PostService.applyVerificationQuestions
|
||||||
|
@Mapping(target = "verificationQuestions", ignore = true)
|
||||||
Post toEntity(PostRequest request);
|
Post toEntity(PostRequest request);
|
||||||
|
|
||||||
@Mapping(source = "user.id", target = "userId")
|
@Mapping(source = "user.id", target = "userId")
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.repository;
|
package com.krylov.refound.repository;
|
||||||
|
|
||||||
import com.krylov.refound.entity.Chat;
|
import com.krylov.refound.entity.Chat;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -16,6 +17,10 @@ public interface ChatRepository extends JpaRepository<Chat, Long> {
|
|||||||
+ "AND ((:postId IS NULL AND c.postId IS NULL) OR c.postId = :postId)")
|
+ "AND ((:postId IS NULL AND c.postId IS NULL) OR c.postId = :postId)")
|
||||||
List<Chat> findByUsersAndPost(Long u1, Long u2, Long postId);
|
List<Chat> findByUsersAndPost(Long u1, Long u2, Long postId);
|
||||||
|
|
||||||
|
/** Подтвердил ли автор находки ответы этого заявителя — тогда ему открывается номер. */
|
||||||
|
boolean existsByClaimantIdAndPostIdAndVerificationStatus(Long claimantId, Long postId,
|
||||||
|
ChatVerificationStatus verificationStatus);
|
||||||
|
|
||||||
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
|
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
|
||||||
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
|
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
|
||||||
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
|
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
|
||||||
|
|||||||
158
src/main/java/com/krylov/refound/service/ChatClaimService.java
Normal file
158
src/main/java/com/krylov/refound/service/ChatClaimService.java
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
package com.krylov.refound.service;
|
||||||
|
|
||||||
|
import com.krylov.refound.dto.ChatDto;
|
||||||
|
import com.krylov.refound.dto.ClaimAnswerDto;
|
||||||
|
import com.krylov.refound.dto.MessageDto;
|
||||||
|
import com.krylov.refound.entity.Chat;
|
||||||
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
|
import com.krylov.refound.enums.MessageKind;
|
||||||
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
|
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||||
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import com.krylov.refound.service.antifraud.AntiFraudProperties;
|
||||||
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Заявки на объявления с контрольными вопросами: «нашёл вашу вещь» к потере и
|
||||||
|
* «это моё» к находке. Заявитель отвечает на вопросы — чат создаётся с ответами
|
||||||
|
* первым сообщением и статусом PENDING. Пока автор не подтвердил ответы,
|
||||||
|
* заявитель не пишет в чат и не видит номер (ChatService.checkCanWrite,
|
||||||
|
* PhoneRevealService). Так «нашедший», который вещи не видел, не дойдёт до
|
||||||
|
* просьбы о предоплате, а находка не уйдёт тому, кто просто увидел фото.
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ChatClaimService {
|
||||||
|
|
||||||
|
static final String RULE_CLAIM_DAY = "claim-user-day";
|
||||||
|
static final String RULE_CLAIM_POST = "claim-user-post";
|
||||||
|
public static final int MAX_ANSWER_LENGTH = 500;
|
||||||
|
private static final Duration DAY = Duration.ofDays(1);
|
||||||
|
|
||||||
|
private final PostRepository postRepository;
|
||||||
|
private final ChatRepository chatRepository;
|
||||||
|
private final ChatService chatService;
|
||||||
|
private final RedisRateLimiter rateLimiter;
|
||||||
|
private final AntiFraudProperties properties;
|
||||||
|
|
||||||
|
/** Ответы на вопросы объявления: создаёт чат-заявку и отправляет ответы автору. */
|
||||||
|
@Transactional
|
||||||
|
public ChatDto claim(Long userId, Long postId, List<String> answers) {
|
||||||
|
Post post = postRepository.findById(postId)
|
||||||
|
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
|
||||||
|
if (post.getStatus() != PostStatus.ACTIVE || !post.requiresVerification()) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "У объявления нет контрольных вопросов",
|
||||||
|
HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
Long ownerId = post.getUser().getId();
|
||||||
|
if (ownerId.equals(userId)) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Это ваше объявление", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
List<ClaimAnswerDto> qa = pairAnswers(post.getVerificationQuestions(), answers);
|
||||||
|
|
||||||
|
Long userId1 = Math.min(userId, ownerId);
|
||||||
|
Long userId2 = Math.max(userId, ownerId);
|
||||||
|
if (!chatRepository.findByUsersAndPost(userId1, userId2, postId).isEmpty()) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Вы уже писали автору этого объявления", HttpStatus.CONFLICT);
|
||||||
|
}
|
||||||
|
// Лимиты — после проверок: неверно заполненная форма попытку не тратит
|
||||||
|
checkLimit(RULE_CLAIM_DAY, "u" + userId, properties.getClaimDailyLimit(), DAY,
|
||||||
|
"Слишком много заявок за сутки, попробуйте завтра");
|
||||||
|
checkLimit(RULE_CLAIM_POST, "u" + userId + ":p" + postId, properties.getClaimAttemptsPerPost(),
|
||||||
|
properties.getClaimRetryWindow(), "Вы уже отвечали на вопросы этого объявления");
|
||||||
|
|
||||||
|
Chat chat = new Chat();
|
||||||
|
chat.setUserOneId(userId1);
|
||||||
|
chat.setUserTwoId(userId2);
|
||||||
|
chat.setPostId(postId);
|
||||||
|
chat.setVerificationStatus(ChatVerificationStatus.PENDING);
|
||||||
|
chat.setClaimantId(userId);
|
||||||
|
chat = chatRepository.save(chat);
|
||||||
|
|
||||||
|
chatService.saveAndBroadcast(chat, userId, formatAnswers(qa), List.of(), MessageKind.CLAIM,
|
||||||
|
ClaimPayload.writeAnswers(qa));
|
||||||
|
log.info("Заявка с ответами на вопросы: postId={}, claimantId={}, chatId={}", postId, userId, chat.getId());
|
||||||
|
return chatService.toDto(chat, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Решение автора объявления. Отклонённую заявку можно потом подтвердить (автор
|
||||||
|
* передумал или нажал не ту кнопку), подтверждённую — уже нет.
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public MessageDto decide(Long userId, Long chatId, boolean approved) {
|
||||||
|
Chat chat = chatService.getChatOrThrow(chatId);
|
||||||
|
chatService.checkParticipant(chat, userId);
|
||||||
|
ChatVerificationStatus status = chat.getVerificationStatus();
|
||||||
|
if (status == null || Objects.equals(chat.getClaimantId(), userId)) {
|
||||||
|
throw new ApiException(ErrorCode.FORBIDDEN, "Ответы проверяет автор объявления", HttpStatus.FORBIDDEN);
|
||||||
|
}
|
||||||
|
if (status == ChatVerificationStatus.APPROVED || (status == ChatVerificationStatus.REJECTED && !approved)) {
|
||||||
|
throw new ApiException(ErrorCode.INVALID_STATUS_TRANSITION, "Решение по ответам уже принято",
|
||||||
|
HttpStatus.CONFLICT);
|
||||||
|
}
|
||||||
|
ChatVerificationStatus next = approved ? ChatVerificationStatus.APPROVED : ChatVerificationStatus.REJECTED;
|
||||||
|
chat.setVerificationStatus(next);
|
||||||
|
chat.setVerifiedAt(TimeZoneContext.now());
|
||||||
|
chatRepository.save(chat);
|
||||||
|
|
||||||
|
String content = approved
|
||||||
|
? "Автор объявления подтвердил ответы — договоритесь о встрече"
|
||||||
|
: "Автор объявления не подтвердил ответы";
|
||||||
|
log.info("Решение по заявке: chatId={}, ownerId={}, status={}", chatId, userId, next);
|
||||||
|
return chatService.saveAndBroadcast(chat, userId, content, List.of(), MessageKind.VERIFICATION, next.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<ClaimAnswerDto> pairAnswers(List<String> questions, List<String> answers) {
|
||||||
|
if (answers == null || answers.size() != questions.size()) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Ответьте на все вопросы автора", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
List<ClaimAnswerDto> qa = new ArrayList<>();
|
||||||
|
for (int i = 0; i < questions.size(); i++) {
|
||||||
|
String answer = answers.get(i);
|
||||||
|
if (!StringUtils.hasText(answer)) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Ответьте на все вопросы автора", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
if (answer.length() > MAX_ANSWER_LENGTH) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||||
|
"Ответ длиннее " + MAX_ANSWER_LENGTH + " символов", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
qa.add(new ClaimAnswerDto(questions.get(i), answer.trim()));
|
||||||
|
}
|
||||||
|
return qa;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Текст сообщения — для превью в списке чатов и клиентов, которые не знают kind = CLAIM. */
|
||||||
|
private static String formatAnswers(List<ClaimAnswerDto> qa) {
|
||||||
|
StringBuilder text = new StringBuilder("Ответы на вопросы автора объявления:");
|
||||||
|
for (int i = 0; i < qa.size(); i++) {
|
||||||
|
text.append("\n\n").append(i + 1).append(". ").append(qa.get(i).question())
|
||||||
|
.append("\n— ").append(qa.get(i).answer());
|
||||||
|
}
|
||||||
|
return text.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkLimit(String rule, String subject, int limit, Duration window, String message) {
|
||||||
|
RedisRateLimiter.Decision decision = rateLimiter.hit(rule, subject, limit, window);
|
||||||
|
if (!decision.allowed()) {
|
||||||
|
log.warn("Лимит заявок '{}' превышен: {}", rule, subject);
|
||||||
|
throw new ApiException(ErrorCode.TOO_MANY_REQUESTS, message, HttpStatus.TOO_MANY_REQUESTS,
|
||||||
|
decision.retryAfterSeconds());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,13 +13,16 @@ import com.krylov.refound.entity.Post;
|
|||||||
import com.krylov.refound.entity.User;
|
import com.krylov.refound.entity.User;
|
||||||
import com.krylov.refound.enums.AttachmentKind;
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
import com.krylov.refound.enums.AttachmentStatus;
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
import com.krylov.refound.enums.ErrorCode;
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
|
import com.krylov.refound.enums.MessageKind;
|
||||||
import com.krylov.refound.exception.ApiException;
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.repository.ChatRepository;
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||||
import com.krylov.refound.repository.MessageRepository;
|
import com.krylov.refound.repository.MessageRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import com.krylov.refound.repository.UserRepository;
|
import com.krylov.refound.repository.UserRepository;
|
||||||
|
import com.krylov.refound.service.antifraud.FraudSignals;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -84,6 +87,7 @@ public class ChatService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
|
public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
|
||||||
validateContent(content);
|
validateContent(content);
|
||||||
|
boolean requiresVerification = false;
|
||||||
if (currentUserId.equals(otherUserId)) {
|
if (currentUserId.equals(otherUserId)) {
|
||||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
@@ -98,14 +102,24 @@ public class ChatService {
|
|||||||
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
|
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
|
||||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
requiresVerification = post.requiresVerification() && !ownerId.equals(currentUserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
Long userId1 = Math.min(currentUserId, otherUserId);
|
Long userId1 = Math.min(currentUserId, otherUserId);
|
||||||
Long userId2 = Math.max(currentUserId, otherUserId);
|
Long userId2 = Math.max(currentUserId, otherUserId);
|
||||||
|
|
||||||
|
Optional<Chat> existing = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst();
|
||||||
|
if (existing.isPresent()) {
|
||||||
|
checkCanWrite(existing.get(), currentUserId);
|
||||||
|
} else if (requiresVerification) {
|
||||||
|
// К объявлению с контрольными вопросами первое сообщение — только ответы на них
|
||||||
|
throw new ApiException(ErrorCode.VERIFICATION_REQUIRED,
|
||||||
|
"Сначала ответьте на вопросы автора объявления", HttpStatus.FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
// Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
|
// Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
|
||||||
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
|
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
|
||||||
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
|
Chat chat = existing.orElseGet(() -> {
|
||||||
Chat newChat = new Chat();
|
Chat newChat = new Chat();
|
||||||
newChat.setUserOneId(userId1);
|
newChat.setUserOneId(userId1);
|
||||||
newChat.setUserTwoId(userId2);
|
newChat.setUserTwoId(userId2);
|
||||||
@@ -169,6 +183,7 @@ public class ChatService {
|
|||||||
// Права проверяем до загрузки: посторонний не должен класть файлы в чужой чат
|
// Права проверяем до загрузки: посторонний не должен класть файлы в чужой чат
|
||||||
Chat chat = getChatOrThrow(chatId);
|
Chat chat = getChatOrThrow(chatId);
|
||||||
checkParticipant(chat, senderId);
|
checkParticipant(chat, senderId);
|
||||||
|
checkCanWrite(chat, senderId);
|
||||||
|
|
||||||
List<ChatAttachmentService.StoredPhoto> stored = attachmentService.storePhotos(chatId, photos);
|
List<ChatAttachmentService.StoredPhoto> stored = attachmentService.storePhotos(chatId, photos);
|
||||||
List<MessageAttachment> attachments = new ArrayList<>();
|
List<MessageAttachment> attachments = new ArrayList<>();
|
||||||
@@ -204,6 +219,7 @@ public class ChatService {
|
|||||||
public ChatVideoUploadService.UploadTicket requestVideoUpload(Long userId, Long chatId, String contentType, long sizeBytes) {
|
public ChatVideoUploadService.UploadTicket requestVideoUpload(Long userId, Long chatId, String contentType, long sizeBytes) {
|
||||||
Chat chat = getChatOrThrow(chatId);
|
Chat chat = getChatOrThrow(chatId);
|
||||||
checkParticipant(chat, userId);
|
checkParticipant(chat, userId);
|
||||||
|
checkCanWrite(chat, userId);
|
||||||
return videoUploadService.requestUpload(chatId, userId, contentType, sizeBytes);
|
return videoUploadService.requestUpload(chatId, userId, contentType, sizeBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,6 +236,7 @@ public class ChatService {
|
|||||||
}
|
}
|
||||||
Chat chat = getChatOrThrow(chatId);
|
Chat chat = getChatOrThrow(chatId);
|
||||||
checkParticipant(chat, senderId);
|
checkParticipant(chat, senderId);
|
||||||
|
checkCanWrite(chat, senderId);
|
||||||
|
|
||||||
ChatVideoUploadService.ClaimedSource source = videoUploadService.claim(chatId, senderId, sourceKey);
|
ChatVideoUploadService.ClaimedSource source = videoUploadService.claim(chatId, senderId, sourceKey);
|
||||||
MessageAttachment video = new MessageAttachment();
|
MessageAttachment video = new MessageAttachment();
|
||||||
@@ -257,10 +274,19 @@ public class ChatService {
|
|||||||
|
|
||||||
Chat chat = getChatOrThrow(chatId);
|
Chat chat = getChatOrThrow(chatId);
|
||||||
checkParticipant(chat, senderId);
|
checkParticipant(chat, senderId);
|
||||||
|
checkCanWrite(chat, senderId);
|
||||||
|
|
||||||
saveAndBroadcast(chat, senderId, content, List.of());
|
saveAndBroadcast(chat, senderId, content, List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Один чат участника: ChatPage берёт из него статус проверки ответов и данные собеседника. */
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public ChatDto getChat(Long chatId, Long userId) {
|
||||||
|
Chat chat = getChatOrThrow(chatId);
|
||||||
|
checkParticipant(chat, userId);
|
||||||
|
return toDto(chat, userId);
|
||||||
|
}
|
||||||
|
|
||||||
private void validateContent(String content) {
|
private void validateContent(String content) {
|
||||||
if (content == null || content.isBlank()) {
|
if (content == null || content.isBlank()) {
|
||||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
|
||||||
@@ -277,11 +303,19 @@ public class ChatService {
|
|||||||
*/
|
*/
|
||||||
private MessageDto saveAndBroadcast(Chat chat, Long senderId, String content,
|
private MessageDto saveAndBroadcast(Chat chat, Long senderId, String content,
|
||||||
List<MessageAttachment> newAttachments) {
|
List<MessageAttachment> newAttachments) {
|
||||||
|
return saveAndBroadcast(chat, senderId, content, newAttachments, MessageKind.TEXT, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** То же для служебных сообщений заявки (ChatClaimService): CLAIM и VERIFICATION. */
|
||||||
|
MessageDto saveAndBroadcast(Chat chat, Long senderId, String content,
|
||||||
|
List<MessageAttachment> newAttachments, MessageKind kind, String payload) {
|
||||||
Long chatId = chat.getId();
|
Long chatId = chat.getId();
|
||||||
Message message = new Message();
|
Message message = new Message();
|
||||||
message.setChatId(chatId);
|
message.setChatId(chatId);
|
||||||
message.setSenderId(senderId);
|
message.setSenderId(senderId);
|
||||||
message.setContent(content);
|
message.setContent(content);
|
||||||
|
message.setKind(kind);
|
||||||
|
message.setPayload(payload);
|
||||||
message = messageRepository.save(message);
|
message = messageRepository.save(message);
|
||||||
|
|
||||||
List<MessageAttachment> attachments = new ArrayList<>(newAttachments);
|
List<MessageAttachment> attachments = new ArrayList<>(newAttachments);
|
||||||
@@ -368,18 +402,32 @@ public class ChatService {
|
|||||||
return chatRepository.isParticipantOfChat(chatId, userId);
|
return chatRepository.isParticipantOfChat(chatId, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Chat getChatOrThrow(Long chatId) {
|
Chat getChatOrThrow(Long chatId) {
|
||||||
return chatRepository.findById(chatId)
|
return chatRepository.findById(chatId)
|
||||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
|
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkParticipant(Chat chat, Long userId) {
|
/**
|
||||||
|
* Заявитель к объявлению с вопросами пишет только после того, как автор
|
||||||
|
* подтвердил ответы. Автор может писать всегда — например, чтобы уточнить.
|
||||||
|
*/
|
||||||
|
private static void checkCanWrite(Chat chat, Long userId) {
|
||||||
|
if (!chat.isLockedFor(userId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String message = chat.getVerificationStatus() == ChatVerificationStatus.REJECTED
|
||||||
|
? "Автор объявления не подтвердил ваши ответы"
|
||||||
|
: "Автор объявления ещё проверяет ваши ответы — написать можно будет после подтверждения";
|
||||||
|
throw new ApiException(ErrorCode.VERIFICATION_REQUIRED, message, HttpStatus.FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
void checkParticipant(Chat chat, Long userId) {
|
||||||
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
||||||
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
|
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ChatDto toDto(Chat chat, Long currentUserId) {
|
ChatDto toDto(Chat chat, Long currentUserId) {
|
||||||
return toDtos(List.of(chat), currentUserId).get(0);
|
return toDtos(List.of(chat), currentUserId).get(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,7 +478,10 @@ public class ChatService {
|
|||||||
if (other != null) {
|
if (other != null) {
|
||||||
dto.setOtherUserName(other.getName() + " " + other.getLastName());
|
dto.setOtherUserName(other.getName() + " " + other.getLastName());
|
||||||
dto.setOtherUserAvatar(other.getAvatarUrl());
|
dto.setOtherUserAvatar(other.getAvatarUrl());
|
||||||
|
dto.setOtherUserCreatedAt(other.getCreatedAt());
|
||||||
}
|
}
|
||||||
|
dto.setVerificationStatus(chat.getVerificationStatus());
|
||||||
|
dto.setClaimantId(chat.getClaimantId());
|
||||||
|
|
||||||
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
|
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
|
||||||
if (post != null) {
|
if (post != null) {
|
||||||
@@ -441,6 +492,7 @@ public class ChatService {
|
|||||||
postDto.setType(post.getType());
|
postDto.setType(post.getType());
|
||||||
postDto.setStatus(post.getStatus());
|
postDto.setStatus(post.getStatus());
|
||||||
postDto.setCity(post.getCity());
|
postDto.setCity(post.getCity());
|
||||||
|
postDto.setPhoneVisible(post.isPhoneVisible());
|
||||||
dto.setPost(postDto);
|
dto.setPost(postDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,6 +521,14 @@ public class ChatService {
|
|||||||
dto.setContent(m.getContent());
|
dto.setContent(m.getContent());
|
||||||
dto.setRead(m.isRead());
|
dto.setRead(m.isRead());
|
||||||
dto.setCreatedAt(m.getCreatedAt());
|
dto.setCreatedAt(m.getCreatedAt());
|
||||||
|
MessageKind kind = m.getKind() == null ? MessageKind.TEXT : m.getKind();
|
||||||
|
dto.setKind(kind);
|
||||||
|
switch (kind) {
|
||||||
|
case CLAIM -> dto.setClaimAnswers(ClaimPayload.readAnswers(m.getPayload()));
|
||||||
|
case VERIFICATION -> dto.setVerificationStatus(ClaimPayload.readStatus(m.getPayload()));
|
||||||
|
// Регулярки по сообщению дешевле отдельной колонки и работают и для старой переписки
|
||||||
|
default -> dto.setFraudSignal(FraudSignals.detect(m.getContent()));
|
||||||
|
}
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
54
src/main/java/com/krylov/refound/service/ClaimPayload.java
Normal file
54
src/main/java/com/krylov/refound/service/ClaimPayload.java
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package com.krylov.refound.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.krylov.refound.dto.ClaimAnswerDto;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Содержимое служебных сообщений заявки (messages.payload): у CLAIM — JSON
|
||||||
|
* вопросов и ответов, у VERIFICATION — имя статуса. Вопросы копируются в
|
||||||
|
* сообщение: автор может потом их поменять, а ответы должны остаться при своих.
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
final class ClaimPayload {
|
||||||
|
|
||||||
|
private static final ObjectMapper JSON = new ObjectMapper();
|
||||||
|
private static final TypeReference<List<ClaimAnswerDto>> ANSWERS = new TypeReference<>() {
|
||||||
|
};
|
||||||
|
|
||||||
|
private ClaimPayload() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static String writeAnswers(List<ClaimAnswerDto> answers) {
|
||||||
|
try {
|
||||||
|
return JSON.writeValueAsString(answers);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new IllegalStateException("Ответы на вопросы не сериализуются", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<ClaimAnswerDto> readAnswers(String payload) {
|
||||||
|
if (payload == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return JSON.readValue(payload, ANSWERS);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
// Текст ответов есть и в content: сообщение покажется обычным
|
||||||
|
log.warn("Повреждённые ответы в сообщении-заявке: {}", e.getMessage());
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static ChatVerificationStatus readStatus(String payload) {
|
||||||
|
try {
|
||||||
|
return payload == null ? null : ChatVerificationStatus.valueOf(payload);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -86,6 +86,7 @@ public class PostService {
|
|||||||
if (phoneVisible) {
|
if (phoneVisible) {
|
||||||
PostFieldLimits.requirePhone(request.getPhone());
|
PostFieldLimits.requirePhone(request.getPhone());
|
||||||
}
|
}
|
||||||
|
List<String> questions = parseVerificationQuestions(request.getVerificationQuestions());
|
||||||
|
|
||||||
AddressInfo location = geocode(request.getLatitude(), request.getLongitude());
|
AddressInfo location = geocode(request.getLatitude(), request.getLongitude());
|
||||||
List<String> imageKeys = uploadImages(images);
|
List<String> imageKeys = uploadImages(images);
|
||||||
@@ -99,6 +100,7 @@ public class PostService {
|
|||||||
post.setUser(currentUser);
|
post.setUser(currentUser);
|
||||||
post.setIsReward(request.getReward());
|
post.setIsReward(request.getReward());
|
||||||
applyPhone(post, request.getPhone(), phoneVisible);
|
applyPhone(post, request.getPhone(), phoneVisible);
|
||||||
|
applyVerificationQuestions(post, questions);
|
||||||
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
|
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
|
||||||
post.setAddress(normalizeAddress(request.getAddress()));
|
post.setAddress(normalizeAddress(request.getAddress()));
|
||||||
applyLocation(post, location, request.getAddress());
|
applyLocation(post, location, request.getAddress());
|
||||||
@@ -214,7 +216,8 @@ public class PostService {
|
|||||||
*/
|
*/
|
||||||
public PostResponse update(Long id, String type, String title, String address, Double latitude,
|
public PostResponse update(Long id, String type, String title, String address, Double latitude,
|
||||||
Double longitude, String description, String category, String phone, Boolean phoneVisible,
|
Double longitude, String description, String category, String phone, Boolean phoneVisible,
|
||||||
Boolean reward, String rewardText, List<MultipartFile> images, String existingImagesJson) {
|
Boolean reward, String rewardText, List<MultipartFile> images, String existingImagesJson,
|
||||||
|
String verificationQuestionsJson) {
|
||||||
|
|
||||||
PostRequest request = new PostRequest();
|
PostRequest request = new PostRequest();
|
||||||
request.setType(PostType.from(type));
|
request.setType(PostType.from(type));
|
||||||
@@ -234,6 +237,7 @@ public class PostService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<String> existingUrls = parseExistingImages(existingImagesJson);
|
List<String> existingUrls = parseExistingImages(existingImagesJson);
|
||||||
|
List<String> questions = parseVerificationQuestions(verificationQuestionsJson);
|
||||||
|
|
||||||
// Проверка владельца — до обращения к внешним сервисам и загрузки файлов
|
// Проверка владельца — до обращения к внешним сервисам и загрузки файлов
|
||||||
findOwnedPost(id);
|
findOwnedPost(id);
|
||||||
@@ -241,7 +245,8 @@ public class PostService {
|
|||||||
List<String> imageKeys = uploadImages(images);
|
List<String> imageKeys = uploadImages(images);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return transactionTemplate.execute(status -> doUpdate(id, request, imageKeys, existingUrls, location));
|
return transactionTemplate.execute(status -> doUpdate(id, request, imageKeys, existingUrls, questions,
|
||||||
|
location));
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
postDeletionService.deleteFilesAfterCommit(imageKeys);
|
postDeletionService.deleteFilesAfterCommit(imageKeys);
|
||||||
throw e;
|
throw e;
|
||||||
@@ -249,7 +254,7 @@ public class PostService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private PostResponse doUpdate(Long id, PostRequest request, List<String> imageKeys, List<String> existingUrls,
|
private PostResponse doUpdate(Long id, PostRequest request, List<String> imageKeys, List<String> existingUrls,
|
||||||
AddressInfo location) {
|
List<String> questions, AddressInfo location) {
|
||||||
Post post = findOwnedPost(id);
|
Post post = findOwnedPost(id);
|
||||||
|
|
||||||
post.setStatus(PostStatus.MODERATION);
|
post.setStatus(PostStatus.MODERATION);
|
||||||
@@ -262,6 +267,7 @@ public class PostService {
|
|||||||
boolean phoneVisible = request.getPhoneVisible() != null ? request.getPhoneVisible() : post.isPhoneVisible();
|
boolean phoneVisible = request.getPhoneVisible() != null ? request.getPhoneVisible() : post.isPhoneVisible();
|
||||||
applyPhone(post, request.getPhone(), phoneVisible);
|
applyPhone(post, request.getPhone(), phoneVisible);
|
||||||
post.setType(request.getType());
|
post.setType(request.getType());
|
||||||
|
applyVerificationQuestions(post, questions);
|
||||||
post.setIsReward(request.getReward());
|
post.setIsReward(request.getReward());
|
||||||
post.setReward(request.getRewardText());
|
post.setReward(request.getRewardText());
|
||||||
post.setAddress(normalizeAddress(request.getAddress()));
|
post.setAddress(normalizeAddress(request.getAddress()));
|
||||||
@@ -475,6 +481,40 @@ public class PostService {
|
|||||||
post.setPhone(phone.trim());
|
post.setPhone(phone.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Контрольные вопросы автора. У потери они отсекают «нашёл, оплатите доставку»:
|
||||||
|
* мошенник вещи в руках не держал и не ответит, что выгравировано на обороте.
|
||||||
|
* У находки — «это моё» от тех, кто просто увидел фото.
|
||||||
|
* questions == null — клиент поле не прислал, вопросы не меняются.
|
||||||
|
*/
|
||||||
|
static void applyVerificationQuestions(Post post, List<String> questions) {
|
||||||
|
if (questions == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
post.getVerificationQuestions().clear();
|
||||||
|
post.getVerificationQuestions().addAll(questions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JSON-массив вопросов из формы: пустые строки отбрасываются; null — поле не прислано. */
|
||||||
|
private List<String> parseVerificationQuestions(String json) {
|
||||||
|
if (json == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String[] raw;
|
||||||
|
try {
|
||||||
|
raw = objectMapper.readValue(json, String[].class);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Некорректный формат verificationQuestions",
|
||||||
|
HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
List<String> questions = raw == null ? List.of() : Arrays.stream(raw)
|
||||||
|
.filter(StringUtils::hasText)
|
||||||
|
.map(String::trim)
|
||||||
|
.toList();
|
||||||
|
PostFieldLimits.validateVerificationQuestions(questions);
|
||||||
|
return questions;
|
||||||
|
}
|
||||||
|
|
||||||
private List<String> parseExistingImages(String existingImagesJson) {
|
private List<String> parseExistingImages(String existingImagesJson) {
|
||||||
if (existingImagesJson == null) {
|
if (existingImagesJson == null) {
|
||||||
return List.of();
|
return List.of();
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.krylov.refound.service.antifraud;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
/** Лимиты заявок к объявлениям с контрольными вопросами ({@code anti-fraud.*}). */
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@ConfigurationProperties(prefix = "anti-fraud")
|
||||||
|
public class AntiFraudProperties {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сколько заявок один аккаунт может отправить за сутки: мошенник, который
|
||||||
|
* рассылает «нашёл вашу вещь» по всем потерям подряд, упирается в лимит.
|
||||||
|
*/
|
||||||
|
private int claimDailyLimit = 5;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сколько раз можно ответить на вопросы одного объявления за claimRetryWindow.
|
||||||
|
* Иначе, удалив отклонённый чат, заявитель подбирал бы ответы заново.
|
||||||
|
*/
|
||||||
|
private int claimAttemptsPerPost = 2;
|
||||||
|
private Duration claimRetryWindow = Duration.ofDays(30);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package com.krylov.refound.service.antifraud;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.FraudSignal;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Распознаёт в сообщении чата типичные просьбы мошенников: «переведите
|
||||||
|
* предоплату за доставку», «продиктуйте код из СМС», номер карты. Сообщение
|
||||||
|
* не блокируется — фронт показывает получателю предупреждение. Ложные
|
||||||
|
* срабатывания допустимы: предупреждение ничего не запрещает, а пропущенная
|
||||||
|
* схема стоит человеку денег.
|
||||||
|
*/
|
||||||
|
public final class FraudSignals {
|
||||||
|
|
||||||
|
private static final int FLAGS = Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS;
|
||||||
|
|
||||||
|
// Порядок вставки — приоритет: при нескольких признаках показываем самый опасный
|
||||||
|
private static final Map<FraudSignal, List<Pattern>> PATTERNS = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
PATTERNS.put(FraudSignal.SMS_CODE, compile(
|
||||||
|
"код\\w*.{0,20}(смс|sms|сообщени|пуш|push)",
|
||||||
|
"(смс|sms)[- ]?код",
|
||||||
|
"(продикту|назов|назва|скаж|сообщ|пришл|скин|отправ)\\w*.{0,15}\\bкод",
|
||||||
|
"код\\w* подтвержд",
|
||||||
|
"госуслуг"));
|
||||||
|
PATTERNS.put(FraudSignal.CARD_DATA, compile(
|
||||||
|
"\\b(cvv2?|cvc2?)\\b",
|
||||||
|
"срок\\w* действия карт",
|
||||||
|
"(три|3) цифры (на|с) (обороте|обратной)"));
|
||||||
|
PATTERNS.put(FraudSignal.PREPAYMENT, compile(
|
||||||
|
"предоплат",
|
||||||
|
"\\bпереве(ди|дите|сти)\\b",
|
||||||
|
"\\b(скин|закин)(ь|ьте|уть)\\b",
|
||||||
|
"\\bзалог",
|
||||||
|
"\\bсбп\\b",
|
||||||
|
"(оплат|заплат)\\w*.{0,25}(доставк|пересылк|курьер|сдэк|cdek|почт|такси)",
|
||||||
|
"(доставк|пересылк|курьер|сдэк|cdek)\\w*.{0,40}(оплат|заплат|перевод|переве|руб|₽)",
|
||||||
|
"\\bна (карту|карточку|киви|qiwi|юмани|yoomoney)\\b",
|
||||||
|
"\\b(prepay|prepayment|advance payment|send money|wire transfer)\\b"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 13–19 цифр, можно через пробелы и дефисы; номер телефона (до 12 цифр) не подходит
|
||||||
|
private static final Pattern CARD_NUMBER = Pattern.compile("(?<!\\d)\\d(?:[ -]?\\d){12,18}(?!\\d)");
|
||||||
|
|
||||||
|
private FraudSignals() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Самый опасный признак в тексте или null. */
|
||||||
|
public static FraudSignal detect(String text) {
|
||||||
|
if (text == null || text.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String normalized = text.toLowerCase(Locale.ROOT).replace('ё', 'е');
|
||||||
|
for (Map.Entry<FraudSignal, List<Pattern>> entry : PATTERNS.entrySet()) {
|
||||||
|
if (entry.getKey() == FraudSignal.CARD_DATA && containsCardNumber(normalized)) {
|
||||||
|
return FraudSignal.CARD_DATA;
|
||||||
|
}
|
||||||
|
for (Pattern pattern : entry.getValue()) {
|
||||||
|
if (pattern.matcher(normalized).find()) {
|
||||||
|
return entry.getKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean containsCardNumber(String text) {
|
||||||
|
Matcher matcher = CARD_NUMBER.matcher(text);
|
||||||
|
while (matcher.find()) {
|
||||||
|
if (luhnValid(matcher.group().replaceAll("[ -]", ""))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Контрольная сумма номеров карт: отсекает случайные длинные числа (трек-номера, суммы). */
|
||||||
|
static boolean luhnValid(String digits) {
|
||||||
|
int sum = 0;
|
||||||
|
boolean doubled = false;
|
||||||
|
for (int i = digits.length() - 1; i >= 0; i--) {
|
||||||
|
int d = digits.charAt(i) - '0';
|
||||||
|
if (doubled) {
|
||||||
|
d *= 2;
|
||||||
|
if (d > 9) {
|
||||||
|
d -= 9;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum += d;
|
||||||
|
doubled = !doubled;
|
||||||
|
}
|
||||||
|
return sum % 10 == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Pattern> compile(String... regexes) {
|
||||||
|
return Arrays.stream(regexes).map(regex -> Pattern.compile(regex, FLAGS)).toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
package com.krylov.refound.service.phone;
|
package com.krylov.refound.service.phone;
|
||||||
|
|
||||||
import com.krylov.refound.entity.Post;
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
import com.krylov.refound.enums.ErrorCode;
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
import com.krylov.refound.exception.ApiException;
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||||
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -28,7 +30,8 @@ import org.springframework.util.StringUtils;
|
|||||||
* номера или несуществующего, неверное решение, id-ловушки), — это
|
* номера или несуществующего, неверное решение, id-ловушки), — это
|
||||||
* перебор; после нескольких таких IP банится на сутки.</li>
|
* перебор; после нескольких таких IP банится на сутки.</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
* Номер показывается только у активных объявлений с согласием автора.
|
* Номер показывается только у активных объявлений с согласием автора. У объявления
|
||||||
|
* с контрольными вопросами — только автору и заявителю, чьи ответы автор подтвердил.
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -48,12 +51,14 @@ public class PhoneRevealService {
|
|||||||
private final RedisRateLimiter rateLimiter;
|
private final RedisRateLimiter rateLimiter;
|
||||||
private final StringRedisTemplate redisTemplate;
|
private final StringRedisTemplate redisTemplate;
|
||||||
private final PhoneRevealProperties properties;
|
private final PhoneRevealProperties properties;
|
||||||
|
private final ChatRepository chatRepository;
|
||||||
|
|
||||||
/** Задача для открытия номера; сложность зависит от того, сколько номеров IP уже открыл за час. */
|
/** Задача для открытия номера; сложность зависит от того, сколько номеров IP уже открыл за час. */
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public ProofOfWorkService.Challenge challenge(long postId, String ip) {
|
public ProofOfWorkService.Challenge challenge(long postId, String ip, Long userId) {
|
||||||
checkNotBanned(ip);
|
checkNotBanned(ip);
|
||||||
requireRevealablePost(postId, ip);
|
// Задачу не выдаём, если номер всё равно не откроется: не тратим CPU клиента
|
||||||
|
checkVerified(requireRevealablePost(postId, ip), userId);
|
||||||
long revealsThisHour = rateLimiter.current(RULE_HOUR, ip, HOUR);
|
long revealsThisHour = rateLimiter.current(RULE_HOUR, ip, HOUR);
|
||||||
return proofOfWork.create(postId, proofOfWork.maxNumberFor(revealsThisHour));
|
return proofOfWork.create(postId, proofOfWork.maxNumberFor(revealsThisHour));
|
||||||
}
|
}
|
||||||
@@ -69,10 +74,11 @@ public class PhoneRevealService {
|
|||||||
HttpStatus.BAD_REQUEST);
|
HttpStatus.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
Post post = requireRevealablePost(postId, ip);
|
Post post = requireRevealablePost(postId, ip);
|
||||||
if (userId != null && post.getUser() != null && userId.equals(post.getUser().getId())) {
|
if (isOwner(post, userId)) {
|
||||||
// Автор смотрит свой номер в ленте — это не сбор, лимиты не тратим
|
// Автор смотрит свой номер в ленте — это не сбор, лимиты не тратим
|
||||||
return post.getPhone();
|
return post.getPhone();
|
||||||
}
|
}
|
||||||
|
checkVerified(post, userId);
|
||||||
|
|
||||||
// Лимиты считаем после проверки решения: каждая попытка сборщика стоит ему CPU
|
// Лимиты считаем после проверки решения: каждая попытка сборщика стоит ему CPU
|
||||||
checkLimit(RULE_HOUR, ip, properties.getIpHourlyLimit(), HOUR);
|
checkLimit(RULE_HOUR, ip, properties.getIpHourlyLimit(), HOUR);
|
||||||
@@ -99,6 +105,25 @@ public class PhoneRevealService {
|
|||||||
return post;
|
return post;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Объявление с контрольными вопросами: номер — только заявителю с подтверждёнными
|
||||||
|
* ответами. Это не перебор (кнопку видят все), поэтому без штрафа IP.
|
||||||
|
*/
|
||||||
|
private void checkVerified(Post post, Long userId) {
|
||||||
|
if (!post.requiresVerification() || isOwner(post, userId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (userId == null || !chatRepository.existsByClaimantIdAndPostIdAndVerificationStatus(userId, post.getId(),
|
||||||
|
ChatVerificationStatus.APPROVED)) {
|
||||||
|
throw new ApiException(ErrorCode.VERIFICATION_REQUIRED,
|
||||||
|
"Номер откроется, когда автор объявления подтвердит ваши ответы на его вопросы", HttpStatus.FORBIDDEN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isOwner(Post post, Long userId) {
|
||||||
|
return userId != null && post.getUser() != null && userId.equals(post.getUser().getId());
|
||||||
|
}
|
||||||
|
|
||||||
private void checkLimit(String rule, String subject, int limit, Duration window) {
|
private void checkLimit(String rule, String subject, int limit, Duration window) {
|
||||||
RedisRateLimiter.Decision decision = rateLimiter.hit(rule, subject, limit, window);
|
RedisRateLimiter.Decision decision = rateLimiter.hit(rule, subject, limit, window);
|
||||||
if (!decision.allowed()) {
|
if (!decision.allowed()) {
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ public final class PostFieldLimits {
|
|||||||
public static final int REWARD_TEXT = 255;
|
public static final int REWARD_TEXT = 255;
|
||||||
public static final int ADDRESS = 500;
|
public static final int ADDRESS = 500;
|
||||||
public static final int CITY = 100;
|
public static final int CITY = 100;
|
||||||
|
/** Контрольные вопросы объявления (changelog 026): сколько и какой длины. */
|
||||||
|
public static final int MAX_VERIFICATION_QUESTIONS = 3;
|
||||||
|
public static final int VERIFICATION_QUESTION = 200;
|
||||||
private static final int MIN_PHONE_DIGITS = 10;
|
private static final int MIN_PHONE_DIGITS = 10;
|
||||||
private static final int MAX_PHONE_DIGITS = 15;
|
private static final int MAX_PHONE_DIGITS = 15;
|
||||||
|
|
||||||
@@ -33,6 +36,15 @@ public final class PostFieldLimits {
|
|||||||
checkLength("Текст вознаграждения", rewardText, REWARD_TEXT);
|
checkLength("Текст вознаграждения", rewardText, REWARD_TEXT);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Контрольные вопросы объявления: не больше трёх, каждый до 200 символов. */
|
||||||
|
public static void validateVerificationQuestions(java.util.List<String> questions) {
|
||||||
|
if (questions.size() > MAX_VERIFICATION_QUESTIONS) {
|
||||||
|
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||||
|
"Не больше " + MAX_VERIFICATION_QUESTIONS + " контрольных вопросов", HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
questions.forEach(q -> checkLength("Контрольный вопрос", q, VERIFICATION_QUESTION));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Номер для показа другим пользователям: 10–15 цифр (E.164), остальное —
|
* Номер для показа другим пользователям: 10–15 цифр (E.164), остальное —
|
||||||
* форматирование. 400 VALIDATION_ERROR, если номера нет или он некорректен.
|
* форматирование. 400 VALIDATION_ERROR, если номера нет или он некорректен.
|
||||||
|
|||||||
@@ -193,6 +193,12 @@ rate-limit:
|
|||||||
paths: [/api/v1/chats/with/**]
|
paths: [/api/v1/chats/with/**]
|
||||||
limit: 30
|
limit: 30
|
||||||
window: PT1M
|
window: PT1M
|
||||||
|
# «Это моё» с одного IP (суточный лимит на аккаунт — anti-fraud.claim-daily-limit)
|
||||||
|
- name: post-claim
|
||||||
|
method: POST
|
||||||
|
paths: [/api/v1/posts/*/claim]
|
||||||
|
limit: 10
|
||||||
|
window: PT1H
|
||||||
# Первый рубеж против сборщиков номеров — короткие всплески; часовые и
|
# Первый рубеж против сборщиков номеров — короткие всплески; часовые и
|
||||||
# суточные лимиты, PoW и баны — в PhoneRevealService (phone-reveal.*)
|
# суточные лимиты, PoW и баны — в PhoneRevealService (phone-reveal.*)
|
||||||
- name: phone-challenge
|
- name: phone-challenge
|
||||||
@@ -217,6 +223,12 @@ rate-limit:
|
|||||||
window: PT1M
|
window: PT1M
|
||||||
|
|
||||||
# Защита номеров от сбора (PhoneRevealService, docs/phone-protection.md)
|
# Защита номеров от сбора (PhoneRevealService, docs/phone-protection.md)
|
||||||
|
# Заявки к объявлениям с контрольными вопросами (ChatClaimService)
|
||||||
|
anti-fraud:
|
||||||
|
claim-daily-limit: ${ANTI_FRAUD_CLAIM_DAILY_LIMIT:5}
|
||||||
|
claim-attempts-per-post: 2
|
||||||
|
claim-retry-window: P30D
|
||||||
|
|
||||||
phone-reveal:
|
phone-reveal:
|
||||||
# HMAC-ключ задач proof-of-work; пусто — используется jwt.secret
|
# HMAC-ключ задач proof-of-work; пусто — используется jwt.secret
|
||||||
secret: ${PHONE_REVEAL_SECRET:}
|
secret: ${PHONE_REVEAL_SECRET:}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
databaseChangeLog:
|
||||||
|
- changeSet:
|
||||||
|
id: 026-anti-fraud-verification
|
||||||
|
author: krylov
|
||||||
|
comment: >
|
||||||
|
Защита от мошенников. post_verification_questions — контрольные вопросы
|
||||||
|
автора объявления (до 3): чтобы написать ему, нужно ответить, а чат и
|
||||||
|
номер открываются только после подтверждения ответов автором.
|
||||||
|
chats.verification_status — PENDING/APPROVED/REJECTED у чата-заявки
|
||||||
|
(null — обычный чат), claimant_id — кто ответил на вопросы.
|
||||||
|
messages.kind — TEXT (обычное), CLAIM (ответы на вопросы, payload — JSON
|
||||||
|
вопросов и ответов), VERIFICATION (решение автора, payload — статус).
|
||||||
|
preConditions:
|
||||||
|
onFail: MARK_RAN
|
||||||
|
not:
|
||||||
|
tableExists:
|
||||||
|
tableName: post_verification_questions
|
||||||
|
changes:
|
||||||
|
- createTable:
|
||||||
|
tableName: post_verification_questions
|
||||||
|
columns:
|
||||||
|
- column: { name: post_id, type: BIGINT, constraints: { nullable: false } }
|
||||||
|
- column: { name: position, type: INT, constraints: { nullable: false } }
|
||||||
|
- column: { name: question, type: VARCHAR(200), constraints: { nullable: false } }
|
||||||
|
- addPrimaryKey:
|
||||||
|
tableName: post_verification_questions
|
||||||
|
columnNames: post_id, position
|
||||||
|
constraintName: pk_post_verification_questions
|
||||||
|
- addForeignKeyConstraint:
|
||||||
|
baseTableName: post_verification_questions
|
||||||
|
baseColumnNames: post_id
|
||||||
|
referencedTableName: posts
|
||||||
|
referencedColumnNames: id
|
||||||
|
constraintName: fk_post_verification_questions_post
|
||||||
|
onDelete: CASCADE
|
||||||
|
- addColumn:
|
||||||
|
tableName: chats
|
||||||
|
columns:
|
||||||
|
- column: { name: verification_status, type: VARCHAR(16) }
|
||||||
|
- column: { name: claimant_id, type: BIGINT }
|
||||||
|
- column: { name: verified_at, type: TIMESTAMP }
|
||||||
|
- createIndex:
|
||||||
|
tableName: chats
|
||||||
|
indexName: idx_chats_claimant_post
|
||||||
|
columns:
|
||||||
|
- column: { name: claimant_id }
|
||||||
|
- column: { name: post_id }
|
||||||
|
- addColumn:
|
||||||
|
tableName: messages
|
||||||
|
columns:
|
||||||
|
- column:
|
||||||
|
name: kind
|
||||||
|
type: VARCHAR(16)
|
||||||
|
defaultValue: TEXT
|
||||||
|
constraints: { nullable: false }
|
||||||
|
- column: { name: payload, type: TEXT }
|
||||||
@@ -38,3 +38,4 @@ databaseChangeLog:
|
|||||||
- include: { file: db/changelog/add/023-add-phone-visible-posts.yaml }
|
- include: { file: db/changelog/add/023-add-phone-visible-posts.yaml }
|
||||||
- include: { file: db/changelog/create/024-create-message-attachments.yaml }
|
- include: { file: db/changelog/create/024-create-message-attachments.yaml }
|
||||||
- include: { file: db/changelog/add/025-message-attachments-video.yaml }
|
- include: { file: db/changelog/add/025-message-attachments-video.yaml }
|
||||||
|
- include: { file: db/changelog/create/026-anti-fraud-verification.yaml }
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package com.krylov.refound.service;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import com.krylov.refound.config.ClusterMessaging;
|
||||||
|
import com.krylov.refound.dto.ChatDto;
|
||||||
|
import com.krylov.refound.dto.ClaimAnswerDto;
|
||||||
|
import com.krylov.refound.dto.MessageDto;
|
||||||
|
import com.krylov.refound.entity.Chat;
|
||||||
|
import com.krylov.refound.entity.Message;
|
||||||
|
import com.krylov.refound.entity.Post;
|
||||||
|
import com.krylov.refound.entity.User;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
|
import com.krylov.refound.enums.FraudSignal;
|
||||||
|
import com.krylov.refound.enums.MessageKind;
|
||||||
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import com.krylov.refound.enums.PostType;
|
||||||
|
import com.krylov.refound.exception.ApiException;
|
||||||
|
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||||
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
|
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||||
|
import com.krylov.refound.repository.MessageRepository;
|
||||||
|
import com.krylov.refound.repository.PostRepository;
|
||||||
|
import com.krylov.refound.repository.UserRepository;
|
||||||
|
import com.krylov.refound.service.antifraud.AntiFraudProperties;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
|
|
||||||
|
class ChatClaimServiceTest {
|
||||||
|
|
||||||
|
private static final long OWNER = 19L;
|
||||||
|
private static final long CLAIMANT = 14L;
|
||||||
|
private static final long POST = 41L;
|
||||||
|
|
||||||
|
private ChatRepository chatRepository;
|
||||||
|
private PostRepository postRepository;
|
||||||
|
private MessageRepository messageRepository;
|
||||||
|
private RedisRateLimiter rateLimiter;
|
||||||
|
private ChatService chatService;
|
||||||
|
private ChatClaimService claimService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
chatRepository = mock(ChatRepository.class);
|
||||||
|
postRepository = mock(PostRepository.class);
|
||||||
|
messageRepository = mock(MessageRepository.class);
|
||||||
|
rateLimiter = mock(RedisRateLimiter.class);
|
||||||
|
UserRepository userRepository = mock(UserRepository.class);
|
||||||
|
chatService = new ChatService(chatRepository, messageRepository, mock(ClusterMessaging.class),
|
||||||
|
userRepository, postRepository, mock(MessageAttachmentRepository.class), mock(ChatAttachmentService.class),
|
||||||
|
mock(TransactionTemplate.class), mock(ChatVideoUploadService.class), mock(ApplicationEventPublisher.class));
|
||||||
|
claimService = new ChatClaimService(postRepository, chatRepository, chatService, rateLimiter,
|
||||||
|
new AntiFraudProperties());
|
||||||
|
|
||||||
|
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||||
|
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
||||||
|
when(chatRepository.save(any(Chat.class))).thenAnswer(inv -> {
|
||||||
|
Chat chat = inv.getArgument(0);
|
||||||
|
chat.setId(100L);
|
||||||
|
return chat;
|
||||||
|
});
|
||||||
|
when(messageRepository.save(any(Message.class))).thenAnswer(inv -> {
|
||||||
|
Message message = inv.getArgument(0);
|
||||||
|
message.setId(500L);
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
when(rateLimiter.hit(anyString(), anyString(), anyInt(), any()))
|
||||||
|
.thenReturn(new RedisRateLimiter.Decision(true, 1, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Post foundWithQuestions(String... questions) {
|
||||||
|
User owner = new User();
|
||||||
|
owner.setId(OWNER);
|
||||||
|
Post post = new Post();
|
||||||
|
post.setId(POST);
|
||||||
|
post.setUser(owner);
|
||||||
|
post.setType(PostType.FOUND);
|
||||||
|
post.setStatus(PostStatus.ACTIVE);
|
||||||
|
post.setVerificationQuestions(new ArrayList<>(List.of(questions)));
|
||||||
|
when(postRepository.findById(POST)).thenReturn(Optional.of(post));
|
||||||
|
return post;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Chat pendingChat() {
|
||||||
|
Chat chat = new Chat();
|
||||||
|
chat.setId(100L);
|
||||||
|
chat.setUserOneId(CLAIMANT);
|
||||||
|
chat.setUserTwoId(OWNER);
|
||||||
|
chat.setPostId(POST);
|
||||||
|
chat.setVerificationStatus(ChatVerificationStatus.PENDING);
|
||||||
|
chat.setClaimantId(CLAIMANT);
|
||||||
|
when(chatRepository.findById(100L)).thenReturn(Optional.of(chat));
|
||||||
|
return chat;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void claimCreatesPendingChatWithAnswersAsFirstMessage() {
|
||||||
|
foundWithQuestions("Что на брелке?", "Какого цвета чехол?");
|
||||||
|
|
||||||
|
ChatDto chat = claimService.claim(CLAIMANT, POST, List.of(" Сова ", "Синий"));
|
||||||
|
|
||||||
|
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.PENDING);
|
||||||
|
assertThat(chat.getClaimantId()).isEqualTo(CLAIMANT);
|
||||||
|
ArgumentCaptor<Message> saved = ArgumentCaptor.forClass(Message.class);
|
||||||
|
verify(messageRepository).save(saved.capture());
|
||||||
|
Message message = saved.getValue();
|
||||||
|
assertThat(message.getKind()).isEqualTo(MessageKind.CLAIM);
|
||||||
|
assertThat(message.getContent()).contains("Что на брелке?").contains("— Сова");
|
||||||
|
assertThat(ClaimPayload.readAnswers(message.getPayload())).containsExactly(
|
||||||
|
new ClaimAnswerDto("Что на брелке?", "Сова"), new ClaimAnswerDto("Какого цвета чехол?", "Синий"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lossOwnerQuestionsStopFakeFinderBeforeChat() {
|
||||||
|
// Главная схема: «нашёл вашу вещь, оплатите доставку» — к потере только через ответы
|
||||||
|
foundWithQuestions("Что выгравировано на обороте?").setType(PostType.LOSS);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> chatService.startChat(CLAIMANT, OWNER, POST, "Нашёл, оплатите доставку"))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.VERIFICATION_REQUIRED));
|
||||||
|
ChatDto chat = claimService.claim(CLAIMANT, POST, List.of("Инициалы А.К."));
|
||||||
|
|
||||||
|
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.PENDING);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void claimRequiresAnswerToEveryQuestion() {
|
||||||
|
foundWithQuestions("Что на брелке?", "Какого цвета чехол?");
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> claimService.claim(CLAIMANT, POST, List.of("Сова", " ")))
|
||||||
|
.isInstanceOf(ApiException.class);
|
||||||
|
assertThatThrownBy(() -> claimService.claim(CLAIMANT, POST, List.of("Сова")))
|
||||||
|
.isInstanceOf(ApiException.class);
|
||||||
|
verify(chatRepository, never()).save(any());
|
||||||
|
verify(rateLimiter, never()).hit(anyString(), anyString(), anyInt(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void claimOverDailyLimitIsRejected() {
|
||||||
|
foundWithQuestions("Что на брелке?");
|
||||||
|
when(rateLimiter.hit(eq(ChatClaimService.RULE_CLAIM_DAY), anyString(), anyInt(), any()))
|
||||||
|
.thenReturn(new RedisRateLimiter.Decision(false, 6, 600));
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> claimService.claim(CLAIMANT, POST, List.of("Сова")))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS));
|
||||||
|
verify(chatRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void plainFirstMessageToFoundWithQuestionsIsRefused() {
|
||||||
|
foundWithQuestions("Что на брелке?");
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> chatService.startChat(CLAIMANT, OWNER, POST, "Это моё, вышлите доставкой"))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.VERIFICATION_REQUIRED));
|
||||||
|
verify(chatRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ownerCanStillWriteFirstToClaimantOfOwnFound() {
|
||||||
|
foundWithQuestions("Что на брелке?");
|
||||||
|
|
||||||
|
ChatDto chat = chatService.startChat(OWNER, CLAIMANT, POST, "Здравствуйте");
|
||||||
|
|
||||||
|
assertThat(chat.getVerificationStatus()).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void claimantCannotWriteUntilApprovedButOwnerCan() {
|
||||||
|
pendingChat();
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> chatService.sendMessage(CLAIMANT, 100L, "Ну что?"))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||||
|
chatService.sendMessage(OWNER, 100L, "Какая наклейка на обороте?");
|
||||||
|
verify(messageRepository).save(any(Message.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void approvalUnlocksChatAndIsBroadcastAsVerificationMessage() {
|
||||||
|
Chat chat = pendingChat();
|
||||||
|
|
||||||
|
MessageDto decision = claimService.decide(OWNER, 100L, true);
|
||||||
|
|
||||||
|
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.APPROVED);
|
||||||
|
assertThat(chat.getVerifiedAt()).isNotNull();
|
||||||
|
assertThat(decision.getKind()).isEqualTo(MessageKind.VERIFICATION);
|
||||||
|
assertThat(decision.getVerificationStatus()).isEqualTo(ChatVerificationStatus.APPROVED);
|
||||||
|
chatService.sendMessage(CLAIMANT, 100L, "Спасибо!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onlyOwnerDecidesAndApprovalIsFinal() {
|
||||||
|
Chat chat = pendingChat();
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> claimService.decide(CLAIMANT, 100L, true))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||||
|
|
||||||
|
claimService.decide(OWNER, 100L, false);
|
||||||
|
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.REJECTED);
|
||||||
|
// Отклонение можно исправить на подтверждение, но не наоборот
|
||||||
|
claimService.decide(OWNER, 100L, true);
|
||||||
|
assertThatThrownBy(() -> claimService.decide(OWNER, 100L, false))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.CONFLICT));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void messagesWithPrepaymentRequestCarryFraudSignal() {
|
||||||
|
Chat chat = pendingChat();
|
||||||
|
chat.setVerificationStatus(null);
|
||||||
|
Message message = new Message();
|
||||||
|
message.setId(1L);
|
||||||
|
message.setChatId(100L);
|
||||||
|
message.setSenderId(OWNER);
|
||||||
|
message.setContent("Нашёл ваш кошелёк, переведите 500 ₽ за доставку курьером");
|
||||||
|
when(messageRepository.findByChatIdOrderByCreatedAtDesc(eq(100L), any()))
|
||||||
|
.thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(message)));
|
||||||
|
|
||||||
|
MessageDto dto = chatService.getMessages(100L, CLAIMANT, org.springframework.data.domain.Pageable.unpaged())
|
||||||
|
.getContent().get(0);
|
||||||
|
|
||||||
|
assertThat(dto.getFraudSignal()).isEqualTo(FraudSignal.PREPAYMENT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.krylov.refound.service.antifraud;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.FraudSignal;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class FraudSignalsTest {
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(strings = {
|
||||||
|
"Нужна предоплата 50%, потом отправлю",
|
||||||
|
"Переведите 300 рублей, и я отправлю СДЭКом",
|
||||||
|
"оплатите доставку курьером, он привезёт",
|
||||||
|
"Скиньте на карту за пересылку",
|
||||||
|
"Доставка платная, 450 руб",
|
||||||
|
"Скинь по СБП, номер тот же",
|
||||||
|
"Нужен залог, чтобы я не ездил зря"})
|
||||||
|
void detectsPrepaymentRequests(String text) {
|
||||||
|
assertThat(FraudSignals.detect(text)).isEqualTo(FraudSignal.PREPAYMENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(strings = {
|
||||||
|
"Вам придёт код из СМС, продиктуйте его",
|
||||||
|
"Назовите код, который пришёл",
|
||||||
|
"Скажите смс-код для подтверждения",
|
||||||
|
"Зайдите в Госуслуги и подтвердите"})
|
||||||
|
void detectsSmsCodeRequests(String text) {
|
||||||
|
assertThat(FraudSignals.detect(text)).isEqualTo(FraudSignal.SMS_CODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void detectsValidCardNumberAndCvv() {
|
||||||
|
assertThat(FraudSignals.detect("Моя карта 4276 3800 1234 5679")).isEqualTo(FraudSignal.CARD_DATA);
|
||||||
|
assertThat(FraudSignals.detect("и ещё CVV с обратной стороны")).isEqualTo(FraudSignal.CARD_DATA);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void smsCodeOutranksPrepayment() {
|
||||||
|
assertThat(FraudSignals.detect("Переведите предоплату и продиктуйте код из смс"))
|
||||||
|
.isEqualTo(FraudSignal.SMS_CODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(strings = {
|
||||||
|
"Здравствуйте! Это мой кот, на ошейнике бирка с именем Барсик",
|
||||||
|
"Могу подъехать завтра к метро в 18:00",
|
||||||
|
"Мой номер +7 999 123-45-67",
|
||||||
|
"Трек-номер посылки 1234567890123",
|
||||||
|
"Спасибо огромное, что нашли!"})
|
||||||
|
void ordinaryMessagesAreClean(String text) {
|
||||||
|
assertThat(FraudSignals.detect(text)).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void luhnRejectsRandomLongNumbers() {
|
||||||
|
assertThat(FraudSignals.luhnValid("4276380012345679")).isTrue();
|
||||||
|
assertThat(FraudSignals.luhnValid("4276380012345678")).isFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,9 +14,12 @@ import static org.mockito.Mockito.when;
|
|||||||
|
|
||||||
import com.krylov.refound.entity.Post;
|
import com.krylov.refound.entity.Post;
|
||||||
import com.krylov.refound.entity.User;
|
import com.krylov.refound.entity.User;
|
||||||
|
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||||
import com.krylov.refound.enums.PostStatus;
|
import com.krylov.refound.enums.PostStatus;
|
||||||
|
import com.krylov.refound.enums.PostType;
|
||||||
import com.krylov.refound.exception.ApiException;
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||||
|
import com.krylov.refound.repository.ChatRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -47,13 +50,15 @@ class PhoneRevealServiceTest {
|
|||||||
private StringRedisTemplate redis;
|
private StringRedisTemplate redis;
|
||||||
@Mock
|
@Mock
|
||||||
private ValueOperations<String, String> values;
|
private ValueOperations<String, String> values;
|
||||||
|
@Mock
|
||||||
|
private ChatRepository chatRepository;
|
||||||
|
|
||||||
private final PhoneRevealProperties properties = new PhoneRevealProperties();
|
private final PhoneRevealProperties properties = new PhoneRevealProperties();
|
||||||
private PhoneRevealService service;
|
private PhoneRevealService service;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
service = new PhoneRevealService(postRepository, proofOfWork, rateLimiter, redis, properties);
|
service = new PhoneRevealService(postRepository, proofOfWork, rateLimiter, redis, properties, chatRepository);
|
||||||
lenient().when(redis.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(-2L);
|
lenient().when(redis.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(-2L);
|
||||||
lenient().when(redis.opsForValue()).thenReturn(values);
|
lenient().when(redis.opsForValue()).thenReturn(values);
|
||||||
lenient().when(rateLimiter.hit(anyString(), anyString(), anyInt(), any())).thenReturn(ALLOWED);
|
lenient().when(rateLimiter.hit(anyString(), anyString(), anyInt(), any())).thenReturn(ALLOWED);
|
||||||
@@ -76,7 +81,7 @@ class PhoneRevealServiceTest {
|
|||||||
ProofOfWorkService.Challenge challenge = new ProofOfWorkService.Challenge("SHA-256", "c", "s", 400_000, "sig");
|
ProofOfWorkService.Challenge challenge = new ProofOfWorkService.Challenge("SHA-256", "c", "s", 400_000, "sig");
|
||||||
when(proofOfWork.create(1L, 400_000L)).thenReturn(challenge);
|
when(proofOfWork.create(1L, 400_000L)).thenReturn(challenge);
|
||||||
|
|
||||||
assertThat(service.challenge(1L, IP)).isSameAs(challenge);
|
assertThat(service.challenge(1L, IP, null)).isSameAs(challenge);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -101,6 +106,50 @@ class PhoneRevealServiceTest {
|
|||||||
verify(rateLimiter, never()).hit(anyString(), anyString(), anyInt(), any());
|
verify(rateLimiter, never()).hit(anyString(), anyString(), anyInt(), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Post foundWithQuestions() {
|
||||||
|
Post post = post(PostStatus.ACTIVE, true, "+79991112233");
|
||||||
|
post.setType(PostType.FOUND);
|
||||||
|
post.setVerificationQuestions(new java.util.ArrayList<>(List.of("Что на брелке?")));
|
||||||
|
User author = new User();
|
||||||
|
author.setId(9L);
|
||||||
|
post.setUser(author);
|
||||||
|
return post;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void foundWithQuestionsHidesPhoneUntilAnswersApproved() {
|
||||||
|
when(postRepository.findById(1L)).thenReturn(Optional.of(foundWithQuestions()));
|
||||||
|
when(chatRepository.existsByClaimantIdAndPostIdAndVerificationStatus(5L, 1L, ChatVerificationStatus.APPROVED))
|
||||||
|
.thenReturn(false);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.challenge(1L, IP, 5L))
|
||||||
|
.isInstanceOfSatisfying(ApiException.class,
|
||||||
|
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||||
|
assertThatThrownBy(() -> service.challenge(1L, IP, null)).isInstanceOf(ApiException.class);
|
||||||
|
// Кнопку видят все — это не перебор, IP не штрафуем
|
||||||
|
verify(rateLimiter, never()).hit(eq(PhoneRevealService.RULE_STRIKE), anyString(), anyInt(), any());
|
||||||
|
verify(proofOfWork, never()).create(anyLong(), anyLong());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void approvedClaimantSeesPhoneOfFoundWithQuestions() {
|
||||||
|
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
|
||||||
|
when(postRepository.findById(1L)).thenReturn(Optional.of(foundWithQuestions()));
|
||||||
|
when(chatRepository.existsByClaimantIdAndPostIdAndVerificationStatus(5L, 1L, ChatVerificationStatus.APPROVED))
|
||||||
|
.thenReturn(true);
|
||||||
|
|
||||||
|
assertThat(service.reveal(1L, "s", 5L, "sig", IP, 5L)).isEqualTo("+79991112233");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ownerOfFoundWithQuestionsSeesOwnPhone() {
|
||||||
|
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
|
||||||
|
when(postRepository.findById(1L)).thenReturn(Optional.of(foundWithQuestions()));
|
||||||
|
|
||||||
|
assertThat(service.reveal(1L, "s", 5L, "sig", IP, 9L)).isEqualTo("+79991112233");
|
||||||
|
verify(chatRepository, never()).existsByClaimantIdAndPostIdAndVerificationStatus(any(), any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void solutionForAnotherPostIsRejectedAsStrike() {
|
void solutionForAnotherPostIsRejectedAsStrike() {
|
||||||
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(2L));
|
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(2L));
|
||||||
@@ -116,7 +165,7 @@ class PhoneRevealServiceTest {
|
|||||||
void postWithoutConsentIsNotFoundAndCountsAsStrike() {
|
void postWithoutConsentIsNotFoundAndCountsAsStrike() {
|
||||||
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, false, null)));
|
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, false, null)));
|
||||||
|
|
||||||
assertThatThrownBy(() -> service.challenge(1L, IP))
|
assertThatThrownBy(() -> service.challenge(1L, IP, null))
|
||||||
.isInstanceOf(ApiException.class)
|
.isInstanceOf(ApiException.class)
|
||||||
.extracting(e -> ((ApiException) e).getStatus()).isEqualTo(HttpStatus.NOT_FOUND);
|
.extracting(e -> ((ApiException) e).getStatus()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||||
verify(rateLimiter).hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any());
|
verify(rateLimiter).hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any());
|
||||||
@@ -126,7 +175,7 @@ class PhoneRevealServiceTest {
|
|||||||
void closedPostDoesNotShowPhone() {
|
void closedPostDoesNotShowPhone() {
|
||||||
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.CLOSED, true, "+79991112233")));
|
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.CLOSED, true, "+79991112233")));
|
||||||
|
|
||||||
assertThatThrownBy(() -> service.challenge(1L, IP)).isInstanceOf(ApiException.class);
|
assertThatThrownBy(() -> service.challenge(1L, IP, null)).isInstanceOf(ApiException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -135,7 +184,7 @@ class PhoneRevealServiceTest {
|
|||||||
when(rateLimiter.hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any()))
|
when(rateLimiter.hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any()))
|
||||||
.thenReturn(new RedisRateLimiter.Decision(false, properties.getStrikeLimit(), 60));
|
.thenReturn(new RedisRateLimiter.Decision(false, properties.getStrikeLimit(), 60));
|
||||||
|
|
||||||
assertThatThrownBy(() -> service.challenge(99L, IP)).isInstanceOf(ApiException.class);
|
assertThatThrownBy(() -> service.challenge(99L, IP, null)).isInstanceOf(ApiException.class);
|
||||||
verify(values).set(eq("phone-ban:" + IP), eq("1"), eq(properties.getBanDuration()));
|
verify(values).set(eq("phone-ban:" + IP), eq("1"), eq(properties.getBanDuration()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +192,7 @@ class PhoneRevealServiceTest {
|
|||||||
void trapPostBansImmediately() {
|
void trapPostBansImmediately() {
|
||||||
properties.setTrapPostIds(List.of(777L));
|
properties.setTrapPostIds(List.of(777L));
|
||||||
|
|
||||||
assertThatThrownBy(() -> service.challenge(777L, IP)).isInstanceOf(ApiException.class);
|
assertThatThrownBy(() -> service.challenge(777L, IP, null)).isInstanceOf(ApiException.class);
|
||||||
verify(values).set(eq("phone-ban:" + IP), eq("1"), any(Duration.class));
|
verify(values).set(eq("phone-ban:" + IP), eq("1"), any(Duration.class));
|
||||||
verify(postRepository, never()).findById(anyLong());
|
verify(postRepository, never()).findById(anyLong());
|
||||||
}
|
}
|
||||||
@@ -152,7 +201,7 @@ class PhoneRevealServiceTest {
|
|||||||
void bannedIpGets429WithRetryAfter() {
|
void bannedIpGets429WithRetryAfter() {
|
||||||
when(redis.getExpire("phone-ban:" + IP, TimeUnit.SECONDS)).thenReturn(3600L);
|
when(redis.getExpire("phone-ban:" + IP, TimeUnit.SECONDS)).thenReturn(3600L);
|
||||||
|
|
||||||
assertThatThrownBy(() -> service.challenge(1L, IP))
|
assertThatThrownBy(() -> service.challenge(1L, IP, null))
|
||||||
.isInstanceOfSatisfying(ApiException.class, e -> {
|
.isInstanceOfSatisfying(ApiException.class, e -> {
|
||||||
assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
|
assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
|
||||||
assertThat(e.getRetryAfterSeconds()).isEqualTo(3600L);
|
assertThat(e.getRetryAfterSeconds()).isEqualTo(3600L);
|
||||||
|
|||||||
Reference in New Issue
Block a user