62 lines
2.6 KiB
Java
62 lines
2.6 KiB
Java
package com.krylov.refound.controller;
|
||
|
||
import com.krylov.refound.dto.PhoneRevealRequest;
|
||
import com.krylov.refound.dto.PhoneRevealResponse;
|
||
import com.krylov.refound.entity.User;
|
||
import com.krylov.refound.exception.ApiException;
|
||
import com.krylov.refound.service.UserService;
|
||
import com.krylov.refound.service.phone.PhoneRevealService;
|
||
import com.krylov.refound.service.phone.ProofOfWorkService;
|
||
import jakarta.servlet.http.HttpServletRequest;
|
||
import lombok.RequiredArgsConstructor;
|
||
import org.springframework.http.CacheControl;
|
||
import org.springframework.http.ResponseEntity;
|
||
import org.springframework.web.bind.annotation.GetMapping;
|
||
import org.springframework.web.bind.annotation.PathVariable;
|
||
import org.springframework.web.bind.annotation.PostMapping;
|
||
import org.springframework.web.bind.annotation.RequestBody;
|
||
import org.springframework.web.bind.annotation.RequestMapping;
|
||
import org.springframework.web.bind.annotation.RestController;
|
||
|
||
/**
|
||
* Показ номера автора: сначала задача proof-of-work, затем номер в обмен на
|
||
* решение. Оба эндпоинта публичные — позвонить можно без регистрации.
|
||
* IP — {@code request.getRemoteAddr()}, за прокси восстанавливается из
|
||
* X-Forwarded-For (server.forward-headers-strategy).
|
||
*/
|
||
@RestController
|
||
@RequestMapping("/api/v1/posts/{id:\\d+}/phone")
|
||
@RequiredArgsConstructor
|
||
public class PhoneRevealController {
|
||
|
||
private final PhoneRevealService phoneRevealService;
|
||
private final UserService userService;
|
||
|
||
@GetMapping("/challenge")
|
||
public ResponseEntity<ProofOfWorkService.Challenge> challenge(@PathVariable Long id, HttpServletRequest request) {
|
||
return ResponseEntity.ok()
|
||
.cacheControl(CacheControl.noStore())
|
||
.body(phoneRevealService.challenge(id, request.getRemoteAddr()));
|
||
}
|
||
|
||
@PostMapping
|
||
public ResponseEntity<PhoneRevealResponse> reveal(@PathVariable Long id, @RequestBody PhoneRevealRequest body,
|
||
HttpServletRequest request) {
|
||
String phone = phoneRevealService.reveal(id, body.salt(), body.number(), body.signature(),
|
||
request.getRemoteAddr(), currentUserId());
|
||
return ResponseEntity.ok()
|
||
.cacheControl(CacheControl.noStore())
|
||
.body(new PhoneRevealResponse(phone));
|
||
}
|
||
|
||
/** id пользователя с токеном или null для анонимного запроса. */
|
||
private Long currentUserId() {
|
||
try {
|
||
User user = userService.getCurrentUser();
|
||
return user == null ? null : user.getId();
|
||
} catch (ApiException e) {
|
||
return null;
|
||
}
|
||
}
|
||
}
|