Merge branch 'feats/api-status' into design

# Conflicts:
#	src/main/resources/static/css/main.css.map
#	src/main/resources/static/css/main.min.css
#	src/main/resources/static/css/main.min.css.map
#	src/main/resources/templates/views/apps/mypage/apiKeyModifyStep2.html
#	src/main/resources/templates/views/apps/mypage/apiKeyRegisterStep2.html
#	src/main/resources/templates/views/fragment/djbank/header_container.html
This commit is contained in:
Rinjae
2026-07-20 19:13:38 +09:00
38 changed files with 3587 additions and 4 deletions
@@ -0,0 +1,387 @@
package com.eactive.apim.portal.djb.webhook.controller;
import com.eactive.apim.portal.apps.apiservice.dto.ApiGroupSearch;
import com.eactive.apim.portal.apps.app.service.AppServiceFacade;
import com.eactive.apim.portal.apps.apiservice.service.ApiServiceService;
import com.eactive.apim.portal.common.user.PortalAuthenticatedUser;
import com.eactive.apim.portal.common.util.SecurityUtil;
import com.eactive.apim.portal.djb.webhook.dto.WebhookDTO;
import com.eactive.apim.portal.djb.webhook.dto.WebhookRegistrationDTO;
import com.eactive.apim.portal.djb.webhook.service.WebhookEventTypeProvider;
import com.eactive.apim.portal.djb.webhook.service.WebhookService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* Webhook 신청/관리 (기업 사용자, ROLE_APP).
*
* App API Key 신청의 3-Step + 세션 + 비밀번호 재인증 패턴을 답습하되, 승인 워크플로우 없이 즉시 발급한다.
* 참조: {@code apps/app/controller/MyAppController}.
*/
@Slf4j
@Controller
@RequestMapping("/webhook")
@Secured("ROLE_API_KEY_REQUEST")
@RequiredArgsConstructor
@SessionAttributes({"webhookRegistration", "webhookModification"})
public class WebhookController {
// 클래스 기본: 법인 관리자(ROLE_API_KEY_REQUEST)만 신청/수정/삭제/Secret 관리 가능.
// 조회(index)만 메서드 레벨에서 ROLE_APP 으로 완화(같은 기관 일반 사용자도 열람).
private static final int TOTAL_STEPS = 3;
private final WebhookService webhookService;
private final WebhookEventTypeProvider eventTypeProvider;
private final ApiServiceService apiServiceService;
private final AppServiceFacade appServiceFacade;
@ModelAttribute("webhookRegistration")
public WebhookRegistrationDTO webhookRegistration() {
return new WebhookRegistrationDTO();
}
@ModelAttribute("webhookModification")
public WebhookRegistrationDTO webhookModification() {
return new WebhookRegistrationDTO();
}
// ============================ 조회 ============================
@Secured("ROLE_APP")
@GetMapping
public ModelAndView index() {
String orgId = currentOrgId();
Optional<WebhookDTO> webhook = webhookService.getByOrg(orgId);
if (webhook.isPresent()) {
ModelAndView mav = new ModelAndView("apps/webhook/webhookList");
mav.addObject("webhook", webhook.get());
return mav;
}
return new ModelAndView("apps/webhook/webhookEmpty");
}
// ======================= 신규 신청 플로우 =======================
@GetMapping("/register/step1")
public ModelAndView registerStep1(
@RequestParam(value = "clear", required = false, defaultValue = "false") boolean clear,
@ModelAttribute("webhookRegistration") WebhookRegistrationDTO registration,
SessionStatus sessionStatus,
Model model) {
if (webhookService.existsByOrg(currentOrgId())) {
return new ModelAndView("redirect:/webhook");
}
if (clear) {
sessionStatus.setComplete();
registration = new WebhookRegistrationDTO();
model.addAttribute("webhookRegistration", registration);
}
registration.setRequestType("NEW");
ModelAndView mav = new ModelAndView("apps/webhook/webhookRegisterStep1");
mav.addObject("eventTypes", eventTypeProvider.getAll());
addStepModel(mav, 1);
return mav;
}
@PostMapping("/register/step1")
public ModelAndView processStep1(
@Valid @ModelAttribute("webhookRegistration") WebhookRegistrationDTO registration,
BindingResult bindingResult,
Model model) {
validateStep1(registration, bindingResult);
if (bindingResult.hasErrors()) {
ModelAndView mav = new ModelAndView("apps/webhook/webhookRegisterStep1");
mav.addObject("eventTypes", eventTypeProvider.getAll());
addStepModel(mav, 1);
return mav;
}
return new ModelAndView("redirect:/webhook/register/step2");
}
@GetMapping("/register/step2")
public ModelAndView registerStep2(
@ModelAttribute("webhookRegistration") WebhookRegistrationDTO registration,
RedirectAttributes redirectAttributes) {
if (!registration.isStep1Complete()) {
return new ModelAndView("redirect:/webhook/register/step1");
}
ModelAndView mav = new ModelAndView("apps/webhook/webhookRegisterStep2");
mav.addObject("apiServices", apiServiceService.searchApiGroups(new ApiGroupSearch()));
addStepModel(mav, 2);
return mav;
}
/** Step2 "이전" — 현재 선택을 세션에 저장하고 Step1 로 복귀 (App 신청 saveStep2 답습). */
@PostMapping("/register/step2/save")
public ModelAndView saveStep2(
@RequestParam(value = "selectedApis", required = false) List<String> selectedApis,
@ModelAttribute("webhookRegistration") WebhookRegistrationDTO registration) {
registration.setSelectedApis(selectedApis != null ? selectedApis : new java.util.ArrayList<>());
return new ModelAndView("redirect:/webhook/register/step1");
}
@PostMapping("/register/step2")
public ModelAndView processStep2(
@RequestParam(value = "selectedApis", required = false) List<String> selectedApis,
@ModelAttribute("webhookRegistration") WebhookRegistrationDTO registration,
SessionStatus sessionStatus,
RedirectAttributes redirectAttributes) {
registration.setSelectedApis(selectedApis);
if (!registration.isStep2Complete()) {
redirectAttributes.addFlashAttribute("error", "알림 대상 API를 1개 이상 선택해주세요.");
return new ModelAndView("redirect:/webhook/register/step2");
}
try {
// 평문 Secret 은 화면에 노출하지 않는다 — 목록에서 비밀번호 재인증 후 조회.
webhookService.create(registration, currentOrgId());
sessionStatus.setComplete();
redirectAttributes.addFlashAttribute("registrationSuccess", true);
return new ModelAndView("redirect:/webhook/register/step3");
} catch (RuntimeException e) {
log.warn("Webhook 신청 실패 orgId={} : {}", currentOrgId(), e.getMessage());
redirectAttributes.addFlashAttribute("error", e.getMessage());
return new ModelAndView("redirect:/webhook/register/step2");
}
}
@GetMapping("/register/step3")
public ModelAndView registerStep3(Model model) {
if (!Boolean.TRUE.equals(model.getAttribute("registrationSuccess"))) {
return new ModelAndView("redirect:/webhook");
}
ModelAndView mav = new ModelAndView("apps/webhook/webhookRegisterStep3");
addStepModel(mav, 3);
return mav;
}
@GetMapping("/register/cancel")
public String cancelRegistration(SessionStatus sessionStatus) {
sessionStatus.setComplete();
return "redirect:/webhook";
}
// ========================= 수정 플로우 =========================
@GetMapping("/modify/step1")
public ModelAndView modifyStep1(
@ModelAttribute("webhookModification") WebhookRegistrationDTO modification,
Model model) {
Optional<WebhookDTO> current = webhookService.getByOrg(currentOrgId());
if (!current.isPresent()) {
return new ModelAndView("redirect:/webhook/register/step1?clear=true");
}
WebhookDTO webhook = current.get();
// 세션에 아직 채워지지 않았으면 현재 등록값으로 초기화
if (modification.getId() == null || !webhook.getId().equals(modification.getId())) {
modification.setId(webhook.getId());
modification.setRequestType("MODIFY");
modification.setTargetUrl(webhook.getTargetUrl());
modification.setEventTypes(webhook.getEventTypes().stream()
.map(e -> e.getCode()).collect(java.util.stream.Collectors.toList()));
modification.setSelectedApis(new java.util.ArrayList<>(webhook.getApiIds()));
model.addAttribute("webhookModification", modification);
}
ModelAndView mav = new ModelAndView("apps/webhook/webhookModifyStep1");
mav.addObject("eventTypes", eventTypeProvider.getAll());
addStepModel(mav, 1);
return mav;
}
@PostMapping("/modify/step1")
public ModelAndView processModifyStep1(
@Valid @ModelAttribute("webhookModification") WebhookRegistrationDTO modification,
BindingResult bindingResult,
Model model) {
validateStep1(modification, bindingResult);
if (bindingResult.hasErrors()) {
ModelAndView mav = new ModelAndView("apps/webhook/webhookModifyStep1");
mav.addObject("eventTypes", eventTypeProvider.getAll());
addStepModel(mav, 1);
return mav;
}
return new ModelAndView("redirect:/webhook/modify/step2");
}
@GetMapping("/modify/step2")
public ModelAndView modifyStep2(
@ModelAttribute("webhookModification") WebhookRegistrationDTO modification) {
if (modification.getId() == null || !modification.isStep1Complete()) {
return new ModelAndView("redirect:/webhook/modify/step1");
}
ModelAndView mav = new ModelAndView("apps/webhook/webhookModifyStep2");
mav.addObject("apiServices", apiServiceService.searchApiGroups(new ApiGroupSearch()));
addStepModel(mav, 2);
return mav;
}
/** 수정 Step2 "이전" — 현재 선택을 세션에 저장하고 Step1 로 복귀. */
@PostMapping("/modify/step2/save")
public ModelAndView saveModifyStep2(
@RequestParam(value = "selectedApis", required = false) List<String> selectedApis,
@ModelAttribute("webhookModification") WebhookRegistrationDTO modification) {
modification.setSelectedApis(selectedApis != null ? selectedApis : new java.util.ArrayList<>());
return new ModelAndView("redirect:/webhook/modify/step1");
}
@PostMapping("/modify/step2")
public ModelAndView processModifyStep2(
@RequestParam(value = "selectedApis", required = false) List<String> selectedApis,
@ModelAttribute("webhookModification") WebhookRegistrationDTO modification,
SessionStatus sessionStatus,
RedirectAttributes redirectAttributes) {
modification.setSelectedApis(selectedApis);
if (modification.getId() == null || !modification.isStep2Complete()) {
redirectAttributes.addFlashAttribute("error", "알림 대상 API를 1개 이상 선택해주세요.");
return new ModelAndView("redirect:/webhook/modify/step2");
}
try {
webhookService.update(modification.getId(), modification, currentOrgId());
sessionStatus.setComplete();
redirectAttributes.addFlashAttribute("modifySuccess", true);
return new ModelAndView("redirect:/webhook/modify/step3");
} catch (RuntimeException e) {
log.warn("Webhook 수정 실패 orgId={} : {}", currentOrgId(), e.getMessage());
redirectAttributes.addFlashAttribute("error", e.getMessage());
return new ModelAndView("redirect:/webhook/modify/step2");
}
}
@GetMapping("/modify/step3")
public ModelAndView modifyStep3(Model model) {
if (!Boolean.TRUE.equals(model.getAttribute("modifySuccess"))) {
return new ModelAndView("redirect:/webhook");
}
ModelAndView mav = new ModelAndView("apps/webhook/webhookModifyStep3");
addStepModel(mav, 3);
return mav;
}
@GetMapping("/modify/cancel")
public String cancelModification(SessionStatus sessionStatus) {
sessionStatus.setComplete();
return "redirect:/webhook";
}
// ==================== AJAX (비밀번호 재인증) ====================
@PostMapping("/verify-secret")
@ResponseBody
public Map<String, Object> verifySecret(@RequestParam String password) {
Map<String, Object> result = new HashMap<>();
if (!verifyPassword(password)) {
result.put("success", false);
result.put("message", "비밀번호가 일치하지 않습니다.");
return result;
}
Optional<WebhookDTO> webhook = webhookService.getByOrg(currentOrgId());
if (!webhook.isPresent()) {
result.put("success", false);
result.put("message", "등록된 Webhook이 없습니다.");
return result;
}
result.put("success", true);
result.put("secret", webhookService.getPlainSecret(webhook.get().getId(), currentOrgId()));
return result;
}
@PostMapping("/regenerate-secret")
@ResponseBody
public Map<String, Object> regenerateSecret(@RequestParam String password) {
Map<String, Object> result = new HashMap<>();
if (!verifyPassword(password)) {
result.put("success", false);
result.put("message", "비밀번호가 일치하지 않습니다.");
return result;
}
Optional<WebhookDTO> webhook = webhookService.getByOrg(currentOrgId());
if (!webhook.isPresent()) {
result.put("success", false);
result.put("message", "등록된 Webhook이 없습니다.");
return result;
}
String secret = webhookService.regenerateSecret(webhook.get().getId(), currentOrgId());
result.put("success", true);
result.put("secret", secret);
return result;
}
@PostMapping("/delete")
@ResponseBody
public Map<String, Object> delete(@RequestParam String password) {
Map<String, Object> result = new HashMap<>();
if (!verifyPassword(password)) {
result.put("success", false);
result.put("message", "비밀번호가 일치하지 않습니다.");
return result;
}
Optional<WebhookDTO> webhook = webhookService.getByOrg(currentOrgId());
if (!webhook.isPresent()) {
result.put("success", false);
result.put("message", "등록된 Webhook이 없습니다.");
return result;
}
webhookService.delete(webhook.get().getId(), currentOrgId());
result.put("success", true);
return result;
}
// ============================ helper ============================
private void validateStep1(WebhookRegistrationDTO dto, BindingResult bindingResult) {
String url = dto.getTargetUrl() == null ? "" : dto.getTargetUrl().trim();
if (!bindingResult.hasFieldErrors("targetUrl")
&& !url.startsWith("http://") && !url.startsWith("https://")) {
bindingResult.rejectValue("targetUrl", "invalid.url",
"URL은 http:// 또는 https:// 로 시작해야 합니다.");
}
if (dto.getEventTypes() == null || dto.getEventTypes().isEmpty()) {
bindingResult.rejectValue("eventTypes", "empty.eventTypes",
"EventType을 1개 이상 선택해주세요.");
}
}
private boolean verifyPassword(String password) {
PortalAuthenticatedUser user = SecurityUtil.getPortalAuthenticatedUser();
return appServiceFacade.verifyUserPassword(user, password);
}
private String currentOrgId() {
PortalAuthenticatedUser user = SecurityUtil.getPortalAuthenticatedUser();
return user != null && user.getPortalOrg() != null ? user.getPortalOrg().getId() : null;
}
private void addStepModel(ModelAndView mav, int currentStep) {
mav.addObject("currentStep", currentStep);
mav.addObject("totalSteps", TOTAL_STEPS);
}
}
@@ -0,0 +1,15 @@
package com.eactive.apim.portal.djb.webhook.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* 신규 신청 결과. 평문 {@code secret} 은 발급 직후 1회 노출 목적으로만 전달된다.
*/
@Getter
@RequiredArgsConstructor
public class WebhookCreatedResult {
private final Long id;
private final String secret;
}
@@ -0,0 +1,26 @@
package com.eactive.apim.portal.djb.webhook.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/**
* 등록된 Webhook 상세 표시용. SECRET 은 마스킹 값만 담고 평문은 별도 재인증 조회로만 노출한다.
*/
@Data
public class WebhookDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String targetUrl;
private String secretMasked;
private String createdDate;
/** 구독 API ID 목록. */
private List<String> apiIds = new ArrayList<>();
/** 구독 EventType(코드+한글명) 목록. */
private List<WebhookEventTypeDTO> eventTypes = new ArrayList<>();
}
@@ -0,0 +1,27 @@
package com.eactive.apim.portal.djb.webhook.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* EventType 코드/한글명 쌍. TSEAIRM28(CODEGROUP='EVENT_TYPE') 에서 로드.
* {@code selected} 는 신청 화면에서 현재 구독 여부 표시용.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WebhookEventTypeDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String code;
private String name;
private boolean selected;
public WebhookEventTypeDTO(String code, String name) {
this.code = code;
this.name = name;
}
}
@@ -0,0 +1,48 @@
package com.eactive.apim.portal.djb.webhook.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
/**
* Webhook 신청/수정 스텝 간 세션 보존 데이터 (App 신청 {@code ApiKeyRegistrationDTO} 답습).
*
* Step1: {@code targetUrl} + {@code eventTypes}. Step2: {@code selectedApis}.
*/
@Data
public class WebhookRegistrationDTO implements Serializable {
private static final long serialVersionUID = 1L;
/** 수정 시 대상 신청 ID. 신규 신청이면 null. */
private Long id;
/** "NEW" 또는 "MODIFY" */
private String requestType;
@NotBlank(message = "Webhook 수신 URL을 입력해주세요.")
@Length(max = 255, message = "URL은 255자를 초과할 수 없습니다.")
private String targetUrl;
/** Step1: 구독 EventType 코드 목록 (TSEAIRM28 EVENT_TYPE). */
private List<String> eventTypes = new ArrayList<>();
/** Step2: 알림 대상 API ID 목록. */
private List<String> selectedApis = new ArrayList<>();
public boolean isStep1Complete() {
return targetUrl != null && !targetUrl.trim().isEmpty()
&& eventTypes != null && !eventTypes.isEmpty();
}
public boolean isStep2Complete() {
return selectedApis != null && !selectedApis.isEmpty();
}
public boolean isComplete() {
return isStep1Complete() && isStep2Complete();
}
}
@@ -0,0 +1,13 @@
package com.eactive.apim.portal.djb.webhook.exception;
/**
* Org 당 Webhook 1건 정책 위반(이미 등록됨).
*/
public class WebhookAlreadyExistsException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WebhookAlreadyExistsException(String orgId) {
super("이미 등록된 Webhook이 있습니다. orgId=" + orgId);
}
}
@@ -0,0 +1,13 @@
package com.eactive.apim.portal.djb.webhook.exception;
/**
* 대상 Webhook 신청을 찾을 수 없음.
*/
public class WebhookNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WebhookNotFoundException(Long id) {
super("Webhook 신청을 찾을 수 없습니다. id=" + id);
}
}
@@ -0,0 +1,19 @@
package com.eactive.apim.portal.djb.webhook.mapper;
import com.eactive.apim.portal.djb.webhook.dto.WebhookDTO;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequest;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
/**
* WebhookRequest → WebhookDTO 기본 필드 매핑.
* secretMasked/apiIds/eventTypes 는 연관 테이블 조립이 필요하므로 서비스에서 채운다.
*/
@Mapper(componentModel = "spring")
public interface WebhookMapper {
@Mapping(target = "secretMasked", ignore = true)
@Mapping(target = "apiIds", ignore = true)
@Mapping(target = "eventTypes", ignore = true)
WebhookDTO toDto(WebhookRequest entity);
}
@@ -0,0 +1,20 @@
package com.eactive.apim.portal.djb.webhook.repository;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequestApi;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequestApiId;
import com.eactive.eai.rms.data.EMSDataSource;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
/**
* PTL_WEBHOOK_REQ_API — 신청별 구독 API 목록.
*/
@EMSDataSource
public interface WebhookRequestApiRepository extends JpaRepository<WebhookRequestApi, WebhookRequestApiId> {
List<WebhookRequestApi> findByWebhookReqId(Long webhookReqId);
@Transactional
void deleteByWebhookReqId(Long webhookReqId);
}
@@ -0,0 +1,20 @@
package com.eactive.apim.portal.djb.webhook.repository;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequestEvent;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequestEventId;
import com.eactive.eai.rms.data.EMSDataSource;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
/**
* PTL_WEBHOOK_REQ_EVENT — 신청별 구독 EventType 목록.
*/
@EMSDataSource
public interface WebhookRequestEventRepository extends JpaRepository<WebhookRequestEvent, WebhookRequestEventId> {
List<WebhookRequestEvent> findByWebhookReqId(Long webhookReqId);
@Transactional
void deleteByWebhookReqId(Long webhookReqId);
}
@@ -0,0 +1,17 @@
package com.eactive.apim.portal.djb.webhook.repository;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequest;
import com.eactive.eai.rms.data.EMSDataSource;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* PTL_WEBHOOK_REQ 조회/저장. Org 당 1건 정책이라 orgId 단건 조회를 제공한다.
*/
@EMSDataSource
public interface WebhookRequestRepository extends JpaRepository<WebhookRequest, Long> {
Optional<WebhookRequest> findByOrgId(String orgId);
boolean existsByOrgId(String orgId);
}
@@ -0,0 +1,66 @@
package com.eactive.apim.portal.djb.webhook.repository.entity;
import com.eactive.apim.portal.common.util.SecurityUtil;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
/**
* Webhook 신청 마스터 (EMSAPP.PTL_WEBHOOK_REQ).
*
* admin(eapim-admin) 발송엔진이 이 행을 읽어 TARGET_URL 로 HMAC-SHA256 서명 발송한다.
* SECRET 은 서명 키로 그대로 사용되므로 암호화하지 않고 평문 저장한다.
* CREATED_DATE 는 VARCHAR2(14) yyyyMMddHHmmss 문자열이라 AbstractAuditingEntity 를 쓰지 않고
* {@link #onCreate()} 에서 직접 세팅한다.
*/
@Getter
@Setter
@Entity
@Table(name = "PTL_WEBHOOK_REQ")
public class WebhookRequest implements Serializable {
private static final long serialVersionUID = 1L;
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "webhookReqSeq")
@SequenceGenerator(name = "webhookReqSeq", sequenceName = "SEQ_PTL_WEBHOOK_REQ_ID", allocationSize = 1)
@Column(name = "ID")
private Long id;
@Column(name = "ORG_ID", length = 36)
private String orgId;
@Column(name = "TARGET_URL", length = 255)
private String targetUrl;
@Column(name = "SECRET", length = 500)
private String secret;
@Column(name = "CREATED_BY", length = 200)
private String createdBy;
@Column(name = "CREATED_DATE", length = 14)
private String createdDate;
@PrePersist
public void onCreate() {
if (createdBy == null) {
createdBy = SecurityUtil.getCurrentLoginId();
}
if (createdDate == null) {
createdDate = LocalDateTime.now().format(TS);
}
}
}
@@ -0,0 +1,62 @@
package com.eactive.apim.portal.djb.webhook.repository.entity;
import com.eactive.apim.portal.common.util.SecurityUtil;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
/**
* Webhook 신청이 알림을 받을 API 목록 (EMSAPP.PTL_WEBHOOK_REQ_API).
* 복합키(WEBHOOK_REQ_ID + API_ID).
*/
@Getter
@Setter
@Entity
@Table(name = "PTL_WEBHOOK_REQ_API")
@IdClass(WebhookRequestApiId.class)
public class WebhookRequestApi implements Serializable {
private static final long serialVersionUID = 1L;
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
@Id
@Column(name = "WEBHOOK_REQ_ID")
private Long webhookReqId;
@Id
@Column(name = "API_ID", length = 30)
private String apiId;
@Column(name = "CREATED_BY", length = 200)
private String createdBy;
@Column(name = "CREATED_DATE", length = 14)
private String createdDate;
public WebhookRequestApi() {
}
public WebhookRequestApi(Long webhookReqId, String apiId) {
this.webhookReqId = webhookReqId;
this.apiId = apiId;
}
@PrePersist
public void onCreate() {
if (createdBy == null) {
createdBy = SecurityUtil.getCurrentLoginId();
}
if (createdDate == null) {
createdDate = LocalDateTime.now().format(TS);
}
}
}
@@ -0,0 +1,24 @@
package com.eactive.apim.portal.djb.webhook.repository.entity;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* {@link WebhookRequestApi} 복합키 (WEBHOOK_REQ_ID + API_ID).
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class WebhookRequestApiId implements Serializable {
private static final long serialVersionUID = 1L;
private Long webhookReqId;
private String apiId;
}
@@ -0,0 +1,63 @@
package com.eactive.apim.portal.djb.webhook.repository.entity;
import com.eactive.apim.portal.common.util.SecurityUtil;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
/**
* Webhook 신청이 구독하는 EventType 목록 (EMSAPP.PTL_WEBHOOK_REQ_EVENT).
* EVENT_TYPE 코드값은 EMSAPP.TSEAIRM28(CODEGROUP='EVENT_TYPE') 과 동일 집합.
* 복합키(WEBHOOK_REQ_ID + EVENT_TYPE).
*/
@Getter
@Setter
@Entity
@Table(name = "PTL_WEBHOOK_REQ_EVENT")
@IdClass(WebhookRequestEventId.class)
public class WebhookRequestEvent implements Serializable {
private static final long serialVersionUID = 1L;
private static final DateTimeFormatter TS = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
@Id
@Column(name = "WEBHOOK_REQ_ID")
private Long webhookReqId;
@Id
@Column(name = "EVENT_TYPE", length = 36)
private String eventType;
@Column(name = "CREATED_BY", length = 200)
private String createdBy;
@Column(name = "CREATED_DATE", length = 14)
private String createdDate;
public WebhookRequestEvent() {
}
public WebhookRequestEvent(Long webhookReqId, String eventType) {
this.webhookReqId = webhookReqId;
this.eventType = eventType;
}
@PrePersist
public void onCreate() {
if (createdBy == null) {
createdBy = SecurityUtil.getCurrentLoginId();
}
if (createdDate == null) {
createdDate = LocalDateTime.now().format(TS);
}
}
}
@@ -0,0 +1,24 @@
package com.eactive.apim.portal.djb.webhook.repository.entity;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* {@link WebhookRequestEvent} 복합키 (WEBHOOK_REQ_ID + EVENT_TYPE).
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class WebhookRequestEventId implements Serializable {
private static final long serialVersionUID = 1L;
private Long webhookReqId;
private String eventType;
}
@@ -0,0 +1,76 @@
package com.eactive.apim.portal.djb.webhook.service;
import com.eactive.apim.portal.djb.webhook.dto.WebhookEventTypeDTO;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* EventType 코드/한글명 제공자. EMSAPP.TSEAIRM28(CODEGROUP='EVENT_TYPE', USEYN='Y') 를 조회한다.
* admin 발송엔진과 동일 공통코드 테이블을 단일 소스로 사용하므로 코드 추가/변경 시 DB 만 수정하면 된다.
*
* TSEAIRM28 은 elink-portal-common 의 {@code MonitoringCode} 엔티티가 이미 매핑하고 있어(같은 테이블 중복 @Entity 금지),
* 여기서는 별도 엔티티 없이 EMS EntityManager 네이티브 쿼리로 필요한 두 컬럼만 조회한다.
*/
@Component
public class WebhookEventTypeProvider {
private static final String EVENT_TYPE_SQL =
"SELECT CODE, CODENAME FROM TSEAIRM28 "
+ "WHERE CODEGROUP = 'EVENT_TYPE' AND USEYN = 'Y' "
+ "ORDER BY SEQ, CODE";
/** EMS 데이터소스가 @Primary 이므로 기본 EntityManager 는 EMS 를 가리킨다. */
@PersistenceContext
private EntityManager entityManager;
@Transactional(readOnly = true)
public List<WebhookEventTypeDTO> getAll() {
List<WebhookEventTypeDTO> list = new ArrayList<>();
for (Object[] row : rows()) {
list.add(new WebhookEventTypeDTO(asString(row[0]), asString(row[1])));
}
return list;
}
@Transactional(readOnly = true)
public Map<String, String> asMap() {
Map<String, String> map = new LinkedHashMap<>();
for (Object[] row : rows()) {
map.put(asString(row[0]), asString(row[1]));
}
return map;
}
@Transactional(readOnly = true)
public boolean isValid(String code) {
if (code == null) {
return false;
}
for (Object[] row : rows()) {
if (code.equals(asString(row[0]))) {
return true;
}
}
return false;
}
@Transactional(readOnly = true)
public String getName(String code) {
return asMap().getOrDefault(code, code);
}
@SuppressWarnings("unchecked")
private List<Object[]> rows() {
return entityManager.createNativeQuery(EVENT_TYPE_SQL).getResultList();
}
private String asString(Object value) {
return value == null ? null : value.toString();
}
}
@@ -0,0 +1,28 @@
package com.eactive.apim.portal.djb.webhook.service;
import java.security.SecureRandom;
import org.springframework.stereotype.Component;
/**
* Webhook HMAC Secret 생성기.
*
* admin 발송엔진이 이 값을 그대로 HMAC-SHA256 키로 사용하므로(암복호화 없음),
* 128자 영숫자 랜덤 문자열을 평문으로 발급한다(admin 기존 데이터와 동일 형태).
*/
@Component
public class WebhookSecretGenerator {
private static final char[] ALPHANUM =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
private static final int LENGTH = 128;
private final SecureRandom random = new SecureRandom();
public String generate() {
StringBuilder sb = new StringBuilder(LENGTH);
for (int i = 0; i < LENGTH; i++) {
sb.append(ALPHANUM[random.nextInt(ALPHANUM.length)]);
}
return sb.toString();
}
}
@@ -0,0 +1,189 @@
package com.eactive.apim.portal.djb.webhook.service;
import com.eactive.apim.portal.djb.webhook.dto.WebhookCreatedResult;
import com.eactive.apim.portal.djb.webhook.dto.WebhookDTO;
import com.eactive.apim.portal.djb.webhook.dto.WebhookEventTypeDTO;
import com.eactive.apim.portal.djb.webhook.dto.WebhookRegistrationDTO;
import com.eactive.apim.portal.djb.webhook.exception.WebhookAlreadyExistsException;
import com.eactive.apim.portal.djb.webhook.exception.WebhookNotFoundException;
import com.eactive.apim.portal.djb.webhook.mapper.WebhookMapper;
import com.eactive.apim.portal.djb.webhook.repository.WebhookRequestApiRepository;
import com.eactive.apim.portal.djb.webhook.repository.WebhookRequestEventRepository;
import com.eactive.apim.portal.djb.webhook.repository.WebhookRequestRepository;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequest;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequestApi;
import com.eactive.apim.portal.djb.webhook.repository.entity.WebhookRequestEvent;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Webhook 신청/조회/수정/삭제 및 Secret 발급 오케스트레이션.
*
* 단일 EMS 데이터소스만 사용하므로 기본 {@code @Transactional} 로 충분하다(JTA 분산 트랜잭션 불필요).
* 모든 수정/삭제/Secret 조회는 소유 Org 검증({@link #loadOwned})을 거친다.
*/
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class WebhookService {
private static final String SECRET_MASK = "••••••••••••";
private final WebhookRequestRepository requestRepository;
private final WebhookRequestApiRepository apiRepository;
private final WebhookRequestEventRepository eventRepository;
private final WebhookSecretGenerator secretGenerator;
private final WebhookEventTypeProvider eventTypeProvider;
private final WebhookMapper webhookMapper;
@Transactional(readOnly = true)
public boolean existsByOrg(String orgId) {
return requestRepository.existsByOrgId(orgId);
}
@Transactional(readOnly = true)
public Optional<WebhookDTO> getByOrg(String orgId) {
return requestRepository.findByOrgId(orgId).map(this::toDetailDto);
}
/**
* 신규 신청. Org 당 1건 정책 위반 시 예외. 평문 Secret 을 1회 반환한다.
*/
public WebhookCreatedResult create(WebhookRegistrationDTO dto, String orgId) {
if (requestRepository.existsByOrgId(orgId)) {
throw new WebhookAlreadyExistsException(orgId);
}
validate(dto);
String secret = secretGenerator.generate();
WebhookRequest request = new WebhookRequest();
request.setOrgId(orgId);
request.setTargetUrl(dto.getTargetUrl().trim());
request.setSecret(secret);
WebhookRequest saved = requestRepository.save(request);
persistChildren(saved.getId(), dto);
log.info("Webhook 신규 등록 orgId={} id={}", orgId, saved.getId());
return new WebhookCreatedResult(saved.getId(), secret);
}
/**
* URL/API/EventType 수정. Secret 은 보존한다. 연관 테이블은 delete-all 후 재삽입.
*/
public WebhookDTO update(Long id, WebhookRegistrationDTO dto, String orgId) {
WebhookRequest request = loadOwned(id, orgId);
validate(dto);
request.setTargetUrl(dto.getTargetUrl().trim());
requestRepository.save(request);
apiRepository.deleteByWebhookReqId(id);
eventRepository.deleteByWebhookReqId(id);
apiRepository.flush();
eventRepository.flush();
persistChildren(id, dto);
log.info("Webhook 수정 orgId={} id={}", orgId, id);
return toDetailDto(request);
}
/**
* Secret 재발급(교체). 새 평문 Secret 반환.
*/
public String regenerateSecret(Long id, String orgId) {
WebhookRequest request = loadOwned(id, orgId);
String secret = secretGenerator.generate();
request.setSecret(secret);
requestRepository.save(request);
log.info("Webhook Secret 재발급 orgId={} id={}", orgId, id);
return secret;
}
/**
* 3개 테이블 HardDelete.
*/
public void delete(Long id, String orgId) {
WebhookRequest request = loadOwned(id, orgId);
apiRepository.deleteByWebhookReqId(id);
eventRepository.deleteByWebhookReqId(id);
requestRepository.delete(request);
log.info("Webhook 삭제 orgId={} id={}", orgId, id);
}
/**
* 평문 Secret 조회. 컨트롤러에서 비밀번호 재인증 후에만 호출한다.
*/
@Transactional(readOnly = true)
public String getPlainSecret(Long id, String orgId) {
return loadOwned(id, orgId).getSecret();
}
// ----------------------------------------------------------------
private WebhookRequest loadOwned(Long id, String orgId) {
WebhookRequest request = requestRepository.findById(id)
.orElseThrow(() -> new WebhookNotFoundException(id));
if (!Objects.equals(request.getOrgId(), orgId)) {
throw new AccessDeniedException("해당 Webhook에 대한 권한이 없습니다.");
}
return request;
}
private void persistChildren(Long reqId, WebhookRegistrationDTO dto) {
for (String apiId : dedup(dto.getSelectedApis())) {
apiRepository.save(new WebhookRequestApi(reqId, apiId));
}
for (String eventType : dedup(dto.getEventTypes())) {
if (!eventTypeProvider.isValid(eventType)) {
throw new IllegalArgumentException("유효하지 않은 EventType 코드입니다: " + eventType);
}
eventRepository.save(new WebhookRequestEvent(reqId, eventType));
}
}
private void validate(WebhookRegistrationDTO dto) {
String url = dto.getTargetUrl() == null ? "" : dto.getTargetUrl().trim();
if (!url.startsWith("http://") && !url.startsWith("https://")) {
throw new IllegalArgumentException("URL은 http:// 또는 https:// 로 시작해야 합니다.");
}
if (dto.getEventTypes() == null || dto.getEventTypes().isEmpty()) {
throw new IllegalArgumentException("EventType을 1개 이상 선택해주세요.");
}
if (dto.getSelectedApis() == null || dto.getSelectedApis().isEmpty()) {
throw new IllegalArgumentException("알림 대상 API를 1개 이상 선택해주세요.");
}
}
private List<String> dedup(List<String> values) {
if (values == null) {
return java.util.Collections.emptyList();
}
return new java.util.ArrayList<>(new LinkedHashSet<>(values));
}
private WebhookDTO toDetailDto(WebhookRequest request) {
WebhookDTO dto = webhookMapper.toDto(request);
dto.setSecretMasked(request.getSecret() == null ? "" : SECRET_MASK);
dto.setApiIds(apiRepository.findByWebhookReqId(request.getId()).stream()
.map(WebhookRequestApi::getApiId)
.collect(Collectors.toList()));
Map<String, String> names = eventTypeProvider.asMap();
dto.setEventTypes(eventRepository.findByWebhookReqId(request.getId()).stream()
.map(e -> new WebhookEventTypeDTO(e.getEventType(),
names.getOrDefault(e.getEventType(), e.getEventType())))
.collect(Collectors.toList()));
return dto;
}
}
+28
View File
@@ -205,6 +205,10 @@ portal:
method: GET
view-name: apps/service/oauth2-guide
- path-pattern: /service/webhook-dev-guide
method: GET
view-name: apps/service/webhook-dev-guide
- path-pattern: /dashboard
method: GET
view-name: apps/mypage/dashboard
@@ -297,6 +301,9 @@ page:
oauth2_guide:
name: "OAuth2 개발가이드"
path: "/service/oauth2-guide"
webhook_dev_guide:
name: "웹훅 개발가이드"
path: "/service/webhook-dev-guide"
apis:
name: "API"
path: "#"
@@ -390,6 +397,27 @@ page:
api_statistics:
name: "이용 통계"
path: "/statistics/api"
webhook:
name: "Webhook 관리"
path: "/webhook"
webhook_register_step1:
name: "Webhook 신청 (기본 정보)"
path: "/webhook/register/step1"
webhook_register_step2:
name: "Webhook 신청 (API 선택)"
path: "/webhook/register/step2"
webhook_register_step3:
name: "Webhook 신청 완료"
path: "/webhook/register/step3"
webhook_modify_step1:
name: "Webhook 수정 (기본 정보)"
path: "/webhook/modify/step1"
webhook_modify_step2:
name: "Webhook 수정 (API 선택)"
path: "/webhook/modify/step2"
webhook_modify_step3:
name: "Webhook 수정 완료"
path: "/webhook/modify/step3"
# 에디터 이미지 설정 (약관 이미지 표시용)
editor:
+436
View File
@@ -24179,6 +24179,442 @@ input[type=checkbox]:checked + .custom-checkbox {
flex-wrap: wrap;
}
}
.webhook-container {
max-width: 880px;
margin: 0 auto;
padding: 24px 16px 60px;
}
.webhook-container .field-help {
color: #6b7280;
font-size: 13px;
margin-top: 6px;
}
.webhook-container .field-error,
.webhook-container .webhook-field-error {
color: #e03131;
font-size: 13px;
margin-top: 6px;
}
.webhook-container .req {
color: #e03131;
}
.webhook-empty {
text-align: center;
padding: 64px 20px;
background: #f5f7fb;
border: 1px solid #e2e6ee;
border-radius: 14px;
}
.webhook-empty .empty-icon {
font-size: 48px;
}
.webhook-empty h3 {
margin: 16px 0 8px;
font-size: 20px;
}
.webhook-empty p {
color: #6b7280;
margin-bottom: 24px;
}
.webhook-steps {
display: flex;
gap: 8px;
margin-bottom: 28px;
}
.webhook-steps .webhook-step {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 12px;
border-radius: 10px;
background: #f5f7fb;
color: #6b7280;
font-size: 14px;
}
.webhook-steps .webhook-step .step-no {
width: 22px;
height: 22px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: #d5dbe6;
color: #fff;
font-size: 12px;
font-weight: 700;
}
.webhook-steps .webhook-step.active {
background: rgba(11, 95, 255, 0.1);
color: #0b5fff;
}
.webhook-steps .webhook-step.active .step-no {
background: #0b5fff;
}
.webhook-field {
margin-bottom: 24px;
}
.webhook-field label {
display: block;
font-weight: 600;
margin-bottom: 8px;
}
.webhook-field input[type=text],
.webhook-field input[type=password] {
width: 100%;
padding: 12px 14px;
border: 1px solid #e2e6ee;
border-radius: 10px;
font-size: 14px;
}
.webhook-field input[type=text]:focus,
.webhook-field input[type=password]:focus {
outline: none;
border-color: #0b5fff;
}
.webhook-eventtype-list {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.webhook-eventtype-list .eventtype-item {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 14px;
border: 1px solid #e2e6ee;
border-radius: 10px;
cursor: pointer;
}
.webhook-eventtype-list .eventtype-item input {
width: 18px;
height: 18px;
}
.webhook-eventtype-list .eventtype-item .eventtype-name {
font-weight: 600;
}
.webhook-eventtype-list .eventtype-item .eventtype-code {
color: #6b7280;
font-size: 12px;
margin-left: auto;
}
.webhook-eventtype-list .eventtype-item:hover {
border-color: #0b5fff;
}
.webhook-api-groups {
margin: 16px 0 8px;
}
.webhook-api-group {
margin-bottom: 24px;
}
.webhook-api-group .group-name {
font-size: 16px;
margin-bottom: 12px;
}
.webhook-api-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px;
}
.webhook-api-list .webhook-api-card {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 14px;
border: 1px solid #e2e6ee;
border-radius: 10px;
cursor: pointer;
}
.webhook-api-list .webhook-api-card input {
width: 18px;
height: 18px;
}
.webhook-api-list .webhook-api-card .api-name {
font-weight: 600;
}
.webhook-api-list .webhook-api-card .api-id {
color: #6b7280;
font-size: 12px;
margin-left: auto;
}
.webhook-api-list .webhook-api-card:hover {
border-color: #0b5fff;
}
.webhook-actions {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 32px;
}
.webhook-actions.center {
justify-content: center;
}
.btn-webhook-next,
.btn-webhook-create {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 12px 28px;
background: #0b5fff;
color: #fff;
border: none;
border-radius: 10px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
text-decoration: none;
}
.btn-webhook-next:hover,
.btn-webhook-create:hover {
background: #0847c4;
}
.btn-webhook-cancel {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 12px 28px;
background: #fff;
color: #6b7280;
border: 1px solid #e2e6ee;
border-radius: 10px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
text-decoration: none;
}
.btn-webhook-cancel:hover {
border-color: #6b7280;
}
.btn-webhook-danger {
padding: 12px 28px;
background: #fff;
color: #e03131;
border: 1px solid #e03131;
border-radius: 10px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
}
.btn-webhook-danger:hover {
background: #e03131;
color: #fff;
}
.btn-mini {
padding: 4px 12px;
background: #f5f7fb;
color: #0b5fff;
border: 1px solid #e2e6ee;
border-radius: 8px;
font-size: 12px;
cursor: pointer;
}
.btn-mini:hover {
background: rgba(11, 95, 255, 0.1);
}
.btn-copy {
padding: 10px 18px;
background: #0b5fff;
color: #fff;
border: none;
border-radius: 8px;
cursor: pointer;
}
.btn-copy:hover {
background: #0847c4;
}
.webhook-card {
border: 1px solid #e2e6ee;
border-radius: 14px;
padding: 24px;
}
.webhook-card .webhook-card-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
}
.webhook-card .webhook-card-head h3 {
font-size: 18px;
}
.webhook-card .webhook-card-head .webhook-created {
color: #6b7280;
font-size: 13px;
}
.webhook-card .webhook-card-row {
display: flex;
gap: 16px;
padding: 14px 0;
border-top: 1px solid #e2e6ee;
}
.webhook-card .webhook-card-row .row-label {
width: 110px;
color: #6b7280;
font-weight: 600;
flex-shrink: 0;
}
.webhook-card .webhook-card-row .row-value {
flex: 1;
word-break: break-all;
}
.webhook-card .webhook-card-row.secret-row, .webhook-card .webhook-card-row .secret-row {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.webhook-card .webhook-card-row code {
background: #f5f7fb;
padding: 4px 8px;
border-radius: 6px;
}
.webhook-card .eventtype-badge,
.webhook-card .api-badge {
display: inline-block;
padding: 4px 10px;
margin: 2px 4px 2px 0;
border-radius: 999px;
font-size: 12px;
background: rgba(11, 95, 255, 0.1);
color: #0b5fff;
}
.webhook-card .api-badge {
background: #f5f7fb;
color: #6b7280;
}
.webhook-card .webhook-card-actions {
display: flex;
gap: 12px;
justify-content: flex-end;
margin-top: 24px;
}
.webhook-complete {
text-align: center;
padding: 24px;
}
.webhook-complete .complete-icon {
font-size: 48px;
}
.webhook-complete h3 {
margin: 16px 0;
}
.webhook-complete .webhook-secret-box {
text-align: left;
max-width: 640px;
margin: 24px auto;
padding: 20px;
background: #f5f7fb;
border: 1px solid #e2e6ee;
border-radius: 12px;
}
.webhook-complete .webhook-secret-box .secret-warning {
color: #92400e;
background: #fef3c7;
border-radius: 8px;
padding: 12px 14px;
margin-bottom: 16px;
font-size: 13px;
}
.webhook-complete .webhook-secret-box label {
display: block;
font-weight: 600;
margin-bottom: 8px;
}
.webhook-complete .webhook-secret-box .secret-value-row {
display: flex;
gap: 8px;
}
.webhook-complete .webhook-secret-box .secret-value-row input {
flex: 1;
padding: 12px 14px;
border: 1px solid #e2e6ee;
border-radius: 10px;
font-family: monospace;
}
.webhook-guide-link {
margin-top: 20px;
text-align: center;
}
.webhook-guide-link a {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 10px 18px;
border: 1px dashed #e2e6ee;
border-radius: 10px;
color: #0b5fff;
font-size: 14px;
font-weight: 600;
text-decoration: none;
}
.webhook-guide-link a:hover {
border-color: #0b5fff;
background: rgba(11, 95, 255, 0.05);
}
.webhook-modal {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.webhook-modal .webhook-modal-box {
background: #fff;
border-radius: 14px;
padding: 28px;
width: 360px;
max-width: 90vw;
}
.webhook-modal .webhook-modal-box h4 {
font-size: 18px;
margin-bottom: 8px;
}
.webhook-modal .webhook-modal-box p {
color: #6b7280;
font-size: 14px;
margin-bottom: 16px;
}
.webhook-modal .webhook-modal-box input {
width: 100%;
padding: 12px 14px;
border: 1px solid #e2e6ee;
border-radius: 10px;
margin-bottom: 8px;
}
.webhook-modal .webhook-modal-box input:focus {
outline: none;
border-color: #0b5fff;
}
.webhook-modal .webhook-modal-box .webhook-modal-actions {
display: flex;
gap: 12px;
justify-content: flex-end;
margin-top: 12px;
}
.webhook-modal .webhook-modal-box .webhook-modal-actions .btn-webhook-next, .webhook-modal .webhook-modal-box .webhook-modal-actions .btn-webhook-cancel {
padding: 10px 20px;
font-size: 14px;
}
.d-none {
display: none !important;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,464 @@
/**
* API 선택 공용 모듈 (fragment/api_selector.html 전용)
*
* 사용처: 앱(API Key) 신청/수정 step2, Webhook 신청/수정 step2
*
* 계약:
* - 폼: #apiSelectorForm (data-save-action = "이전" 저장 POST 경로)
* - 기선택: window.API_SELECTOR_SELECTED (fragment 인라인 스크립트가 주입)
* - "이전" 버튼: 호출 페이지의 #btnPrevStep (없으면 스킵)
* - API 목록: GET /apis/for_request[?groupIds=] (ROLE_API_KEY_REQUEST)
*
* 원본(apiKeyRegisterStep2 인라인 스크립트) 대비 패치 3건:
* 1) 모달 열 때마다 updateModalList() 재빌드 — 세션 복원 직후(카드 렌더 전) 빈 모달 방지
* 2) 모달 리스트를 DOM 체크박스가 아닌 selectedApis Set 기준으로 생성 — 미렌더/타 카테고리 누락 방지
* 3) 제출/이전 시 DOM에 없는 선택분을 hidden input으로 주입 — 카테고리 필터 상태 전송 유실 방지
*/
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('apiSelectorForm');
if (!form) {
return; // 모듈 미사용 페이지
}
// DOM Elements
const searchInput = document.getElementById('apiSearch');
const sidebar = document.getElementById('apiSidebar');
const mobileToggle = document.getElementById('mobileToggle');
const mobileOverlay = document.getElementById('mobileOverlay');
const menuTitles = document.querySelectorAll('.menu-title');
const apiCardGrid = document.getElementById('apiCardGrid');
const loadingState = document.getElementById('loadingState');
const emptyState = document.getElementById('emptyState');
let currentFilter = ''; // Empty string means "all"
let currentServiceName = '전체';
let allApis = [];
let selectedApis = new Set();
// Restore selected APIs from session (fragment 인라인 주입)
const sessionSelectedApis = window.API_SELECTOR_SELECTED;
if (sessionSelectedApis && Array.isArray(sessionSelectedApis)) {
sessionSelectedApis.forEach(function(apiId) {
selectedApis.add(apiId);
});
}
// Load APIs via AJAX
function loadApis(groupId) {
loadingState.style.display = 'block';
emptyState.style.display = 'none';
document.querySelectorAll('.api-selection-card').forEach(card => card.remove());
let url = '/apis/for_request';
if (groupId) {
url += '?groupIds=' + encodeURIComponent(groupId);
}
fetch(url).then(response => response.json()).then(apis => {
allApis = apis;
loadingState.style.display = 'none';
if (apis.length === 0) {
emptyState.style.display = 'block';
return;
}
renderApiCards(apis);
updateSelectAllUI();
}).catch(error => {
console.error('Failed to load APIs:', error);
loadingState.style.display = 'none';
emptyState.querySelector('h3').textContent = 'API 로드 실패';
emptyState.querySelector('p').textContent = '다시 시도해주세요.';
emptyState.style.display = 'block';
});
}
// Render API cards
function renderApiCards(apis) {
const fragment = document.createDocumentFragment();
apis.forEach(api => {
fragment.appendChild(createApiCard(api));
});
apiCardGrid.appendChild(fragment);
attachCardEventListeners();
}
// Create API card element
function createApiCard(api) {
const card = document.createElement('div');
card.className = 'api-selection-card';
card.setAttribute('data-group', api.apiGroupId || '');
card.setAttribute('data-name', (api.apiName || '').toLowerCase());
card.setAttribute('data-desc', (api.apiSimpleDescription || '').toLowerCase());
card.setAttribute('data-api-id', api.apiId);
const isSelected = selectedApis.has(api.apiId);
if (isSelected) {
card.classList.add('selected');
}
const mainIconHtml = api.mainIcon
? `<img src="${api.mainIcon}" alt="${api.apiName}" onerror="this.style.display='none'; this.nextElementSibling.style.display='block'"><i class="fas fa-cube" style="display:none"></i>`
: `<i class="fas fa-cube"></i>`;
card.innerHTML = `
<div class="api-card-content">
<div class="api-card-header">
<span class="api-card-category">${api.service || '카테고리'}</span>
<div class="checkbox-wrapper">
<input type="checkbox"
name="selectedApis"
value="${api.apiId}"
id="api-${api.apiId}"
class="api-checkbox visually-hidden"
${isSelected ? 'checked' : ''}>
<span class="custom-checkbox"></span>
</div>
</div>
<h3 class="api-name">${api.apiName || 'API 이름'}</h3>
<p class="api-description">${api.apiSimpleDescription || 'API 설명이 없습니다.'}</p>
<div class="api-card-icon">
${mainIconHtml}
</div>
</div>
`;
return card;
}
// Attach event listeners to cards
function attachCardEventListeners() {
const checkboxes = document.querySelectorAll('.api-checkbox');
const apiCards = document.querySelectorAll('.api-selection-card');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
updateCardSelection(this);
updateSelectedCount();
});
});
apiCards.forEach(card => {
card.addEventListener('click', function(e) {
if (e.target.classList.contains('api-checkbox')) {
return;
}
const checkbox = card.querySelector('.api-checkbox');
if (checkbox) {
checkbox.checked = !checkbox.checked;
updateCardSelection(checkbox);
updateSelectedCount();
}
});
});
}
// Update card visual state
function updateCardSelection(checkbox) {
const card = checkbox.closest('.api-selection-card');
if (checkbox.checked) {
card.classList.add('selected');
selectedApis.add(checkbox.value);
} else {
card.classList.remove('selected');
selectedApis.delete(checkbox.value);
}
}
// Update selected count
function updateSelectedCount() {
const floatingCartBtn = document.getElementById('floatingCartBtn');
const cartCount = document.querySelector('.cart-count');
if (selectedApis.size > 0) {
floatingCartBtn.style.display = 'flex';
cartCount.textContent = selectedApis.size;
} else {
floatingCartBtn.style.display = 'none';
}
updateModalList();
updateSelectAllCheckboxState();
}
// Update select all UI visibility and text
function updateSelectAllUI() {
const selectAllWrapper = document.getElementById('selectAllWrapper');
const selectAllText = document.getElementById('selectAllText');
if (currentFilter === '') {
selectAllWrapper.style.display = 'none';
} else {
selectAllWrapper.style.display = 'flex';
selectAllText.textContent = currentServiceName + ' API 전체 선택';
}
updateSelectAllCheckboxState();
}
// Update select all checkbox state based on visible cards
function updateSelectAllCheckboxState() {
const selectAllCheckbox = document.getElementById('selectAllCheckbox');
const visibleCards = Array.from(document.querySelectorAll('.api-selection-card')).filter(card => card.style.display !== 'none');
if (visibleCards.length === 0) {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = false;
return;
}
const visibleCheckboxes = visibleCards.map(card => card.querySelector('.api-checkbox'));
const checkedCount = visibleCheckboxes.filter(cb => cb.checked).length;
if (checkedCount === 0) {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = false;
} else if (checkedCount === visibleCheckboxes.length) {
selectAllCheckbox.checked = true;
selectAllCheckbox.indeterminate = false;
} else {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = true;
}
}
// Update modal selected APIs list — selectedApis Set 기준 (패치 2)
function updateModalList() {
const modalSelectedList = document.getElementById('modalSelectedList');
modalSelectedList.innerHTML = '';
if (selectedApis.size === 0) {
modalSelectedList.innerHTML = '<p class="empty-message">선택된 API가 없습니다.</p>';
return;
}
selectedApis.forEach(function(apiId) {
const card = document.querySelector('.api-selection-card[data-api-id="' + apiId + '"]');
const apiName = card ? card.querySelector('.api-name').textContent : apiId;
const apiPill = document.createElement('div');
apiPill.className = 'api-pill';
apiPill.innerHTML = `
<span class="api-pill-name">${apiName}</span>
<button type="button" class="api-pill-remove" data-value="${apiId}" aria-label="Remove ${apiName}">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
`;
modalSelectedList.appendChild(apiPill);
});
document.querySelectorAll('.api-pill-remove').forEach(function(btn) {
btn.addEventListener('click', function() {
const value = this.getAttribute('data-value');
selectedApis.delete(value);
const checkbox = document.querySelector('.api-checkbox[value="' + value + '"]');
if (checkbox) {
checkbox.checked = false;
updateCardSelection(checkbox);
}
updateSelectedCount();
});
});
}
// Search functionality
if (searchInput) {
searchInput.addEventListener('input', function() {
const searchTerm = this.value.toLowerCase();
document.querySelectorAll('.api-selection-card').forEach(function(card) {
const apiName = card.getAttribute('data-name');
const apiDesc = card.getAttribute('data-desc');
const matchesSearch = apiName.includes(searchTerm) || apiDesc.includes(searchTerm);
card.style.display = matchesSearch ? '' : 'none';
});
updateSelectAllCheckboxState();
});
}
// Sidebar category selection
menuTitles.forEach(function(title) {
title.addEventListener('click', function(e) {
e.preventDefault();
menuTitles.forEach(t => t.classList.remove('active'));
this.classList.add('active');
const groupId = this.getAttribute('data-group');
currentFilter = groupId;
currentServiceName = this.textContent.trim().split('\n')[0].trim();
loadApis(groupId);
if (searchInput) {
searchInput.value = '';
}
if (window.innerWidth <= 768 && sidebar.classList.contains('mobile-open')) {
closeMobileMenu();
}
});
});
// Mobile menu toggle
function closeMobileMenu() {
sidebar.classList.remove('mobile-open');
mobileOverlay.classList.remove('active');
mobileToggle.innerHTML = '☰';
mobileToggle.setAttribute('aria-label', '메뉴 열기');
}
if (mobileToggle && sidebar && mobileOverlay) {
mobileToggle.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
sidebar.classList.toggle('mobile-open');
mobileOverlay.classList.toggle('active');
if (sidebar.classList.contains('mobile-open')) {
this.innerHTML = '✕';
this.setAttribute('aria-label', '메뉴 닫기');
} else {
this.innerHTML = '☰';
this.setAttribute('aria-label', '메뉴 열기');
}
});
mobileOverlay.addEventListener('click', closeMobileMenu);
}
window.addEventListener('resize', function() {
if (window.innerWidth > 768 && sidebar.classList.contains('mobile-open')) {
closeMobileMenu();
}
});
// Modal control
const floatingCartBtn = document.getElementById('floatingCartBtn');
const selectedApisModal = document.getElementById('selectedApisModal');
const modalOverlay = document.getElementById('modalOverlay');
const modalCloseBtn = document.getElementById('modalCloseBtn');
const modalCancelBtn = document.getElementById('modalCancelBtn');
function openModal() {
updateModalList(); // 열 때마다 최신 선택 상태로 재빌드 (패치 1)
selectedApisModal.style.display = 'block';
setTimeout(function() {
if (modalOverlay) {
modalOverlay.classList.add('show');
}
selectedApisModal.classList.add('show');
}, 10);
document.body.style.overflow = 'hidden';
}
function closeModal() {
if (modalOverlay) {
modalOverlay.classList.remove('show');
}
selectedApisModal.classList.remove('show');
setTimeout(function() {
selectedApisModal.style.display = 'none';
}, 300);
document.body.style.overflow = '';
}
if (floatingCartBtn) {
floatingCartBtn.addEventListener('click', openModal);
}
if (modalOverlay) {
modalOverlay.addEventListener('click', closeModal);
}
if (modalCloseBtn) {
modalCloseBtn.addEventListener('click', closeModal);
}
if (modalCancelBtn) {
modalCancelBtn.addEventListener('click', closeModal);
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && selectedApisModal.style.display === 'block') {
closeModal();
}
});
// Select All checkbox event
const selectAllCheckbox = document.getElementById('selectAllCheckbox');
if (selectAllCheckbox) {
selectAllCheckbox.addEventListener('change', function() {
const isChecked = this.checked;
const visibleCards = Array.from(document.querySelectorAll('.api-selection-card')).filter(card => card.style.display !== 'none');
visibleCards.forEach(function(card) {
const checkbox = card.querySelector('.api-checkbox');
if (checkbox) {
checkbox.checked = isChecked;
updateCardSelection(checkbox);
}
});
updateSelectedCount();
});
}
// DOM에 렌더되지 않은 선택분을 hidden input으로 주입 — 전송 유실 방지 (패치 3)
function syncHiddenSelected() {
document.querySelectorAll('input.hidden-selected-api').forEach(el => el.remove());
selectedApis.forEach(function(apiId) {
if (!document.querySelector('.api-checkbox[value="' + apiId + '"]')) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'selectedApis';
input.value = apiId;
input.className = 'hidden-selected-api';
form.appendChild(input);
}
});
}
// Previous step button — 선택 저장 후 step1 복귀
const btnPrevStep = document.getElementById('btnPrevStep');
if (btnPrevStep) {
btnPrevStep.addEventListener('click', function(e) {
e.preventDefault();
const saveAction = form.getAttribute('data-save-action');
if (saveAction) {
form.action = saveAction;
}
syncHiddenSelected();
form.submit();
});
}
// Form validation
form.addEventListener('submit', function(e) {
if (selectedApis.size === 0) {
e.preventDefault();
if (window.customPopups && customPopups.showAlert) {
customPopups.showAlert('최소 1개 이상의 API를 선택해주세요.');
} else {
alert('최소 1개 이상의 API를 선택해주세요.');
}
return false;
}
syncHiddenSelected();
});
// Initialize
updateSelectedCount();
loadApis('');
});
+1
View File
@@ -66,6 +66,7 @@
@use 'pages/terms-agreements' as *;
@use 'pages/service' as *;
@use 'pages/api-statistics' as *;
@use 'pages/webhook' as *;
// 6. Themes
@use 'themes/dark' as *;
@@ -0,0 +1,293 @@
// Webhook 신청/관리 (DJPGPT0004)
// App API Key 신청 3-step UI 톤을 답습한 자체 완결 스타일.
$wh-primary: #0b5fff;
$wh-primary-dark: #0847c4;
$wh-danger: #e03131;
$wh-border: #e2e6ee;
$wh-muted: #6b7280;
$wh-bg-soft: #f5f7fb;
.webhook-container {
max-width: 880px;
margin: 0 auto;
padding: 24px 16px 60px;
.field-help { color: $wh-muted; font-size: 13px; margin-top: 6px; }
.field-error,
.webhook-field-error { color: $wh-danger; font-size: 13px; margin-top: 6px; }
.req { color: $wh-danger; }
}
// ---------- 빈 상태 ----------
.webhook-empty {
text-align: center;
padding: 64px 20px;
background: $wh-bg-soft;
border: 1px solid $wh-border;
border-radius: 14px;
.empty-icon { font-size: 48px; }
h3 { margin: 16px 0 8px; font-size: 20px; }
p { color: $wh-muted; margin-bottom: 24px; }
}
// ---------- 진행 표시 ----------
.webhook-steps {
display: flex;
gap: 8px;
margin-bottom: 28px;
.webhook-step {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 12px;
border-radius: 10px;
background: $wh-bg-soft;
color: $wh-muted;
font-size: 14px;
.step-no {
width: 22px; height: 22px;
display: inline-flex; align-items: center; justify-content: center;
border-radius: 50%;
background: #d5dbe6; color: #fff; font-size: 12px; font-weight: 700;
}
&.active {
background: rgba($wh-primary, 0.1);
color: $wh-primary;
.step-no { background: $wh-primary; }
}
}
}
// ---------- 폼 ----------
.webhook-field {
margin-bottom: 24px;
label { display: block; font-weight: 600; margin-bottom: 8px; }
input[type="text"],
input[type="password"] {
width: 100%;
padding: 12px 14px;
border: 1px solid $wh-border;
border-radius: 10px;
font-size: 14px;
&:focus { outline: none; border-color: $wh-primary; }
}
}
.webhook-eventtype-list {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
.eventtype-item {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 14px;
border: 1px solid $wh-border;
border-radius: 10px;
cursor: pointer;
input { width: 18px; height: 18px; }
.eventtype-name { font-weight: 600; }
.eventtype-code { color: $wh-muted; font-size: 12px; margin-left: auto; }
&:hover { border-color: $wh-primary; }
}
}
// ---------- API 선택 ----------
.webhook-api-groups { margin: 16px 0 8px; }
.webhook-api-group {
margin-bottom: 24px;
.group-name { font-size: 16px; margin-bottom: 12px; }
}
.webhook-api-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px;
.webhook-api-card {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 14px;
border: 1px solid $wh-border;
border-radius: 10px;
cursor: pointer;
input { width: 18px; height: 18px; }
.api-name { font-weight: 600; }
.api-id { color: $wh-muted; font-size: 12px; margin-left: auto; }
&:hover { border-color: $wh-primary; }
}
}
// ---------- 액션 버튼 ----------
.webhook-actions {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 32px;
&.center { justify-content: center; }
}
.btn-webhook-next,
.btn-webhook-create {
display: inline-flex; align-items: center; justify-content: center;
padding: 12px 28px;
background: $wh-primary; color: #fff;
border: none; border-radius: 10px;
font-size: 15px; font-weight: 600; cursor: pointer; text-decoration: none;
&:hover { background: $wh-primary-dark; }
}
.btn-webhook-cancel {
display: inline-flex; align-items: center; justify-content: center;
padding: 12px 28px;
background: #fff; color: $wh-muted;
border: 1px solid $wh-border; border-radius: 10px;
font-size: 15px; font-weight: 600; cursor: pointer; text-decoration: none;
&:hover { border-color: $wh-muted; }
}
.btn-webhook-danger {
padding: 12px 28px;
background: #fff; color: $wh-danger;
border: 1px solid $wh-danger; border-radius: 10px;
font-size: 15px; font-weight: 600; cursor: pointer;
&:hover { background: $wh-danger; color: #fff; }
}
.btn-mini {
padding: 4px 12px;
background: $wh-bg-soft; color: $wh-primary;
border: 1px solid $wh-border; border-radius: 8px;
font-size: 12px; cursor: pointer;
&:hover { background: rgba($wh-primary, 0.1); }
}
.btn-copy {
padding: 10px 18px;
background: $wh-primary; color: #fff;
border: none; border-radius: 8px; cursor: pointer;
&:hover { background: $wh-primary-dark; }
}
// ---------- 등록 카드 ----------
.webhook-card {
border: 1px solid $wh-border;
border-radius: 14px;
padding: 24px;
.webhook-card-head {
display: flex; align-items: center; justify-content: space-between;
margin-bottom: 20px;
h3 { font-size: 18px; }
.webhook-created { color: $wh-muted; font-size: 13px; }
}
.webhook-card-row {
display: flex;
gap: 16px;
padding: 14px 0;
border-top: 1px solid $wh-border;
.row-label { width: 110px; color: $wh-muted; font-weight: 600; flex-shrink: 0; }
.row-value { flex: 1; word-break: break-all; }
&.secret-row, .secret-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
code { background: $wh-bg-soft; padding: 4px 8px; border-radius: 6px; }
}
.eventtype-badge,
.api-badge {
display: inline-block;
padding: 4px 10px; margin: 2px 4px 2px 0;
border-radius: 999px; font-size: 12px;
background: rgba($wh-primary, 0.1); color: $wh-primary;
}
.api-badge { background: $wh-bg-soft; color: $wh-muted; }
.webhook-card-actions {
display: flex; gap: 12px; justify-content: flex-end;
margin-top: 24px;
}
}
// ---------- 완료 화면 ----------
.webhook-complete {
text-align: center;
padding: 24px;
.complete-icon { font-size: 48px; }
h3 { margin: 16px 0; }
.webhook-secret-box {
text-align: left;
max-width: 640px; margin: 24px auto;
padding: 20px;
background: $wh-bg-soft; border: 1px solid $wh-border; border-radius: 12px;
.secret-warning {
color: #92400e; background: #fef3c7;
border-radius: 8px; padding: 12px 14px; margin-bottom: 16px; font-size: 13px;
}
label { display: block; font-weight: 600; margin-bottom: 8px; }
.secret-value-row {
display: flex; gap: 8px;
input { flex: 1; padding: 12px 14px; border: 1px solid $wh-border; border-radius: 10px; font-family: monospace; }
}
}
}
// ---------- 개발가이드 링크 ----------
.webhook-guide-link {
margin-top: 20px;
text-align: center;
a {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 10px 18px;
border: 1px dashed $wh-border;
border-radius: 10px;
color: $wh-primary;
font-size: 14px;
font-weight: 600;
text-decoration: none;
&:hover {
border-color: $wh-primary;
background: rgba($wh-primary, 0.05);
}
}
}
// ---------- 비밀번호 모달 ----------
.webhook-modal {
position: fixed; inset: 0;
background: rgba(0, 0, 0, 0.45);
display: flex; align-items: center; justify-content: center;
z-index: 1000;
.webhook-modal-box {
background: #fff; border-radius: 14px;
padding: 28px; width: 360px; max-width: 90vw;
h4 { font-size: 18px; margin-bottom: 8px; }
p { color: $wh-muted; font-size: 14px; margin-bottom: 16px; }
input {
width: 100%; padding: 12px 14px;
border: 1px solid $wh-border; border-radius: 10px; margin-bottom: 8px;
&:focus { outline: none; border-color: $wh-primary; }
}
.webhook-modal-actions {
display: flex; gap: 12px; justify-content: flex-end; margin-top: 12px;
.btn-webhook-next, .btn-webhook-cancel { padding: 10px 20px; font-size: 14px; }
}
}
}
@@ -0,0 +1,469 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<th:block layout:fragment="contentFragment">
<section class="oauth2-2legged">
<!-- Section 1: Hero -->
<header class="oauth2-2legged__hero">
<div class="oauth2-2legged__hero-body">
<span class="oauth2-2legged__hero-eyebrow">
<span class="oauth2-2legged__hero-eyebrow-dot"></span>
개발 가이드 · Webhook · HMAC-SHA256
</span>
<h1 class="oauth2-2legged__hero-title">웹훅 개발가이드</h1>
<p class="oauth2-2legged__hero-lead">DJBank가 발송하는 Webhook 요청의 진위를 확인하기 위한</p>
<p class="oauth2-2legged__hero-lead">HMAC-SHA256 서명 검증 방법을 단계별로 설명합니다.</p>
<div class="oauth2-2legged__hero-chips">
<span class="oauth2-2legged__chip oauth2-2legged__chip--primary">HMAC-SHA256</span>
<span class="oauth2-2legged__chip">X-Webhook-Signature</span>
<span class="oauth2-2legged__chip">Raw Body</span>
</div>
</div>
<div class="oauth2-2legged__hero-illust" aria-hidden="true">
<svg viewBox="0 0 280 200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Signed Webhook Delivery">
<defs>
<marker id="whsig-hero-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto">
<path d="M0,0 L10,5 L0,10 Z" fill="#0049b4"/>
</marker>
</defs>
<rect x="0" y="0" width="280" height="200" rx="20" fill="#FFFFFF"/>
<rect x="24" y="92" width="86" height="52" rx="8" fill="#EDF9FE" stroke="#0049b4"/>
<text x="67" y="114" text-anchor="middle" font-size="10" font-weight="700" fill="#0049b4">DJBank</text>
<text x="67" y="128" text-anchor="middle" font-size="10" font-weight="700" fill="#0049b4">Webhook</text>
<rect x="170" y="92" width="86" height="52" rx="8" fill="#EDF9FE" stroke="#0049b4"/>
<text x="213" y="114" text-anchor="middle" font-size="10" font-weight="700" fill="#0049b4">Your</text>
<text x="213" y="128" text-anchor="middle" font-size="10" font-weight="700" fill="#0049b4">Endpoint</text>
<line x1="110" y1="118" x2="170" y2="118" stroke="#0049b4" stroke-width="2" marker-end="url(#whsig-hero-arrow)"/>
<g transform="translate(58,28)">
<rect width="164" height="34" rx="6" fill="#1A1A2E"/>
<text x="12" y="16" font-family="'Fira Code', monospace" font-size="9" fill="#00D4FF">X-Webhook-Signature:</text>
<text x="12" y="28" font-family="'Fira Code', monospace" font-size="9" fill="#FFD93D">sha256=9f86d0..</text>
</g>
<g transform="translate(133,104)">
<circle r="13" fill="#0049b4"/>
<path d="M-5,-1 h10 v7 h-10 z M-3,-1 v-3 a3,3 0 0 1 6,0 v3" fill="none" stroke="#FFFFFF" stroke-width="1.5"/>
</g>
<text x="140" y="172" text-anchor="middle" font-size="11" font-weight="600" fill="#64748B">Signed Webhook Delivery</text>
</svg>
</div>
</header>
<!-- Section 2: 개요 -->
<section class="oauth2-2legged__prereq" aria-labelledby="whsig-prereq-title">
<span class="oauth2-2legged__eyebrow">OVERVIEW</span>
<h2 class="oauth2-2legged__h2" id="whsig-prereq-title">서명 검증이 필요한 이유</h2>
<div class="oauth2-2legged__prereq-grid">
<article class="oauth2-2legged__prereq-card">
<span class="oauth2-2legged__prereq-num">1</span>
<div class="oauth2-2legged__prereq-body">
<h3 class="oauth2-2legged__prereq-title">Secret 확보</h3>
<p>[마이페이지 &gt; Webhook 관리]에서 발급된</p>
<p>Secret Key를 서버에 안전하게 보관.</p>
</div>
</article>
<article class="oauth2-2legged__prereq-card">
<span class="oauth2-2legged__prereq-num">2</span>
<div class="oauth2-2legged__prereq-body">
<h3 class="oauth2-2legged__prereq-title">원문(raw body) 보존</h3>
<p>수신 즉시 본문을 파싱/재직렬화하지 말고</p>
<p>바이트 원문 그대로 서명 계산에 사용.</p>
</div>
</article>
<article class="oauth2-2legged__prereq-card">
<span class="oauth2-2legged__prereq-num">3</span>
<div class="oauth2-2legged__prereq-body">
<h3 class="oauth2-2legged__prereq-title">HMAC 재계산·비교</h3>
<p>동일 Secret으로 HMAC-SHA256을 재계산해</p>
<p>헤더 서명과 상수 시간으로 비교.</p>
</div>
</article>
</div>
</section>
<!-- Section 3: 전체 서명·검증 시퀀스 -->
<section class="oauth2-2legged__sequence" aria-labelledby="whsig-seq-title">
<span class="oauth2-2legged__eyebrow">SEQUENCE</span>
<h2 class="oauth2-2legged__h2" id="whsig-seq-title">전체 서명·검증 시퀀스</h2>
<div class="oauth2-2legged__sequence-diagram">
<svg viewBox="0 0 1120 300" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Webhook Signature Verification Sequence">
<defs>
<marker id="whsig-arrow-primary" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto">
<path d="M0,0 L10,5 L0,10 Z" fill="#0049b4"/>
</marker>
<marker id="whsig-arrow-gray" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto">
<path d="M0,0 L10,5 L0,10 Z" fill="#64748B"/>
</marker>
</defs>
<g>
<rect x="120" y="24" width="240" height="48" rx="24" fill="#EDF9FE" stroke="#0049b4"/>
<text x="240" y="54" text-anchor="middle" font-size="14" font-weight="700" fill="#0049b4">DJBank Webhook Sender</text>
<line x1="240" y1="72" x2="240" y2="272" stroke="#94A3B8" stroke-dasharray="4 4"/>
</g>
<g>
<rect x="760" y="24" width="240" height="48" rx="24" fill="#FFFFFF" stroke="#0049b4"/>
<text x="880" y="54" text-anchor="middle" font-size="14" font-weight="700" fill="#0049b4">Your Endpoint</text>
<line x1="880" y1="72" x2="880" y2="272" stroke="#94A3B8" stroke-dasharray="4 4"/>
</g>
<text x="240" y="104" text-anchor="middle" font-size="12" font-weight="700" fill="#64748B">① 이벤트 발생 (점검·지연·장애)</text>
<text x="240" y="124" text-anchor="middle" font-size="12" font-weight="700" fill="#64748B">② signature = HMAC-SHA256(secret, body)</text>
<text x="560" y="156" text-anchor="middle" font-size="12" font-weight="700" fill="#0049b4">③ POST body · X-Webhook-Signature: sha256=&lt;hex&gt;</text>
<line x1="240" y1="166" x2="880" y2="166" stroke="#0049b4" stroke-width="2" marker-end="url(#whsig-arrow-primary)"/>
<text x="880" y="198" text-anchor="middle" font-size="12" font-weight="700" fill="#64748B">④ 동일 secret으로 재계산</text>
<text x="880" y="218" text-anchor="middle" font-size="12" font-weight="700" fill="#64748B">⑤ 상수 시간 비교 (일치 여부)</text>
<text x="560" y="250" text-anchor="middle" font-size="12" font-weight="700" fill="#64748B">⑥ 200 OK (검증 성공 시)</text>
<line x1="880" y1="260" x2="240" y2="260" stroke="#64748B" stroke-width="2" marker-end="url(#whsig-arrow-gray)"/>
</svg>
</div>
</section>
<!-- Section 4: STEP 1 — 수신 요청 형식 -->
<section class="oauth2-2legged__step" aria-labelledby="whsig-step1-title">
<span class="oauth2-2legged__eyebrow">STEP 1</span>
<h2 class="oauth2-2legged__h2" id="whsig-step1-title">수신 요청 형식</h2>
<p class="oauth2-2legged__desc">DJBank는 등록한 수신 URL로 아래 형태의 POST 요청을 전송합니다.</p>
<div class="oauth2-2legged__endpoint-box">
<span class="oauth2-2legged__method">POST</span>
<code class="oauth2-2legged__endpoint-path">https://your-service.example.com/webhook</code>
<span class="oauth2-2legged__endpoint-content-type">application/json</span>
</div>
<div class="oauth2-2legged__step-grid">
<div class="oauth2-2legged__panel">
<h3 class="oauth2-2legged__panel-title">요청 헤더</h3>
<table class="oauth2-2legged__table">
<thead>
<tr>
<th>HEADER</th>
<th>설명</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>X-Webhook-Signature</code></td>
<td><code>sha256=&lt;hex&gt;</code> — 본문 HMAC-SHA256 서명(소문자 hex)</td>
</tr>
<tr>
<td><code>X-Webhook-Event</code></td>
<td>이벤트 코드 (예: CONTROL_START)</td>
</tr>
<tr>
<td><code>X-Webhook-Timestamp</code></td>
<td>발송 시각 (epoch millis) — 재전송 방어용</td>
</tr>
<tr>
<td><code>Content-Type</code></td>
<td>application/json</td>
</tr>
</tbody>
</table>
<p class="oauth2-2legged__warning">⚠ 서명 대상은 파싱 전 <strong>본문 원문(raw body)</strong> 입니다.</p>
</div>
<div class="oauth2-2legged__code-panel">
<span class="oauth2-2legged__code-tag">Request Body · JSON</span>
<pre class="oauth2-2legged__code-block">{
<span class="o2leg-c">"eventType"</span>: <span class="o2leg-y">"CONTROL_START"</span>,
<span class="o2leg-c">"eventId"</span>: <span class="o2leg-y">"f47ac10b-58cc-4372-a567-0e02b2c3d479"</span>,
<span class="o2leg-c">"timestamp"</span>: <span class="o2leg-p">1723600000000</span>,
<span class="o2leg-c">"data"</span>: [ <span class="o2leg-y">"TESTCASE003S1"</span>, <span class="o2leg-y">"TESTCASE005S1"</span> ]
}
<span class="o2leg-g"># eventId: 발송 건 고유 ID · data: 영향 API 목록</span></pre>
</div>
</div>
</section>
<!-- Section 5: STEP 2 — 서명 검증 알고리즘 -->
<section class="oauth2-2legged__step" aria-labelledby="whsig-step2-title">
<span class="oauth2-2legged__eyebrow">STEP 2</span>
<h2 class="oauth2-2legged__h2" id="whsig-step2-title">서명 검증 알고리즘</h2>
<p class="oauth2-2legged__desc">수신한 본문 원문과 발급된 Secret으로 서명을 재계산해 헤더 값과 비교합니다.</p>
<div class="oauth2-2legged__step-grid">
<div class="oauth2-2legged__code-panel">
<span class="oauth2-2legged__code-tag">Verification Steps</span>
<pre class="oauth2-2legged__code-block"><span class="o2leg-cm"># 1) 헤더에서 서명 추출</span>
received = header[<span class="o2leg-c">"X-Webhook-Signature"</span>] <span class="o2leg-g"># "sha256=...."</span>
<span class="o2leg-cm"># 2) 본문 원문으로 HMAC-SHA256 재계산</span>
digest = HMAC_SHA256(secret, rawBody) <span class="o2leg-g"># bytes</span>
expected = <span class="o2leg-y">"sha256="</span> + toHexLower(digest)
<span class="o2leg-cm"># 3) 상수 시간 비교</span>
valid = constantTimeEquals(received, expected)</pre>
</div>
<div class="oauth2-2legged__panel">
<h3 class="oauth2-2legged__panel-title">검증 규칙</h3>
<ul class="oauth2-2legged__tips">
<li>알고리즘: <code>HmacSHA256</code>, 키: Secret(UTF-8 bytes)</li>
<li>메시지: 수신 <strong>본문 원문</strong>(UTF-8 bytes)</li>
<li>출력: <strong>소문자 hex</strong>, 헤더는 <code>sha256=</code> 접두 포함</li>
<li>비교: 타이밍 공격 방지를 위해 <strong>상수 시간</strong> 비교</li>
<li>불일치 시 요청을 폐기하고 2xx 이외로 응답</li>
</ul>
<h4 class="oauth2-2legged__panel-subtitle">재전송(replay) 방어</h4>
<ul class="oauth2-2legged__tips">
<li><code>X-Webhook-Timestamp</code>가 허용 오차(예: 5분) 밖이면 거부</li>
<li>동일 <code>eventId</code> 중복 수신은 멱등 처리</li>
</ul>
</div>
</div>
</section>
<!-- Section 6: STEP 3 — 언어별 예제 -->
<section class="oauth2-2legged__step" aria-labelledby="whsig-step3-title">
<span class="oauth2-2legged__eyebrow">STEP 3</span>
<h2 class="oauth2-2legged__h2" id="whsig-step3-title">언어별 서명 검증 예제</h2>
<p class="oauth2-2legged__desc">프레임워크에서 반드시 <strong>원문 바디</strong>에 접근할 수 있어야 합니다.</p>
<div class="oauth2-2legged__step-grid">
<div class="oauth2-2legged__code-panel">
<span class="oauth2-2legged__code-tag">Node.js (Express)</span>
<pre class="oauth2-2legged__code-block"><span class="o2leg-p">const</span> crypto = <span class="o2leg-y">require</span>(<span class="o2leg-c">'crypto'</span>);
<span class="o2leg-cm">// rawBody: express.raw() 등으로 확보한 원문 Buffer</span>
<span class="o2leg-p">function</span> <span class="o2leg-y">verify</span>(rawBody, header, secret) {
<span class="o2leg-p">const</span> expected = <span class="o2leg-c">'sha256='</span> +
crypto.<span class="o2leg-y">createHmac</span>(<span class="o2leg-c">'sha256'</span>, secret)
.<span class="o2leg-y">update</span>(rawBody)
.<span class="o2leg-y">digest</span>(<span class="o2leg-c">'hex'</span>);
<span class="o2leg-p">const</span> a = Buffer.<span class="o2leg-y">from</span>(header);
<span class="o2leg-p">const</span> b = Buffer.<span class="o2leg-y">from</span>(expected);
<span class="o2leg-p">return</span> a.length === b.length &amp;&amp;
crypto.<span class="o2leg-y">timingSafeEqual</span>(a, b);
}</pre>
</div>
<div class="oauth2-2legged__code-panel">
<span class="oauth2-2legged__code-tag">Python (Flask)</span>
<pre class="oauth2-2legged__code-block"><span class="o2leg-p">import</span> hmac, hashlib
<span class="o2leg-cm"># raw_body: request.get_data() 로 확보한 bytes</span>
<span class="o2leg-p">def</span> <span class="o2leg-y">verify</span>(raw_body, header, secret):
digest = hmac.<span class="o2leg-y">new</span>(
secret.<span class="o2leg-y">encode</span>(<span class="o2leg-c">'utf-8'</span>),
raw_body,
hashlib.sha256
).<span class="o2leg-y">hexdigest</span>()
expected = <span class="o2leg-c">'sha256='</span> + digest
<span class="o2leg-p">return</span> hmac.<span class="o2leg-y">compare_digest</span>(expected, header)</pre>
</div>
</div>
<div class="oauth2-2legged__step-grid">
<div class="oauth2-2legged__code-panel">
<span class="oauth2-2legged__code-tag">Java</span>
<pre class="oauth2-2legged__code-block"><span class="o2leg-p">import</span> javax.crypto.Mac;
<span class="o2leg-p">import</span> javax.crypto.spec.SecretKeySpec;
<span class="o2leg-p">import</span> java.nio.charset.StandardCharsets;
<span class="o2leg-p">import</span> java.security.MessageDigest;
<span class="o2leg-cm">// rawBody: 파싱 전 원문 문자열</span>
<span class="o2leg-p">boolean</span> <span class="o2leg-y">verify</span>(String rawBody, String header, String secret) <span class="o2leg-p">throws</span> Exception {
Mac mac = Mac.<span class="o2leg-y">getInstance</span>(<span class="o2leg-c">"HmacSHA256"</span>);
mac.<span class="o2leg-y">init</span>(<span class="o2leg-p">new</span> SecretKeySpec(secret.<span class="o2leg-y">getBytes</span>(StandardCharsets.UTF_8), <span class="o2leg-c">"HmacSHA256"</span>));
<span class="o2leg-p">byte</span>[] hash = mac.<span class="o2leg-y">doFinal</span>(rawBody.<span class="o2leg-y">getBytes</span>(StandardCharsets.UTF_8));
StringBuilder hex = <span class="o2leg-p">new</span> StringBuilder();
<span class="o2leg-p">for</span> (<span class="o2leg-p">byte</span> b : hash) hex.<span class="o2leg-y">append</span>(String.<span class="o2leg-y">format</span>(<span class="o2leg-c">"%02x"</span>, b));
String expected = <span class="o2leg-c">"sha256="</span> + hex;
<span class="o2leg-p">return</span> MessageDigest.<span class="o2leg-y">isEqual</span>(
expected.<span class="o2leg-y">getBytes</span>(StandardCharsets.UTF_8),
header.<span class="o2leg-y">getBytes</span>(StandardCharsets.UTF_8));
}</pre>
</div>
<div class="oauth2-2legged__panel">
<h3 class="oauth2-2legged__panel-title">이벤트 코드 (X-Webhook-Event)</h3>
<table class="oauth2-2legged__table">
<thead>
<tr>
<th>CODE</th>
<th>의미</th>
</tr>
</thead>
<tbody>
<tr><td><code>CONTROL_START</code></td><td>점검 시작</td></tr>
<tr><td><code>CONTROL_END</code></td><td>점검 종료</td></tr>
<tr><td><code>DELAY_START</code></td><td>지연 시작</td></tr>
<tr><td><code>DELAY_END</code></td><td>지연 종료</td></tr>
<tr><td><code>ERROR_START</code></td><td>장애 시작</td></tr>
<tr><td><code>ERROR_END</code></td><td>장애 종료</td></tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- Section 6.5: STEP 4 — 응답 반환 규칙 -->
<section class="oauth2-2legged__step" aria-labelledby="whsig-step4-title">
<span class="oauth2-2legged__eyebrow">STEP 4</span>
<h2 class="oauth2-2legged__h2" id="whsig-step4-title">응답(리턴) 반환 규칙</h2>
<p class="oauth2-2legged__desc">수신 서버가 반환하는 HTTP 상태 코드에 따라 DJBank의 성공 판정과 재시도가 결정됩니다.</p>
<div class="oauth2-2legged__step-grid">
<div class="oauth2-2legged__panel">
<h3 class="oauth2-2legged__panel-title">상태 코드별 처리</h3>
<table class="oauth2-2legged__table">
<thead>
<tr>
<th>반환</th>
<th>상황</th>
<th>DJBank 처리</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="oauth2-2legged__req-badge oauth2-2legged__req-badge--required">2xx</span></td>
<td>검증 성공 + 정상 접수</td>
<td><strong>발송 성공</strong> 기록. 재시도 없음</td>
</tr>
<tr>
<td><code>400</code></td>
<td>필수 헤더 누락</td>
<td>실패 기록 + 재시도</td>
</tr>
<tr>
<td><code>401</code></td>
<td>서명 불일치 / timestamp 만료</td>
<td>실패 기록 + 재시도</td>
</tr>
<tr>
<td><code>5xx</code> · 타임아웃</td>
<td>수신 서버 일시 장애</td>
<td>실패 기록 + 재시도</td>
</tr>
</tbody>
</table>
<p class="oauth2-2legged__warning">⚠ 2xx 이외 응답과 네트워크 오류는 <strong>일정 간격을 두고 재시도</strong>됩니다(기본 3회). 재시도로 인한 중복 수신은 <code>eventId</code> 멱등 처리로 방어하세요.</p>
<h4 class="oauth2-2legged__panel-subtitle">응답 가이드</h4>
<ul class="oauth2-2legged__tips">
<li>검증 통과 시 <strong>즉시 200 OK</strong> 반환 — 무거운 후속 처리는 비동기로 분리</li>
<li>응답 본문 규격은 자유(발송 로그에 기록만 됨) — 간단한 JSON 권장</li>
<li>서명 검증 실패는 <code>401</code>, 필수 헤더 누락은 <code>400</code> 반환 권장</li>
<li>동일 <code>eventId</code> 재수신 시 재처리 없이 200 반환(멱등)</li>
</ul>
</div>
<div class="oauth2-2legged__code-panel">
<span class="oauth2-2legged__code-tag oauth2-2legged__code-tag--ok">200 OK · JSON (권장)</span>
<pre class="oauth2-2legged__code-block"><span class="o2leg-cm"># 정상 접수</span>
HTTP/1.1 <span class="o2leg-g">200 OK</span>
Content-Type: application/json
{
<span class="o2leg-c">"result"</span>: <span class="o2leg-y">"OK"</span>,
<span class="o2leg-c">"eventType"</span>: <span class="o2leg-y">"CONTROL_START"</span>
}
<span class="o2leg-cm"># 서명 검증 실패</span>
HTTP/1.1 <span class="o2leg-g">401 Unauthorized</span>
{
<span class="o2leg-c">"result"</span>: <span class="o2leg-y">"ERROR"</span>,
<span class="o2leg-c">"message"</span>: <span class="o2leg-y">"서명 검증에 실패하였습니다."</span>
}
<span class="o2leg-cm"># 필수 헤더 누락</span>
HTTP/1.1 <span class="o2leg-g">400 Bad Request</span>
{
<span class="o2leg-c">"result"</span>: <span class="o2leg-y">"ERROR"</span>,
<span class="o2leg-c">"message"</span>: <span class="o2leg-y">"필수 헤더가 누락되었습니다."</span>
}</pre>
</div>
</div>
</section>
<!-- Section 7: 검증 실패 대표 원인 -->
<section class="oauth2-2legged__errors" aria-labelledby="whsig-errors-title">
<span class="oauth2-2legged__eyebrow">TROUBLESHOOTING</span>
<h2 class="oauth2-2legged__h2" id="whsig-errors-title">서명 불일치 대표 원인</h2>
<div class="oauth2-2legged__panel">
<table class="oauth2-2legged__table oauth2-2legged__table--errors">
<thead>
<tr>
<th>원인</th>
<th>증상</th>
<th>해결 가이드</th>
</tr>
</thead>
<tbody>
<tr>
<td>본문 재직렬화</td>
<td>JSON 파싱 후 다시 문자열화한 값으로 서명 계산</td>
<td>파싱 전 raw body(bytes)로 계산</td>
</tr>
<tr>
<td>hex 대소문자</td>
<td>대문자 hex로 비교해 불일치</td>
<td>소문자 hex 사용</td>
</tr>
<tr>
<td>접두어 처리</td>
<td><code>sha256=</code> 접두 포함/제외 불일치</td>
<td>양쪽 모두 접두 포함 후 비교</td>
</tr>
<tr>
<td>인코딩</td>
<td>Secret/본문을 UTF-8 외로 인코딩</td>
<td>키·메시지 모두 UTF-8 bytes</td>
</tr>
<tr>
<td>Secret 불일치</td>
<td>재발급 후 이전 Secret 사용</td>
<td>최신 Secret으로 교체</td>
</tr>
<tr>
<td>재전송</td>
<td>동일 이벤트 중복 수신</td>
<td>timestamp 검사 + eventId 멱등 처리</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Section 8: CTA -->
<a class="oauth2-2legged__cta" th:href="@{/webhook}">
<div class="oauth2-2legged__cta-body">
<span class="oauth2-2legged__cta-eyebrow">MANAGE</span>
<h2 class="oauth2-2legged__cta-title">Webhook 관리로 가기</h2>
<p class="oauth2-2legged__cta-desc">수신 URL·Secret·구독 이벤트를 등록하고 관리하세요.</p>
<span class="oauth2-2legged__cta-button">Webhook 관리 →</span>
</div>
<span class="oauth2-2legged__cta-deco oauth2-2legged__cta-deco--lg" aria-hidden="true"></span>
<span class="oauth2-2legged__cta-deco oauth2-2legged__cta-deco--sm" aria-hidden="true"></span>
</a>
</section>
</th:block>
</body>
<th:block layout:fragment="contentScript">
</th:block>
</html>
@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 관리</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="webhook-container">
<div class="webhook-empty">
<div class="empty-icon">🔔</div>
<h3>등록된 Webhook이 없습니다</h3>
<p>API 서비스의 점검·지연·장애 알림을 받을 Webhook을 신청해보세요.</p>
<div class="webhook-empty-action" sec:authorize="hasRole('ROLE_API_KEY_REQUEST')">
<button type="button" class="btn-webhook-create" id="requestWebhook">
Webhook 신청
</button>
</div>
<p class="field-help" sec:authorize="!hasRole('ROLE_API_KEY_REQUEST')">
Webhook 신청은 법인 관리자만 가능합니다. 기관 관리자에게 문의하세요.
</p>
<p class="webhook-guide-link">
<a th:href="@{/service/webhook-dev-guide}">
📘 웹훅 개발가이드 — 수신·서명검증·응답 규칙 보러가기
</a>
</p>
</div>
</section>
</th:block>
<th:block layout:fragment="contentScript">
<script th:inline="javascript">
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('requestWebhook');
if (btn) {
btn.addEventListener('click', function () {
window.location.href = '/webhook/register/step1?clear=true';
});
}
});
</script>
</th:block>
</body>
</html>
@@ -0,0 +1,171 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 관리</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="webhook-container">
<div class="webhook-card" th:object="${webhook}">
<div class="webhook-card-head">
<h3>등록된 Webhook</h3>
<span class="webhook-created" th:if="*{createdDate != null and #strings.length(createdDate) >= 8}"
th:text="|등록일 ${#strings.substring(webhook.createdDate,0,4)}-${#strings.substring(webhook.createdDate,4,6)}-${#strings.substring(webhook.createdDate,6,8)}|">등록일</span>
</div>
<div class="webhook-card-row">
<span class="row-label">수신 URL</span>
<span class="row-value" th:text="*{targetUrl}">https://...</span>
</div>
<div class="webhook-card-row">
<span class="row-label">알림 이벤트</span>
<span class="row-value">
<span class="eventtype-badge" th:each="et : *{eventTypes}" th:text="${et.name}">이벤트</span>
</span>
</div>
<div class="webhook-card-row">
<span class="row-label">대상 API</span>
<span class="row-value">
<span class="api-badge" th:each="apiId : *{apiIds}" th:text="${apiId}">API</span>
</span>
</div>
<div class="webhook-card-row">
<span class="row-label">Secret Key</span>
<span class="row-value secret-row">
<code id="secretMasked" th:text="*{secretMasked}">••••••••</code>
<th:block sec:authorize="hasRole('ROLE_API_KEY_REQUEST')">
<button type="button" class="btn-mini" id="btnRevealSecret">조회</button>
<button type="button" class="btn-mini" id="btnRegenSecret">재발급</button>
</th:block>
</span>
</div>
<div class="webhook-card-actions" sec:authorize="hasRole('ROLE_API_KEY_REQUEST')">
<a class="btn-webhook-next" th:href="@{/webhook/modify/step1}">수정</a>
<button type="button" class="btn-webhook-danger" id="btnDeleteWebhook">삭제</button>
</div>
</div>
<p class="webhook-guide-link">
<a th:href="@{/service/webhook-dev-guide}">
📘 웹훅 개발가이드 — 수신·서명검증·응답 규칙 보러가기
</a>
</p>
</section>
<!-- 비밀번호 재인증 모달 -->
<div class="webhook-modal" id="pwModal" style="display:none;">
<div class="webhook-modal-box">
<h4 id="pwModalTitle">비밀번호 확인</h4>
<p id="pwModalDesc">계속하려면 비밀번호를 입력하세요.</p>
<input type="password" id="pwModalInput" placeholder="비밀번호" autocomplete="current-password">
<p class="field-error" id="pwModalError" style="display:none;"></p>
<div class="webhook-modal-actions">
<button type="button" class="btn-webhook-cancel" id="pwModalCancel">취소</button>
<button type="button" class="btn-webhook-next" id="pwModalConfirm">확인</button>
</div>
</div>
</div>
</th:block>
<th:block layout:fragment="contentScript">
<script th:inline="javascript">
document.addEventListener('DOMContentLoaded', function () {
var csrfToken = document.querySelector('meta[name="_csrf"]');
var csrfHeaderMeta = document.querySelector('meta[name="_csrf_header"]');
var CSRF_TOKEN = csrfToken ? csrfToken.getAttribute('content') : '';
var CSRF_HEADER = csrfHeaderMeta ? csrfHeaderMeta.getAttribute('content') : 'X-XSRF-TOKEN';
var modal = document.getElementById('pwModal');
var input = document.getElementById('pwModalInput');
var errorEl = document.getElementById('pwModalError');
var titleEl = document.getElementById('pwModalTitle');
var descEl = document.getElementById('pwModalDesc');
var pendingAction = null;
function openModal(title, desc, action) {
titleEl.textContent = title;
descEl.textContent = desc;
input.value = '';
errorEl.style.display = 'none';
pendingAction = action;
modal.style.display = 'flex';
input.focus();
}
function closeModal() { modal.style.display = 'none'; pendingAction = null; }
document.getElementById('pwModalCancel').addEventListener('click', closeModal);
document.getElementById('pwModalConfirm').addEventListener('click', function () {
if (pendingAction) { pendingAction(input.value); }
});
input.addEventListener('keyup', function (e) {
if (e.key === 'Enter' && pendingAction) { pendingAction(input.value); }
});
function post(url, password) {
var headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
headers[CSRF_HEADER] = CSRF_TOKEN;
return fetch(url, {
method: 'POST',
headers: headers,
body: 'password=' + encodeURIComponent(password)
}).then(function (r) { return r.json(); });
}
function showError(msg) { errorEl.textContent = msg; errorEl.style.display = 'block'; }
// Secret 조회
var btnReveal = document.getElementById('btnRevealSecret');
if (btnReveal) btnReveal.addEventListener('click', function () {
openModal('Secret 조회', '비밀번호 확인 후 Secret Key를 표시합니다.', function (pw) {
post('/webhook/verify-secret', pw).then(function (res) {
if (res.success) {
document.getElementById('secretMasked').textContent = res.secret;
closeModal();
} else { showError(res.message || '실패했습니다.'); }
}).catch(function () { showError('요청 처리 중 오류가 발생했습니다.'); });
});
});
// Secret 재발급
var btnRegen = document.getElementById('btnRegenSecret');
if (btnRegen) btnRegen.addEventListener('click', function () {
openModal('Secret 재발급',
'재발급 시 기존 Secret은 즉시 무효화됩니다. 새 Secret을 수신 서버의 Webhook 서명검증에 반영하지 않으면 이후 발송되는 모든 Webhook의 서명 검증이 실패합니다. 계속하려면 비밀번호를 입력하세요.',
function (pw) {
post('/webhook/regenerate-secret', pw).then(function (res) {
if (res.success) {
document.getElementById('secretMasked').textContent = res.secret;
closeModal();
alert('Secret이 재발급되었습니다.\n반드시 수신 서버의 서명검증 Secret을 새 값으로 교체하세요.\n교체 전까지 Webhook 서명 검증이 실패합니다.');
} else { showError(res.message || '실패했습니다.'); }
}).catch(function () { showError('요청 처리 중 오류가 발생했습니다.'); });
});
});
// 삭제
var btnDelete = document.getElementById('btnDeleteWebhook');
if (btnDelete) btnDelete.addEventListener('click', function () {
openModal('Webhook 삭제', '삭제하면 복구할 수 없습니다. 계속하려면 비밀번호를 입력하세요.', function (pw) {
post('/webhook/delete', pw).then(function (res) {
if (res.success) { window.location.href = '/webhook'; }
else { showError(res.message || '실패했습니다.'); }
}).catch(function () { showError('요청 처리 중 오류가 발생했습니다.'); });
});
});
});
</script>
</th:block>
</body>
</html>
@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 수정</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="webhook-container webhook-register">
<div class="webhook-steps" th:with="cur=${currentStep}">
<div class="webhook-step" th:classappend="${cur >= 1} ? 'active'">
<span class="step-no">1</span><span class="step-label">기본 정보</span>
</div>
<div class="webhook-step" th:classappend="${cur >= 2} ? 'active'">
<span class="step-no">2</span><span class="step-label">API 선택</span>
</div>
<div class="webhook-step" th:classappend="${cur >= 3} ? 'active'">
<span class="step-no">3</span><span class="step-label">완료</span>
</div>
</div>
<form id="modifyStep1Form" method="post" th:action="@{/webhook/modify/step1}" th:object="${webhookModification}">
<div class="webhook-field">
<label for="targetUrl">Webhook 수신 URL <span class="req">*</span></label>
<input type="text" id="targetUrl" th:field="*{targetUrl}"
placeholder="https://example.com/webhook" autocomplete="off">
<p class="field-error" th:if="${#fields.hasErrors('targetUrl')}" th:errors="*{targetUrl}">URL 오류</p>
<p class="field-help">이벤트 발생 시 이 URL로 서명된 POST 요청이 전송됩니다.</p>
</div>
<div class="webhook-field">
<label>알림 받을 이벤트 <span class="req">*</span></label>
<div class="webhook-eventtype-list">
<label class="eventtype-item" th:each="et : ${eventTypes}">
<input type="checkbox" name="eventTypes" th:value="${et.code}"
th:checked="${#lists.contains(webhookModification.eventTypes, et.code)}">
<span class="eventtype-name" th:text="${et.name}">이벤트명</span>
<span class="eventtype-code" th:text="${et.code}">CODE</span>
</label>
</div>
<p class="field-error" th:if="${#fields.hasErrors('eventTypes')}" th:errors="*{eventTypes}">이벤트 오류</p>
</div>
<div class="webhook-actions">
<a class="btn-webhook-cancel" th:href="@{/webhook/modify/cancel}">취소</a>
<button type="submit" class="btn-webhook-next">다음</button>
</div>
</form>
</section>
</th:block>
</body>
</html>
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 관리</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="apikey-register-container">
<!-- Title Bar -->
<div class="common-title-bar">
<h2 class="common-title">Webhook 수정</h2>
<span class="common-subtitle">알림 받을 API 구성을 변경해주세요.</span>
</div>
<!-- Progress Indicator -->
<div class="register-progress">
<div class="progress-steps">
<div class="progress-step-item">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step1.png}" alt="기본 정보" width="36" height="36">
</div>
</div>
<div class="step-label">기본 정보</div>
</div>
<div class="step-dots">
<span></span><span></span><span></span>
</div>
<div class="progress-step-item active">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step2.png}" alt="API 선택" width="36" height="36">
</div>
</div>
<div class="step-label">API 선택</div>
</div>
<div class="step-dots">
<span></span><span></span><span></span>
</div>
<div class="progress-step-item">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step3.png}" alt="수정 완료" width="36" height="36">
</div>
</div>
<div class="step-label">수정 완료</div>
</div>
</div>
</div>
<p class="webhook-field-error" th:if="${error}" th:text="${error}"></p>
<!-- API 선택 공용 모듈 -->
<th:block th:replace="~{fragment/api_selector :: apiSelector(${apiServices}, ${webhookModification.selectedApis}, '/webhook/modify/step2', '/webhook/modify/step2/save')}"/>
<!-- Form Actions -->
<div class="form-actions">
<button type="button" id="btnPrevStep" class="btn-submit btn-secondary">
이전
</button>
<button type="submit" form="apiSelectorForm" class="btn-submit btn-primary">
수정 완료
</button>
</div>
</section>
</th:block>
</body>
</html>
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 수정 완료</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="webhook-container webhook-register">
<div class="webhook-steps">
<div class="webhook-step active"><span class="step-no">1</span><span class="step-label">기본 정보</span></div>
<div class="webhook-step active"><span class="step-no">2</span><span class="step-label">API 선택</span></div>
<div class="webhook-step active"><span class="step-no">3</span><span class="step-label">완료</span></div>
</div>
<div class="webhook-complete">
<div class="complete-icon"></div>
<h3>Webhook 설정이 수정되었습니다</h3>
<p class="field-help">Secret Key는 변경되지 않았습니다.</p>
<div class="webhook-actions center">
<a class="btn-webhook-next" th:href="@{/webhook}">완료</a>
</div>
</div>
</section>
</th:block>
</body>
</html>
@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 신청</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="webhook-container webhook-register">
<!-- 진행 표시 -->
<div class="webhook-steps" th:with="cur=${currentStep}">
<div class="webhook-step" th:classappend="${cur >= 1} ? 'active'">
<span class="step-no">1</span><span class="step-label">기본 정보</span>
</div>
<div class="webhook-step" th:classappend="${cur >= 2} ? 'active'">
<span class="step-no">2</span><span class="step-label">API 선택</span>
</div>
<div class="webhook-step" th:classappend="${cur >= 3} ? 'active'">
<span class="step-no">3</span><span class="step-label">완료</span>
</div>
</div>
<form id="registerStep1Form" method="post" th:action="@{/webhook/register/step1}" th:object="${webhookRegistration}">
<div class="webhook-field">
<label for="targetUrl">Webhook 수신 URL <span class="req">*</span></label>
<input type="text" id="targetUrl" th:field="*{targetUrl}"
placeholder="https://example.com/webhook" autocomplete="off">
<p class="field-error" th:if="${#fields.hasErrors('targetUrl')}" th:errors="*{targetUrl}">URL 오류</p>
<p class="field-help">이벤트 발생 시 이 URL로 서명된 POST 요청이 전송됩니다.</p>
</div>
<div class="webhook-field">
<label>알림 받을 이벤트 <span class="req">*</span></label>
<div class="webhook-eventtype-list">
<label class="eventtype-item" th:each="et : ${eventTypes}">
<input type="checkbox" name="eventTypes" th:value="${et.code}"
th:checked="${#lists.contains(webhookRegistration.eventTypes, et.code)}">
<span class="eventtype-name" th:text="${et.name}">이벤트명</span>
<span class="eventtype-code" th:text="${et.code}">CODE</span>
</label>
</div>
<p class="field-error" th:if="${#fields.hasErrors('eventTypes')}" th:errors="*{eventTypes}">이벤트 오류</p>
</div>
<div class="webhook-actions">
<a class="btn-webhook-cancel" th:href="@{/webhook/register/cancel}">취소</a>
<button type="submit" class="btn-webhook-next">다음</button>
</div>
</form>
</section>
</th:block>
</body>
</html>
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 관리</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="apikey-register-container">
<!-- Title Bar -->
<div class="common-title-bar">
<h2 class="common-title">Webhook 신청</h2>
<span class="common-subtitle">상태 알림을 받을 API를 선택해주세요.</span>
</div>
<!-- Progress Indicator -->
<div class="register-progress">
<div class="progress-steps">
<div class="progress-step-item">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step1.png}" alt="기본 정보" width="36" height="36">
</div>
</div>
<div class="step-label">기본 정보</div>
</div>
<div class="step-dots">
<span></span><span></span><span></span>
</div>
<div class="progress-step-item active">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step2.png}" alt="API 선택" width="36" height="36">
</div>
</div>
<div class="step-label">API 선택</div>
</div>
<div class="step-dots">
<span></span><span></span><span></span>
</div>
<div class="progress-step-item">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step3.png}" alt="신청 완료" width="36" height="36">
</div>
</div>
<div class="step-label">신청 완료</div>
</div>
</div>
</div>
<p class="webhook-field-error" th:if="${error}" th:text="${error}"></p>
<!-- API 선택 공용 모듈 -->
<th:block th:replace="~{fragment/api_selector :: apiSelector(${apiServices}, ${webhookRegistration.selectedApis}, '/webhook/register/step2', '/webhook/register/step2/save')}"/>
<!-- Form Actions -->
<div class="form-actions">
<button type="button" id="btnPrevStep" class="btn-submit btn-secondary">
이전
</button>
<button type="submit" form="apiSelectorForm" class="btn-submit btn-primary">
신청 완료
</button>
</div>
</section>
</th:block>
</body>
</html>
@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/djbank_title_layout}">
<body>
<section layout:fragment="title">
<div class="page-title-banner">
<img th:src="@{/img/img_title_bg.png}" class="title-image">
<h1>Webhook 관리</h1>
</div>
</section>
<th:block layout:fragment="contentFragment">
<section class="apikey-register-container">
<!-- Title Bar -->
<div class="common-title-bar">
<h2 class="common-title">Webhook 신청</h2>
<span class="common-subtitle">Webhook 등록이 완료되었습니다.</span>
</div>
<!-- Progress Indicator -->
<div class="register-progress">
<div class="progress-steps">
<div class="progress-step-item">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step1.png}" alt="기본 정보" width="36" height="36">
</div>
</div>
<div class="step-label">기본 정보</div>
</div>
<div class="step-dots">
<span></span><span></span><span></span>
</div>
<div class="progress-step-item">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step2.png}" alt="API 선택" width="36" height="36">
</div>
</div>
<div class="step-label">API 선택</div>
</div>
<div class="step-dots">
<span></span><span></span><span></span>
</div>
<div class="progress-step-item active">
<div class="step-icon-wrapper">
<div class="step-icon">
<img th:src="@{/img/apikey_step3.png}" alt="신청 완료" width="36" height="36">
</div>
</div>
<div class="step-label">신청 완료</div>
</div>
</div>
</div>
<div class="webhook-complete">
<div class="complete-icon"></div>
<h3>Webhook이 등록되었습니다</h3>
<p class="field-help">Secret Key는 [Webhook 관리]에서 비밀번호 확인 후 조회할 수 있습니다.</p>
<div class="webhook-actions center">
<a class="btn-webhook-next" th:href="@{/webhook}">완료</a>
</div>
</div>
</section>
</th:block>
</body>
</html>
@@ -0,0 +1,142 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<!--
API 선택 공용 모듈 (사이드바 카테고리 + 검색 + AJAX 카드그리드 + 플로팅 카트 + 선택목록 모달)
사용처: 앱(API Key) 신청/수정 step2, Webhook 신청/수정 step2
파라미터:
apiServices : List<ApiServiceDTO> — 사이드바 카테고리 (컨트롤러 model "apiServices")
selectedApis: List<String> — 세션에 보존된 기선택 API ID 목록
formAction : String — 제출(POST) 경로 (예: '/webhook/register/step2')
saveAction : String — "이전" 버튼 저장(POST) 경로 (예: '/webhook/register/step2/save')
호출 예:
<th:block th:replace="~{fragment/api_selector :: apiSelector(${apiServices}, ${webhookRegistration.selectedApis}, '/webhook/register/step2', '/webhook/register/step2/save')}"/>
주의:
- 폼 id는 고정 "apiSelectorForm" — 제출 버튼은 form="apiSelectorForm" 으로 연결.
- "이전" 버튼은 호출 페이지에 id="btnPrevStep" 으로 두면 모듈 JS가 saveAction 으로 저장 후 이동.
- 추가 hidden 필드가 필요하면 호출 페이지에서 form="apiSelectorForm" 속성으로 주입.
- API 목록은 GET /apis/for_request (ROLE_API_KEY_REQUEST) AJAX 로 로드.
- 스타일은 기존 _apikey-register.scss (.register-form-container / .api-selection-card-grid / .modal-dialog .api-pill) 재사용.
-->
<th:block th:fragment="apiSelector(apiServices, selectedApis, formAction, saveAction)">
<!-- Form Content with Sidebar Layout -->
<div class="register-form-container with-sidebar">
<!-- Sidebar Navigation -->
<aside class="apikey-register-sidebar" id="apiSidebar">
<nav class="apikey-sidebar-nav">
<div class="sidebar-title">API 서비스 목록</div>
<!-- All APIs -->
<div class="menu-section">
<div class="menu-title active" data-group="">
<span class="menu-text">전체</span>
<span class="api-count"></span>
</div>
</div>
<!-- Service Categories -->
<div class="menu-section" th:each="service : ${apiServices}">
<div class="menu-title" th:data-group="${service.id}">
<span class="menu-text" th:text="${service.groupName}">서비스명</span>
<span class="api-count"></span>
</div>
</div>
</nav>
</aside>
<!-- Mobile Menu Toggle -->
<button class="apikey-mobile-toggle" id="mobileToggle" aria-label="메뉴 열기" type="button">
</button>
<!-- Mobile Overlay -->
<div class="apikey-mobile-overlay" id="mobileOverlay"></div>
<!-- Main Content -->
<main class="apikey-register-content">
<form id="apiSelectorForm" method="post" th:action="@{${formAction}}" class="register-form"
th:attr="data-save-action=@{${saveAction}}">
<!-- Search Box with Select All -->
<div class="api-filter-header">
<div class="select-all-wrapper" id="selectAllWrapper" style="display: none;">
<label class="select-all-label">
<input type="checkbox" id="selectAllCheckbox" class="select-all-checkbox visually-hidden">
<span class="custom-checkbox"></span>
<span id="selectAllText">전체 선택</span>
</label>
</div>
<div class="api-search-box">
<input type="text"
id="apiSearch"
class="search-input"
placeholder="API 검색...">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.23047 0C14.3285 0 18.4618 4.0539 18.4619 9.05469C18.4619 11.1083 17.7634 13.0014 16.5889 14.5205C16.5913 14.5229 16.5942 14.5249 16.5967 14.5273L19.5498 17.4238C20.1502 18.0131 20.1501 18.9683 19.5498 19.5576C18.949 20.147 17.9748 20.147 17.374 19.5576L14.4209 16.6621C14.3966 16.6383 14.3749 16.6119 14.3525 16.5869C12.8868 17.5478 11.1257 18.1094 9.23047 18.1094C4.13258 18.1092 0 14.0554 0 9.05469C0.000110268 4.05404 4.13265 0.000222701 9.23047 0ZM9.23047 3.01855C5.83201 3.01878 3.07726 5.721 3.07715 9.05469C3.07715 12.3885 5.83194 15.0916 9.23047 15.0918C12.6292 15.0918 15.3848 12.3886 15.3848 9.05469C15.3847 5.72086 12.6291 3.01855 9.23047 3.01855Z" fill="#515961"/>
</svg>
</div>
</div>
<!-- API Cards Grid -->
<div class="api-selection-card-grid" id="apiCardGrid">
<div class="loading-state" id="loadingState" style="grid-column: 1 / -1;">
<div class="loading-spinner"></div>
<p>API 목록을 불러오는 중...</p>
</div>
<div class="empty-api-state" id="emptyState" style="display: none; grid-column: 1 / -1;">
<div class="empty-icon">📦</div>
<h3>API를 선택해주세요</h3>
<p>왼쪽 메뉴에서 서비스를 선택하면 해당 API 목록이 표시됩니다.</p>
</div>
</div>
</form>
</main>
</div>
<!-- Floating Cart Button -->
<button type="button" class="floating-cart-btn" id="floatingCartBtn" style="display: none;">
<span class="cart-label">선택된 API</span>
<span class="cart-badge" id="cartBadge">
<span class="cart-count">0</span>
<span class="cart-unit"></span>
</span>
</button>
<!-- Selected APIs Modal -->
<div class="modal" id="selectedApisModal" style="display: none;">
<div class="modal-backdrop" id="modalOverlay"></div>
<div class="modal-dialog">
<div class="modal-header">
<h3 class="modal-title">선택된 API 목록</h3>
<button type="button" class="modal-close" id="modalCloseBtn">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div class="modal-body">
<div class="selected-apis-list" id="modalSelectedList"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" id="modalCancelBtn">닫기</button>
</div>
</div>
</div>
<!-- 모듈 초기 데이터 + 스크립트 -->
<script th:inline="javascript">
window.API_SELECTOR_SELECTED = /*[[${selectedApis}]]*/ [];
</script>
<script th:src="@{/js/api-selector.js}"></script>
</th:block>
</body>
</html>
@@ -44,6 +44,7 @@
<li><a th:href="@{/service/intro}">API 포탈 소개</a></li>
<li><a th:href="@{/service/guide}">회원가입 안내</a></li>
<li><a th:href="@{/service/oauth2-guide}">OAuth2 개발가이드</a></li>
<li><a th:href="@{/service/webhook-dev-guide}">웹훅 개발가이드</a></li>
</ul>
</li>
<li><a href="/apis" class="nav-link">오픈 API</a></li>
@@ -93,6 +94,7 @@
<li sec:authorize="hasRole('ROLE_APP')">
<a th:href="@{/myapikey}"><i class="fas fa-key"></i>인증 키 관리</a>
<a th:href="@{/statistics/api}"><i class="fas fa-chart-bar"></i>이용 통계</a>
<a th:href="@{/webhook}"><i class="fas fa-bell"></i>Webhook 관리</a>
</li>
<li><a th:href="@{/mypage}"><i class="fas fa-user-circle"></i>내 정보 관리</a></li>
<li><a th:href="@{/change_password}"><i class="fas fa-lock"></i>비밀번호 변경</a></li>
@@ -205,6 +207,7 @@
<li><a th:href="@{/service/intro}">API 포탈 소개</a></li>
<li><a th:href="@{/service/guide}">회원가입 안내</a></li>
<li><a th:href="@{/service/oauth2-guide}">OAuth2 개발가이드</a></li>
<li><a th:href="@{/service/webhook-dev-guide}">웹훅 개발가이드</a></li>
</ul>
</li>
@@ -248,7 +251,7 @@
<li sec:authorize="hasRole('ROLE_USER_MANAGER')"><a th:href="@{/users}">이용자 관리</a></li>
<li sec:authorize="hasRole('ROLE_APP')"><a th:href="@{/myapikey}">인증 키 관리</a></li>
<li sec:authorize="hasRole('ROLE_APP')"><a th:href="@{/statistics/api}">이용 통계</a></li>
<li sec:authorize="hasRole('ROLE_APP')"><a th:href="@{/commission/manage}">과금 관리</a></li>
<li sec:authorize="hasRole('ROLE_APP')"><a th:href="@{/webhook}">Webhook 관리</a></li>
<li><a th:href="@{/mypage}">내 정보 관리</a></li>
<li><a th:href="@{/change_password}">비밀번호 변경</a></li>
</ul>