mirror of
https://github.com/headporter81/specialsource-homepage-backend.git
synced 2026-12-06 07:41:09 +09:00
feat : 방명록(손님 쓰기·회원 삭제, IP당 30초 제한), 대화실(폴링, 메모리 200줄, 접속자 목록)
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 54s
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 54s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6e27519ff6
commit
926d78c094
8 files changed
+309
-1
No files matched your search
@@ -0,0 +1,36 @@
|
||||
package company.specialsource.config;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** 로그인 없이 쓰는 방명록·대화실용: 접속자 IP 구하기 + 너무 자주 쓰기 막기 */
|
||||
public final class ClientGuard {
|
||||
|
||||
private static final Map<String, Instant> LAST = new ConcurrentHashMap<>();
|
||||
|
||||
private ClientGuard() {}
|
||||
|
||||
/** 실제 접속자 IP: 클라우드플레어가 넣어 주는 CF-Connecting-IP → 없으면 X-Forwarded-For 첫 값 → 직접 접속 주소 */
|
||||
public static String ip(HttpServletRequest request) {
|
||||
String ip = request.getHeader("CF-Connecting-IP");
|
||||
if (ip == null || ip.isBlank()) ip = request.getHeader("X-Forwarded-For");
|
||||
if (ip == null || ip.isBlank()) return request.getRemoteAddr();
|
||||
return ip.split(",")[0].trim();
|
||||
}
|
||||
|
||||
/** 같은 key(예: "guestbook:IP")로 gap 안에 다시 오면 true. 아니면 지금 시각을 기록하고 false */
|
||||
// ponytail: 메모리 Map이라 재시작하면 초기화되고 계속 쌓임 (키 = 접속 IP 수만큼이라 작음). 커지면 오래된 키 정리 추가
|
||||
public static boolean tooSoon(String key, Duration gap) {
|
||||
Instant now = Instant.now();
|
||||
Instant prev = LAST.put(key, now);
|
||||
if (prev != null && prev.plus(gap).isAfter(now)) {
|
||||
LAST.put(key, prev); // 막힌 시도는 기록하지 않음 → 기다리면 풀림
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package company.specialsource.config;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
@@ -35,6 +36,10 @@ public class SecurityConfig {
|
||||
.requestMatchers("/api/login", "/api/sync/upload", "/api/headlines").permitAll()
|
||||
// 미디어 파일은 주소의 ?t= 토큰으로, 봇 콜백은 X-Api-Key로 컨트롤러에서 직접 검사
|
||||
.requestMatchers("/api/media-posts/files/**", "/api/media-posts/callback").permitAll()
|
||||
// 방명록 읽기·쓰기, 대화실은 손님도 (방명록 삭제는 아래 anyRequest → 로그인 필요)
|
||||
.requestMatchers(HttpMethod.GET, "/api/guestbook").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/guestbook").permitAll()
|
||||
.requestMatchers("/api/chat").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
@@ -15,6 +15,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(visitorInterceptor)
|
||||
// .addPathPatterns("/api/**") // 🟢 모든 API 주소로 들어오는 길목을 차단하여 감시
|
||||
.excludePathPatterns("/api/analytics/**", "/api/media-posts/files/**", "/static/**", "/favicon.ico"); // 통계 조회 API 자체는 중복 카운팅 차단
|
||||
.excludePathPatterns("/api/analytics/**", "/api/chat", // 대화실은 2초마다 물어봐서 방문 기록에서 뺌
|
||||
"/api/media-posts/files/**", "/static/**", "/favicon.ico"); // 통계 조회 API 자체는 중복 카운팅 차단
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package company.specialsource.controller;
|
||||
|
||||
import company.specialsource.config.ClientGuard;
|
||||
import company.specialsource.repository.UserRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 대화실: 브라우저가 2초마다 "after(마지막으로 받은 번호) 뒤의 새 말"을 물어보는 방식 (폴링).
|
||||
* 대화는 DB에 저장하지 않고 메모리에 최근 200줄만 → 서버가 꺼지면(매일 밤) 지워짐.
|
||||
* 접속자 = 최근 10초 안에 물어본 브라우저(client = 브라우저가 만든 임의 값).
|
||||
*/
|
||||
// ponytail: 폴링 방식. 접속자가 많아져 요청이 부담되면 WebSocket으로 바꾸기
|
||||
@RestController
|
||||
@RequestMapping("/api/chat")
|
||||
@RequiredArgsConstructor
|
||||
public class ChatController {
|
||||
|
||||
private static final int KEEP = 200;
|
||||
private static final Duration ONLINE = Duration.ofSeconds(10);
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public record ChatMessage(long id, String nickname, String message, boolean member, LocalDateTime at) {}
|
||||
|
||||
public record ChatRequest(String nickname, String message) {}
|
||||
|
||||
public record ChatResponse(List<ChatMessage> messages, List<String> online) {}
|
||||
|
||||
private record Seen(String nickname, Instant at) {}
|
||||
|
||||
private final Deque<ChatMessage> messages = new ArrayDeque<>();
|
||||
private final Map<String, Seen> clients = new ConcurrentHashMap<>();
|
||||
private long lastId = 0;
|
||||
|
||||
// after 없으면 최근 50줄. client·nick: 접속자 목록용
|
||||
@GetMapping
|
||||
public ChatResponse poll(@RequestParam(required = false) Long after, @RequestParam(required = false) String client,
|
||||
@RequestParam(required = false) String nick, Principal principal) {
|
||||
Instant now = Instant.now();
|
||||
if (client != null && client.length() <= 64) {
|
||||
String name = principal != null ? principal.getName() : clean(nick, 20);
|
||||
clients.put(client, new Seen(name.isEmpty() ? "손님" : name, now));
|
||||
}
|
||||
clients.values().removeIf(s -> s.at().plus(ONLINE).isBefore(now));
|
||||
List<String> online = clients.values().stream().map(Seen::nickname).distinct().sorted().toList();
|
||||
|
||||
synchronized (messages) {
|
||||
List<ChatMessage> out = after == null
|
||||
? messages.stream().skip(Math.max(0, messages.size() - 50)).toList()
|
||||
: messages.stream().filter(m -> m.id() > after).toList();
|
||||
return new ChatResponse(out, online);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> say(@RequestBody ChatRequest req, Principal principal, HttpServletRequest http) {
|
||||
String message = clean(req.message(), 200);
|
||||
if (message.isEmpty()) return bad("할 말을 1~200자로 써 주세요.");
|
||||
String nickname = principal != null ? principal.getName() : clean(req.nickname(), 20);
|
||||
if (nickname.isEmpty()) return bad("닉네임을 먼저 정해 주세요.");
|
||||
if (principal == null && userRepository.findByUsername(nickname).isPresent()) {
|
||||
return bad("회원 아이디와 같은 닉네임은 쓸 수 없어요.");
|
||||
}
|
||||
if (ClientGuard.tooSoon("chat:" + ClientGuard.ip(http), Duration.ofSeconds(1))) {
|
||||
return ResponseEntity.status(429).body(Map.of("error", "너무 빨라요. 1초에 한 번만 말할 수 있어요."));
|
||||
}
|
||||
synchronized (messages) {
|
||||
messages.addLast(new ChatMessage(++lastId, nickname, message, principal != null, LocalDateTime.now()));
|
||||
while (messages.size() > KEEP) messages.removeFirst();
|
||||
}
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** 앞뒤 공백 제거, 너무 길면 자름 (null이면 빈 문자열) */
|
||||
private static String clean(String s, int max) {
|
||||
if (s == null) return "";
|
||||
s = s.strip();
|
||||
return s.length() > max ? s.substring(0, max) : s;
|
||||
}
|
||||
|
||||
private static ResponseEntity<?> bad(String message) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package company.specialsource.controller;
|
||||
|
||||
import company.specialsource.config.ClientGuard;
|
||||
import company.specialsource.entity.GuestbookEntry;
|
||||
import company.specialsource.repository.GuestbookRepository;
|
||||
import company.specialsource.repository.UserRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 방명록: 누구나 읽고 쓰기 (로그인 안 했으면 닉네임 입력), 삭제는 로그인한 회원(시삽)만.
|
||||
* 같은 IP는 30초에 한 번만 쓸 수 있음.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/guestbook")
|
||||
@RequiredArgsConstructor
|
||||
public class GuestbookController {
|
||||
|
||||
private static final int PAGE = 30;
|
||||
|
||||
private final GuestbookRepository repository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public record EntryRequest(String nickname, String message) {}
|
||||
|
||||
public record EntryResponse(long id, String nickname, String message, boolean member, LocalDateTime createdAt) {
|
||||
static EntryResponse of(GuestbookEntry e) {
|
||||
return new EntryResponse(e.getId(), e.getNickname(), e.getMessage(), e.isMember(), e.getCreatedAt());
|
||||
}
|
||||
}
|
||||
|
||||
// 최신 글부터 30개. before = 이미 받은 마지막 글 id → 그보다 오래된 글 (더 보기)
|
||||
@GetMapping
|
||||
public List<EntryResponse> list(@RequestParam(required = false) Long before) {
|
||||
var page = PageRequest.of(0, PAGE);
|
||||
var rows = before == null ? repository.findByOrderByIdDesc(page) : repository.findByIdLessThanOrderByIdDesc(before, page);
|
||||
return rows.stream().map(EntryResponse::of).toList();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> write(@RequestBody EntryRequest req, Principal principal, HttpServletRequest http) {
|
||||
String message = req.message() == null ? "" : req.message().strip();
|
||||
if (message.isEmpty() || message.length() > 300) return bad("내용은 1~300자로 써 주세요.");
|
||||
|
||||
String nickname;
|
||||
if (principal != null) {
|
||||
nickname = principal.getName();
|
||||
} else {
|
||||
nickname = req.nickname() == null ? "" : req.nickname().strip();
|
||||
if (nickname.isEmpty() || nickname.length() > 20) return bad("닉네임은 1~20자로 써 주세요.");
|
||||
// 손님이 회원 아이디(시삽 등)를 사칭하지 못하게
|
||||
if (userRepository.findByUsername(nickname).isPresent()) return bad("회원 아이디와 같은 닉네임은 쓸 수 없어요.");
|
||||
}
|
||||
if (ClientGuard.tooSoon("guestbook:" + ClientGuard.ip(http), Duration.ofSeconds(30))) {
|
||||
return ResponseEntity.status(429).body(Map.of("error", "방명록은 30초에 한 번만 쓸 수 있어요."));
|
||||
}
|
||||
|
||||
GuestbookEntry saved = repository.save(GuestbookEntry.builder()
|
||||
.nickname(nickname).message(message).member(principal != null).createdAt(LocalDateTime.now()).build());
|
||||
return ResponseEntity.ok(EntryResponse.of(saved));
|
||||
}
|
||||
|
||||
// 로그인한 회원만 (SecurityConfig에서 DELETE는 인증 필요)
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable long id) {
|
||||
repository.deleteById(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private static ResponseEntity<?> bad(String message) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package company.specialsource.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 방명록 한 줄 */
|
||||
@Entity
|
||||
@Table(name = "guestbook_entries")
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class GuestbookEntry {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 20)
|
||||
private String nickname;
|
||||
|
||||
@Column(nullable = false, length = 300)
|
||||
private String message;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean member; // 로그인한 회원이 쓴 글 (닉네임 = 아이디)
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package company.specialsource.repository;
|
||||
|
||||
import company.specialsource.entity.GuestbookEntry;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface GuestbookRepository extends JpaRepository<GuestbookEntry, Long> {
|
||||
List<GuestbookEntry> findByOrderByIdDesc(Pageable pageable);
|
||||
|
||||
List<GuestbookEntry> findByIdLessThanOrderByIdDesc(long before, Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package company.specialsource.controller;
|
||||
|
||||
import company.specialsource.repository.UserRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** 대화실: 새 말만 가져오기(after), 1초 제한, 회원 아이디 사칭 막기, 접속자 목록 */
|
||||
class ChatControllerTest {
|
||||
|
||||
@Test
|
||||
void 대화_흐름() {
|
||||
UserRepository users = mock(UserRepository.class);
|
||||
when(users.findByUsername(anyString())).thenReturn(Optional.empty());
|
||||
when(users.findByUsername("sysop")).thenReturn(Optional.of(company.specialsource.entity.User.builder().username("sysop").build()));
|
||||
ChatController chat = new ChatController(users);
|
||||
|
||||
MockHttpServletRequest a = new MockHttpServletRequest();
|
||||
a.addHeader("CF-Connecting-IP", "10.0.0.1");
|
||||
MockHttpServletRequest b = new MockHttpServletRequest();
|
||||
b.addHeader("CF-Connecting-IP", "10.0.0.2");
|
||||
|
||||
assertThat(chat.say(new ChatController.ChatRequest("철수", "안녕"), null, a).getStatusCode().value()).isEqualTo(204);
|
||||
assertThat(chat.say(new ChatController.ChatRequest("철수", "또"), null, a).getStatusCode().value()).isEqualTo(429); // 1초 안에 또
|
||||
assertThat(chat.say(new ChatController.ChatRequest("sysop", "사칭"), null, b).getStatusCode().value()).isEqualTo(400);
|
||||
assertThat(chat.say(new ChatController.ChatRequest("영희", "반가워"), null, b).getStatusCode().value()).isEqualTo(204);
|
||||
|
||||
var first = chat.poll(null, "c1", "철수", null);
|
||||
assertThat(first.messages()).extracting(ChatController.ChatMessage::message).containsExactly("안녕", "반가워");
|
||||
assertThat(first.online()).containsExactly("철수");
|
||||
|
||||
long last = first.messages().get(1).id();
|
||||
assertThat(chat.poll(last, "c2", "영희", null).messages()).isEmpty(); // 이미 받은 말은 다시 안 옴
|
||||
assertThat(chat.poll(last, "c2", "영희", null).online()).containsExactly("영희", "철수");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user