Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ public enum Action {
/** 코스 응답은 한 판에 한두 번 보내고, 학교 공용 와이파이처럼 한 주소에 여럿이 있을 수 있어 넉넉하게 시간당 60건. */
D1_COURSE_RESPONSE(60, 3_600_000L),
/** 한 판에 시작과 끝 두 번만 보내지만 학교 공용 와이파이를 감안해 시간당 120건. */
EXAM_CAREER_RUN(120, 3_600_000L);
EXAM_CAREER_RUN(120, 3_600_000L),
/** 수능 여론 투표. 한 사람이 하루 열 개 안팎을 고르지만 학교·학원 공용 와이파이를 감안해 시간당 300건. */
POLL_VOTE(300, 3_600_000L);

final int limit;
final long windowMs;
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/com/likelion/chak/controller/AdminController.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public class AdminController {
private final AdminAccessService adminAccessService;
private final com.likelion.chak.service.PromotionInquiryService promotionInquiryService;
private final com.likelion.chak.service.BenefitSubmissionService benefitSubmissionService;
private final com.likelion.chak.service.PollService pollService;

@GetMapping("/ads")
public ResponseEntity<List<AdvertisementResponse>> getAdvertisements(
Expand Down Expand Up @@ -215,6 +216,30 @@ public ResponseEntity<AdminAccessResponse> cancelAdminInvite(
return ResponseEntity.ok(adminAccessService.cancelInvite(principal.userId(), inviteId));
}

@GetMapping("/polls")
public ResponseEntity<List<com.likelion.chak.dto.PollDtos.AdminPollSummary>> getPolls(
@AuthenticationPrincipal AuthenticatedUser principal) {
authService.getAdmin(principal.userId());
return ResponseEntity.ok(pollService.adminList(Instant.now()));
}

@PostMapping("/polls")
public ResponseEntity<com.likelion.chak.dto.PollDtos.AdminPollSummary> createPoll(
@AuthenticationPrincipal AuthenticatedUser principal,
@Valid @RequestBody com.likelion.chak.dto.PollDtos.AdminPollRequest request) {
authService.getAdmin(principal.userId());
return ResponseEntity.status(HttpStatus.CREATED).body(pollService.create(request, Instant.now()));
}

@PatchMapping("/polls/{pollId}")
public ResponseEntity<com.likelion.chak.dto.PollDtos.AdminPollSummary> updatePoll(
@AuthenticationPrincipal AuthenticatedUser principal,
@PathVariable Long pollId,
@RequestBody com.likelion.chak.dto.PollDtos.AdminPollUpdate request) {
authService.getAdmin(principal.userId());
return ResponseEntity.ok(pollService.update(pollId, request, Instant.now()));
}

@GetMapping("/promotion-inquiries")
public ResponseEntity<SliceResponse<com.likelion.chak.dto.PromotionDtos.InquiryResponse>> getPromotionInquiries(
@AuthenticationPrincipal AuthenticatedUser principal,
Expand Down
120 changes: 120 additions & 0 deletions src/main/java/com/likelion/chak/controller/PublicPollController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package com.likelion.chak.controller;

import com.likelion.chak.alert.MinigameRateLimiter;
import com.likelion.chak.alert.MinigameRateLimiter.Action;
import com.likelion.chak.config.AuthenticatedUser;
import com.likelion.chak.dto.GuestSession;
import com.likelion.chak.dto.PollDtos.PollList;
import com.likelion.chak.dto.PollDtos.PollView;
import com.likelion.chak.dto.PollDtos.VoteRequest;
import com.likelion.chak.exception.CustomException;
import com.likelion.chak.exception.ErrorCode;
import com.likelion.chak.repository.GuestIdentityRepository;
import com.likelion.chak.service.AnalyticsService;
import com.likelion.chak.service.GuestIdentityService;
import com.likelion.chak.service.PollService;
import com.likelion.chak.service.RegionNames;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.CookieValue;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.Instant;

/** 수능 여론 투표. 로그인 없이 쓰고, 회원이면 회원 번호로, 아니면 손님 쿠키로 한 사람을 구분한다. */
@RestController
@RequestMapping("/api/public/polls")
@RequiredArgsConstructor
public class PublicPollController {

private final PollService pollService;
private final GuestIdentityService guestIdentityService;
private final GuestIdentityRepository guestIdentityRepository;
private final MinigameRateLimiter rateLimiter;

@Value("${chak.guest-cookie.name}")
private String guestCookieName;

@Value("${chak.guest-cookie.max-age-seconds}")
private long guestCookieMaxAgeSeconds;

@Value("${chak.guest-cookie.secure}")
private boolean guestCookieSecure;

@Value("${chak.guest-cookie.same-site:Lax}")
private String guestCookieSameSite;

@GetMapping
public ResponseEntity<PollList> list(
@AuthenticationPrincipal AuthenticatedUser principal,
@CookieValue(name = "${chak.guest-cookie.name}", required = false) String guestKey) {
String voterKey;
if (principal != null) {
voterKey = "u:" + principal.userId();
} else if (guestKey != null && !guestKey.isBlank()) {
// 목록을 볼 때는 손님을 새로 만들지 않는다. 이미 있는 손님이면 고른 답을 같이 보여 준다.
voterKey = guestIdentityRepository.findByGuestKey(guestKey).map(g -> "g:" + g.getId()).orElse(null);
} else {
voterKey = null;
}
return ResponseEntity.ok(pollService.list(voterKey, Instant.now()));
}

@PostMapping("/{pollId}/votes")
public ResponseEntity<PollView> vote(
@PathVariable long pollId,
@AuthenticationPrincipal AuthenticatedUser principal,
@CookieValue(name = "${chak.guest-cookie.name}", required = false) String guestKey,
@RequestHeader(name = "X-Chak-Geo-Country", required = false) String chakCountry,
@RequestHeader(name = "X-Chak-Geo-Region", required = false) String chakRegion,
@RequestHeader(name = "X-Vercel-IP-Country", required = false) String vercelCountry,
@RequestHeader(name = "X-Vercel-IP-Country-Region", required = false) String vercelRegion,
@Valid @RequestBody VoteRequest request,
HttpServletRequest http) {
String ip = ClientIp.of(http);
if (!rateLimiter.tryAcquire(Action.POLL_VOTE, "ip" + ip)) {
throw new CustomException(ErrorCode.TOO_MANY_VOTES);
}
GuestSession guest = null;
String voterKey;
if (principal != null) {
voterKey = "u:" + principal.userId();
} else {
guest = guestIdentityService.resolveOrCreateLimited(guestKey, ip);
voterKey = "g:" + guest.getGuestIdentity().getId();
}
AnalyticsService.Geo geo = AnalyticsService.Geo.fromHeaders(
firstNonBlank(chakCountry, vercelCountry), firstNonBlank(chakRegion, vercelRegion));
if (geo == null) {
geo = AnalyticsService.Geo.fromHeaders(request.geoCountry(), request.geoRegion());
}
String region = geo == null || !"KR".equals(geo.country()) || geo.region() == null
? null : RegionNames.of(geo.country(), geo.region());
PollView view = pollService.vote(pollId, request.optionId(), voterKey, region, Instant.now());

ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
if (guest != null && guest.isCreated()) {
builder.header(HttpHeaders.SET_COOKIE, ResponseCookie.from(guestCookieName, guest.getGuestIdentity().getGuestKey())
.httpOnly(true).secure(guestCookieSecure).sameSite(guestCookieSameSite).path("/")
.maxAge(Duration.ofSeconds(guestCookieMaxAgeSeconds)).build().toString());
}
return builder.body(view);
}

private static String firstNonBlank(String preferred, String fallback) {
return preferred != null && !preferred.isBlank() ? preferred : fallback;
}
}
45 changes: 45 additions & 0 deletions src/main/java/com/likelion/chak/domain/Poll.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.likelion.chak.domain;

import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.Instant;

/** 수능 여론 질문 하나. 읽고 쓰는 일은 {@code PollService}가 SQL로 하고, 이 클래스는 표 모양을 정한다. */
@Getter
@Entity
@Table(name = "polls", indexes = @Index(name = "idx_polls_opens", columnList = "opens_at"),
uniqueConstraints = @UniqueConstraint(name = "uk_polls_slug", columnNames = "slug"))
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Poll {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, length = 60)
private String slug;

@Column(nullable = false, length = 30)
private String tag;

@Column(nullable = false, length = 120)
private String question;

@Column(name = "opens_at", nullable = false)
private Instant opensAt;

@Column(name = "closes_at")
private Instant closesAt;

@Column(name = "sort_order", nullable = false)
private int sortOrder;

@Column(nullable = false)
private boolean hidden;

@Column(name = "created_at", nullable = false)
private Instant createdAt;
}
28 changes: 28 additions & 0 deletions src/main/java/com/likelion/chak/domain/PollOption.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.likelion.chak.domain;

import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

/** 질문 하나의 선택지. */
@Getter
@Entity
@Table(name = "poll_options", indexes = @Index(name = "idx_poll_options_poll", columnList = "poll_id"))
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class PollOption {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "poll_id", nullable = false)
private Poll poll;

@Column(nullable = false, length = 40)
private String label;

@Column(name = "sort_order", nullable = false)
private int sortOrder;
}
39 changes: 39 additions & 0 deletions src/main/java/com/likelion/chak/domain/PollVote.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.likelion.chak.domain;

import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.Instant;

/** 한 사람의 한 표. voter_key는 'u:회원번호' 또는 'g:손님번호'이고, IP는 저장하지 않는다. */
@Getter
@Entity
@Table(name = "poll_votes",
indexes = @Index(name = "idx_poll_votes_poll_option", columnList = "poll_id, option_id"),
uniqueConstraints = @UniqueConstraint(name = "uk_poll_votes_voter", columnNames = {"poll_id", "voter_key"}))
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class PollVote {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "poll_id", nullable = false)
private Poll poll;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "option_id", nullable = false)
private PollOption option;

@Column(name = "voter_key", nullable = false, length = 40)
private String voterKey;

@Column(length = 20)
private String region;

@Column(name = "created_at", nullable = false)
private Instant createdAt;
}
78 changes: 78 additions & 0 deletions src/main/java/com/likelion/chak/dto/PollDtos.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.likelion.chak.dto;

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

import java.time.Instant;
import java.util.List;

public final class PollDtos {

private PollDtos() {
}

public record OptionView(long id, String label) {
}

/** 지역 하나의 결과. counts는 options와 같은 순서. */
public record RegionResult(String region, long total, List<Long> counts) {
}

/**
* 결과. 투표했거나 닫힌 질문에만 붙는다. counts는 options와 같은 순서.
* regions는 표가 일정 수 이상 모인 지역만, 많은 순서로 담는다.
*/
public record Results(long total, List<Long> counts, List<RegionResult> regions) {
}

/** status: upcoming(곧 열림), open(투표 중), closed(마감). */
public record PollView(
long id,
String slug,
String tag,
String question,
Instant opensAt,
Instant closesAt,
String status,
List<OptionView> options,
Long myOptionId,
String myRegion,
Results results) {
}

public record PollList(Instant now, List<PollView> polls) {
}

public record VoteRequest(
@NotNull Long optionId,
@Size(max = 8) String geoCountry,
@Size(max = 40) String geoRegion) {
}

public record AdminPollRequest(
@NotNull @Size(min = 1, max = 60) String slug,
@NotNull @Size(min = 1, max = 30) String tag,
@NotNull @Size(min = 1, max = 120) String question,
@NotNull @Size(min = 2, max = 6) List<@NotNull @Size(min = 1, max = 40) String> options,
@NotNull Instant opensAt,
Instant closesAt,
Integer sortOrder) {
}

public record AdminPollUpdate(Boolean hidden, Instant opensAt, Instant closesAt, Boolean clearClosesAt) {
}

public record AdminPollSummary(
long id,
String slug,
String tag,
String question,
Instant opensAt,
Instant closesAt,
int sortOrder,
boolean hidden,
String status,
List<OptionView> options,
Results results) {
}
}
5 changes: 5 additions & 0 deletions src/main/java/com/likelion/chak/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ public enum ErrorCode {
INVALID_MINIGAME_ANSWERS(HttpStatus.BAD_REQUEST, "INVALID_MINIGAME_ANSWERS", "제출한 답이 올바르지 않습니다."),
INVALID_MINIGAME_RESULT(HttpStatus.BAD_REQUEST, "INVALID_MINIGAME_RESULT", "게임 결과가 올바르지 않습니다."),
INVALID_D1_COURSE_RESPONSE(HttpStatus.BAD_REQUEST, "INVALID_D1_COURSE_RESPONSE", "코스 응답 형식이 올바르지 않습니다."),
POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POLL_NOT_FOUND", "투표를 찾을 수 없습니다."),
POLL_NOT_OPEN(HttpStatus.CONFLICT, "POLL_NOT_OPEN", "지금은 투표할 수 없는 질문이에요."),
INVALID_POLL_OPTION(HttpStatus.BAD_REQUEST, "INVALID_POLL_OPTION", "선택지가 올바르지 않습니다."),
INVALID_POLL(HttpStatus.BAD_REQUEST, "INVALID_POLL", "질문은 1~120자, 선택지는 2~6개(각 1~40자), 여는 시각이 닫는 시각보다 앞서야 합니다."),
TOO_MANY_VOTES(HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY_VOTES", "투표가 너무 많아요. 잠시 후 다시 시도해주세요."),
INVALID_EXAM_CAREER_RUN(HttpStatus.BAD_REQUEST, "INVALID_EXAM_CAREER_RUN", "커리어 기록 형식이 올바르지 않습니다."),
INVALID_DISPLAY_NAME(HttpStatus.BAD_REQUEST, "INVALID_DISPLAY_NAME", "이름은 한글·영문·숫자·공백·마침표·밑줄·하이픈·괄호로 1~20자여야 합니다."),
INVALID_AVATAR(HttpStatus.BAD_REQUEST, "INVALID_AVATAR", "프로필 사진을 처리할 수 없습니다. JPEG·PNG·WebP 150KB 이하 사진을 올려주세요."),
Expand Down
Loading
Loading