From f7ce249aa79749dacf8367b16a1b4be343789f31 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 12 Mar 2026 09:36:09 +0900 Subject: [PATCH] =?UTF-8?q?260312=5F01=5FENH:=20Error=20=ED=8E=98=EC=9D=B4?= =?UTF-8?q?=EC=A7=80=20=EB=B0=8F=20Redirect=20=ED=8E=98=EC=9D=B4=EC=A7=80?= =?UTF-8?q?=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/IntelliLang.xml | 87 ++++++++++ .idea/misc.xml | 1 - next.config.ts | 17 ++ src/app/(pages)/login/page.tsx | 2 +- src/app/(pages)/redirect/[slug]/page.tsx | 37 ++++ src/app/(pages)/redirect/error/page.tsx | 35 ++++ src/app/api/external/[[...slug]]/route.ts | 43 ++++- src/app/not-found.tsx | 9 + src/components/external/Error.tsx | 116 +++++++++++++ src/components/external/ExternalLayout.tsx | 61 +++++++ src/components/external/RedirectLanding.tsx | 177 ++++++++++++++++++++ src/const/commonConst.ts | 6 +- src/lib/http-client.ts | 3 +- src/lib/utils.ts | 32 +++- src/middleware.ts | 12 ++ src/middleware/catchRedirectPageLanding.ts | 75 +++++++++ src/types/common.ts | 3 + 17 files changed, 710 insertions(+), 6 deletions(-) create mode 100644 .idea/IntelliLang.xml create mode 100644 src/app/(pages)/redirect/[slug]/page.tsx create mode 100644 src/app/(pages)/redirect/error/page.tsx create mode 100644 src/app/not-found.tsx create mode 100644 src/components/external/Error.tsx create mode 100644 src/components/external/ExternalLayout.tsx create mode 100644 src/components/external/RedirectLanding.tsx create mode 100644 src/middleware.ts create mode 100644 src/middleware/catchRedirectPageLanding.ts diff --git a/.idea/IntelliLang.xml b/.idea/IntelliLang.xml new file mode 100644 index 0000000..993cf38 --- /dev/null +++ b/.idea/IntelliLang.xml @@ -0,0 +1,87 @@ + + + + + Spring @Cacheable and @CacheEvict + + + + + + + + + + + + Spring HttpHeaders (org.springframework.http) + + + + + + + Spring Integration/Messaging + + + + + + + Spring JDBC (org.springframework.jdbc.core.JdbcOperations) + + + + + + + + + + + + + + + + Spring JDBC (org.springframework.jdbc.core.PreparedStatementCreatorFactory) + + + + + + + Spring JDBC (org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator) + + + + + + + + Spring Security @PostAuthorize/@PostFilter/@PreAuthorize/@PreFilter/@AuthenticationPrincipal + + + + + + + + + + Spring State Machine + + + + + + + + SpEL for Spring Cache + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 639900d..6e86672 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,3 @@ - diff --git a/next.config.ts b/next.config.ts index d9b9028..e55cbaf 100644 --- a/next.config.ts +++ b/next.config.ts @@ -13,6 +13,23 @@ const nextConfig: NextConfig = { }, ]; }, + + async headers() { + return [ + { + source: "/api/external/:path*", + headers: [ + {key: "Access-Control-Allow-Credentials", value: "true"}, + {key: "Access-Control-Allow-Origin", value: "*"}, + {key: "Access-Control-Allow-Methods", value: "GET,POST,PUT,PATCH,DELETE"}, + { + key: "Access-Control-Allow-Headers", + value: "Content-Type, Authorization, X-Requested-With", + }, + ], + }, + ] + }, }; export default nextConfig; diff --git a/src/app/(pages)/login/page.tsx b/src/app/(pages)/login/page.tsx index 2947ba5..6305a90 100644 --- a/src/app/(pages)/login/page.tsx +++ b/src/app/(pages)/login/page.tsx @@ -45,7 +45,7 @@ const LoginPage = () => { const err = apiError(e); if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요."); else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요."); - else setError(`로그인에 실패했습니다. (status: ${err.status})`); + else setError(`로그인에 실패했습니다. (${err.message})`); } } diff --git a/src/app/(pages)/redirect/[slug]/page.tsx b/src/app/(pages)/redirect/[slug]/page.tsx new file mode 100644 index 0000000..6b64bb9 --- /dev/null +++ b/src/app/(pages)/redirect/[slug]/page.tsx @@ -0,0 +1,37 @@ +import RedirectLanding from "@/components/external/RedirectLanding"; +import {notFound} from "next/navigation"; +import {ALLOW_REDIRECT} from "@/const/commonConst"; +import {RedirectSlug} from "@/types/common"; + +type redirectPageProps = { + params: Promise<{ slug: string }>; + searchParams?: Promise>; +} + +const toRedirectSlug = (slug: string): RedirectSlug | null => { + return ALLOW_REDIRECT.has(slug.toLowerCase()) ? (slug.toLowerCase() as RedirectSlug) : null; +} + +const redirectPage = async ({ + params, + searchParams, + }: redirectPageProps) => { + const { slug } = await params; + const sp = searchParams ? await searchParams : undefined; + + //미들 웨어에서 처리 + console.log(sp); + + const redirectSlug = toRedirectSlug(slug); + + console.log(redirectSlug); + + + if (!redirectSlug) notFound(); + + return ( + + ) +} + +export default redirectPage; \ No newline at end of file diff --git a/src/app/(pages)/redirect/error/page.tsx b/src/app/(pages)/redirect/error/page.tsx new file mode 100644 index 0000000..d1a2df8 --- /dev/null +++ b/src/app/(pages)/redirect/error/page.tsx @@ -0,0 +1,35 @@ +import ErrorPage from "@/components/external/Error"; +import {ErrorCode} from "@/types/common"; + +function toErrorCode(raw: string | undefined): ErrorCode { + if (raw === "500") return "500"; + // fetch_error, 기타 알 수 없는 코드 → 500으로 처리 + if (raw && raw !== "404") return "500"; + return "404"; +} + +type RedirectErrorPageProps = { + searchParams: Promise>; +}; + +const RedirectErrorPage = async ({ searchParams }: RedirectErrorPageProps) => { + const sp = await searchParams; + + console.log(sp) + + const code = toErrorCode(sp.code as string | undefined); + const sid = (sp.sid as string | undefined) ?? ""; + + return ( + + ) +} + +export default RedirectErrorPage \ No newline at end of file diff --git a/src/app/api/external/[[...slug]]/route.ts b/src/app/api/external/[[...slug]]/route.ts index 45fc9a6..3f64d11 100644 --- a/src/app/api/external/[[...slug]]/route.ts +++ b/src/app/api/external/[[...slug]]/route.ts @@ -1 +1,42 @@ -//외부 설문에 뎐동 되는 API \ No newline at end of file +//외부 설문에 뎐동 되는 API + +import {NextRequest, NextResponse} from "next/server"; +import {RouteContext} from "@/types/common"; +import {createContactApi} from "@/lib/server-api"; +import {errorToResponse} from "@/lib/http-util"; +import {getClientIp} from "@/lib/utils"; + +export const POST = async (req: NextRequest, context: RouteContext) => { + try { + const { searchParams } = new URL(req.url); + const {slug = []} = await context.params; + const [action] = slug; + + console.log(slug) + const sid = (searchParams.get("sid") ?? "").trim(); + const allowAction = ["start", "complete", "screen", "quota"] + if(slug.length === 1 && allowAction.includes(action.toLowerCase()) && sid.length > 0){ + const contactApi = await createContactApi(); + + const pathname = req.nextUrl.pathname; + const h = req.headers; + const log = { + remoteAddr: h.get("x-orig-ip") || getClientIp(req), + uri: h.get("x-orig-uri") || pathname, + url: h.get("x-orig-url") || req.url, + userAgent: h.get("x-orig-user-agent") || h.get("user-agent"), + referer: h.get("x-orig-referer") || h.get("referer"), + origin: h.get("x-orig-origin") || h.get("origin"), + xForwardedFor: h.get("x-forwarded-for"), + forwarded: h.get("forwarded"), + }; + + //Todo 수정 필요 + return new NextResponse(null, { status: 204 }); + } + + return NextResponse.json({ message: "Not found" }, { status: 404 }); + } catch (error: unknown) { + return errorToResponse(error); + } +}; \ No newline at end of file diff --git a/src/app/not-found.tsx b/src/app/not-found.tsx new file mode 100644 index 0000000..cb66a60 --- /dev/null +++ b/src/app/not-found.tsx @@ -0,0 +1,9 @@ +import ErrorPage from "@/components/external/Error"; + +const NotFound = () => { + return ( + + ) +} + +export default NotFound \ No newline at end of file diff --git a/src/components/external/Error.tsx b/src/components/external/Error.tsx new file mode 100644 index 0000000..6276be2 --- /dev/null +++ b/src/components/external/Error.tsx @@ -0,0 +1,116 @@ +import { ServerCrash, FileQuestion } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { Separator } from "@/components/ui/separator"; +import ExternalLayout from "@/components/external/ExternalLayout"; +import {ErrorCode} from "@/types/common"; + + +interface ErrorConfig { + httpLabel: string; + defaultTitle: string; + defaultDescription: string; + Icon: React.ElementType; + badgeVariant: "default" | "destructive" | "outline" | "secondary"; + accentClass: string; +} + +// ─── Error Configs ──────────────────────────────────────────────────────────── +const ERROR_MAP: Record = { + "404": { + httpLabel: "Page Not Found", + defaultTitle: "요청하신 페이지를 찾을 수 없습니다", + defaultDescription: + "입력하신 주소가 잘못되었거나, 페이지가 삭제 또는 이동되었을 수 있습니다", + Icon: FileQuestion, + badgeVariant: "secondary", + accentClass: "bg-primary", + }, + "500": { + httpLabel: "Internal Server Error", + defaultTitle: "서버에서 오류가 발생했습니다", + defaultDescription: + "요청을 처리하는 중 예기치 못한 오류가 발생했습니다. 잠시 후 다시 시도해 주세요. 문제가 지속되면 담당자에게 문의해 주세요.", + Icon: ServerCrash, + badgeVariant: "destructive", + accentClass: "bg-destructive", + }, +}; + +interface ErrorViewProps { + code?: ErrorCode; + errorTitle?: string; + errorDescription?: string; +} + +const ErrorPage = ({ + code = "404", + errorTitle, + errorDescription, + }: ErrorViewProps) => { + const config = ERROR_MAP[code] ?? ERROR_MAP["404"]; + const { httpLabel, defaultTitle, defaultDescription, Icon, badgeVariant, accentClass } = config; + + const title = errorTitle ?? defaultTitle; + const description = errorDescription ?? defaultDescription; + + return ( + +
+
+ + {/* 에러 코드 타이포 레이어 */} +
+ {/* 전면 숫자 */} + + {code} + +
+ + {/* 뱃지 */} +
+ + {httpLabel} + + + HTTP {code} + + + KRi Platform + +
+ + + +
+ +

+ {title} +

+
+ +

+ {description} +

+
+
+
+ ); +} + +export default ErrorPage; \ No newline at end of file diff --git a/src/components/external/ExternalLayout.tsx b/src/components/external/ExternalLayout.tsx new file mode 100644 index 0000000..d8e56ab --- /dev/null +++ b/src/components/external/ExternalLayout.tsx @@ -0,0 +1,61 @@ +import React from "react"; +import Image from "next/image"; + +interface ExternalLayoutProps { + children: React.ReactNode; + /** 헤더 우측 영역 (선택) */ + headerRight?: React.ReactNode; + /** 푸터 우측 텍스트 (선택, 기본: "KRi Survey Platform") */ + footerRight?: string; +} + +const ExternalLayout = ( + { + children, + headerRight, + footerRight = "KRi Contact System", + }: ExternalLayoutProps +) => { + return ( +
+ + {/* 상단 컬러 바 */} +
+ + {/* 헤더 */} +
+ KRi + {headerRight ?? ( + + KRi Contact System + + )} +
+ + {/* 콘텐츠 */} +
+ {children} +
+ + {/* 푸터 */} +
+ + © {new Date().getFullYear()} KRi. All rights reserved. + + + {footerRight} + +
+ +
+ ); +} + +export default ExternalLayout \ No newline at end of file diff --git a/src/components/external/RedirectLanding.tsx b/src/components/external/RedirectLanding.tsx new file mode 100644 index 0000000..eb3e2ad --- /dev/null +++ b/src/components/external/RedirectLanding.tsx @@ -0,0 +1,177 @@ +import { CheckCircle, XCircle, Users } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { Card, CardContent, CardHeader } from "@/components/ui/card"; +import { Separator } from "@/components/ui/separator"; +import ExternalLayout from "./ExternalLayout"; +import {RedirectSlug} from "@/types/common"; + +interface StatusConfig { + label: string; + sublabel: string; + title: string; + description: string; + Icon: React.ElementType; + badgeVariant: "default" | "secondary" | "destructive" | "outline"; + iconClassName: string; + savedVisible: boolean; +} + +// ─── Status Configs ─────────────────────────────────────────────────────────── +const STATUS_MAP: Record = { + complete: { + label: "설문 완료", + sublabel: "Survey Complete", + title: "설문에 참여해 주셔서\n감사합니다", + description: + "귀하의 소중한 의견이 성공적으로 접수되었습니다. 응답 결과는 연구 목적으로만 활용되며, 개인 정보는 철저히 보호됩니다.", + Icon: CheckCircle, + badgeVariant: "default", + iconClassName: "text-primary", + savedVisible: true, + }, + screen: { + label: "참여 불가", + sublabel: "Screen Out", + title: "이번 설문에는\n참여하실 수 없습니다", + description: + "현재 진행 중인 설문은 특정 조건에 맞는 응답자를 대상으로 합니다. 귀하의 프로필이 이번 조사의 대상과 맞지 않아 참여가 제한되었습니다.", + Icon: XCircle, + badgeVariant: "outline", + iconClassName: "text-muted-foreground", + savedVisible: false, + }, + quota: { + label: "할당 초과", + sublabel: "Quota Full", + title: "모집 인원이\n마감되었습니다", + description: + "해당 설문의 목표 응답 수가 충족되어 더 이상 참여가 불가합니다. 참여 의사를 가져주신 데 감사드리며, 다른 설문 기회를 기대해 주세요.", + Icon: Users, + badgeVariant: "outline", + iconClassName: "text-muted-foreground", + savedVisible: false, + }, +}; + +const InfoRow = ({ + label, + value, + mono = false, + }: { + label: string; + value: React.ReactNode; + mono?: boolean; +}) => { + return ( +
+ {label} + + {value} + +
+ ); +} + +interface RedirectLandingProps { + redirectSlug: RedirectSlug; + timestamp?: string; +} + +const RedirectLanding = ({ + redirectSlug, + timestamp, + }: RedirectLandingProps) => { + const { + label, + sublabel, + title, + description, + Icon, + badgeVariant, + iconClassName, + savedVisible, + } = STATUS_MAP[redirectSlug]; + + const displayTime = + timestamp ?? + new Date().toLocaleString("ko-KR", { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + + return ( + +
+
+ + {/* 왼쪽: 메시지 */} +
+ + + {sublabel} + + +

+ {title} +

+ + + +

+ {description} +

+
+ + {/* 오른쪽: 카드 */} +
+ + {/* 상태 카드 */} + +
+ +
+ +
+
+ +

+ 최종 상태 +

+

+ {label} +

+
+ + + {/* 상세 정보 */} + + + + + {savedVisible && ( + ✓ 저장 완료} + /> + )} + + +
+
+
+ + ); +} + +export default RedirectLanding; \ No newline at end of file diff --git a/src/const/commonConst.ts b/src/const/commonConst.ts index abae1df..66407ea 100644 --- a/src/const/commonConst.ts +++ b/src/const/commonConst.ts @@ -5,4 +5,8 @@ export const FONT_SIZE = { } as const; export const UNKNOWN_HTTP_ERROR = 'UNKNOWN_HTTP_ERROR'; -export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR'; \ No newline at end of file +export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR'; + +export const ALLOW_REDIRECT = new Set(["complete", "screen", "quota"]); + +export const DEFAULT_API_TIMEOUT_MS = 60_000; \ No newline at end of file diff --git a/src/lib/http-client.ts b/src/lib/http-client.ts index c702916..fd7a1e5 100644 --- a/src/lib/http-client.ts +++ b/src/lib/http-client.ts @@ -1,4 +1,5 @@ import { clientEnv } from "@/lib/env.client"; +import {DEFAULT_API_TIMEOUT_MS} from "@/const/commonConst"; export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; @@ -105,7 +106,7 @@ const isJsonContentType = (ctype: string) => { export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => { const { getToken, - defaultTimeoutMs = 60_000, + defaultTimeoutMs = DEFAULT_API_TIMEOUT_MS, defaultHeaders = { "content-type": "application/json" }, setErrorMessage, } = opts; diff --git a/src/lib/utils.ts b/src/lib/utils.ts index c47db4f..c5b88c3 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,5 +1,6 @@ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" +import type {NextRequest} from "next/server"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) @@ -99,4 +100,33 @@ export const formatKst = ( return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`; }; -export const isBlank = (v?: string | null) => !v || v.trim().length === 0; \ No newline at end of file +export const isBlank = (v?: string | null) => !v || v.trim().length === 0; + +export const getClientIp = (req: NextRequest): string | null => { + const h = req.headers; + + // 가장 흔한 케이스: 프록시/호스팅이 넣어줌 + const xff = h.get("x-forwarded-for"); + if (xff) { + // "client, proxy1, proxy2" 형태. 보통 첫 번째가 client IP로 쓰이지만, + // 프록시가 헤더를 덮어쓰지 않고 append만 하는 환경이면 spoof 가능성 있음. + return xff.split(",")[0].trim(); + } + + // 일부 인프라/프록시에서 쓰는 헤더들 + const xRealIp = h.get("x-real-ip"); + if (xRealIp) return xRealIp.trim(); + + // (Cloudflare 등) 사용 환경이면 + const cf = h.get("cf-connecting-ip"); + if (cf) return cf.trim(); + + // RFC 7239 Forwarded: for=1.2.3.4;proto=https;by=... + const forwarded = h.get("forwarded"); + if (forwarded) { + const m = forwarded.match(/for="?([^;,\s"]+)"?/i); + if (m?.[1]) return m[1]; + } + + return null; +} \ No newline at end of file diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 0000000..3d19742 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,12 @@ +import {NextFetchEvent, NextRequest} from "next/server"; +import {catchRedirectPageLanding} from "@/middleware/catchRedirectPageLanding"; + +export const config = { + matcher: [ + "/redirect/:path*", + ], +} + +export function middleware(req: NextRequest, event: NextFetchEvent) { + return catchRedirectPageLanding(req, event); +} \ No newline at end of file diff --git a/src/middleware/catchRedirectPageLanding.ts b/src/middleware/catchRedirectPageLanding.ts new file mode 100644 index 0000000..bffabbe --- /dev/null +++ b/src/middleware/catchRedirectPageLanding.ts @@ -0,0 +1,75 @@ +import { NextResponse, type NextRequest, type NextFetchEvent } from "next/server"; +import { getClientIp } from "@/lib/utils"; +import {ALLOW_REDIRECT, DEFAULT_API_TIMEOUT_MS} from "@/const/commonConst"; + +export const catchRedirectPageLanding = async (req: NextRequest, event: NextFetchEvent) => { + const pathname = req.nextUrl.pathname; // /redirect/quota + const slug = pathname.split("/")[2] ?? ""; + const search = req.nextUrl.search; + + if(!ALLOW_REDIRECT.has(slug)){ + return NextResponse.next(); + } + + const h = req.headers; + const orig = { + remoteAddr: getClientIp(req), + uri: pathname, + url: req.url, + userAgent: h.get("user-agent"), + referer: h.get("referer"), + origin: h.get("origin"), + xForwardedFor: h.get("x-forwarded-for"), + forwarded: h.get("forwarded"), + }; + + const body = {}; + + const endpoint = new URL(req.url); + endpoint.pathname = `/api/external/${encodeURIComponent(slug)}`; + endpoint.search = search; + + const controller = new AbortController(); + const t = setTimeout(() => controller.abort(), DEFAULT_API_TIMEOUT_MS); + + try { + const res = await fetch(endpoint, { + method: "POST", + headers: { + "content-type": "application/json", + "x-orig-user-agent": orig.userAgent ?? "", + "x-orig-referer": orig.referer ?? "", + "x-orig-origin": orig.origin ?? "", + "x-orig-ip": orig.remoteAddr ?? "", + // (선택) 내부 호출 마커 + "x-internal-log": "1", + }, + body: JSON.stringify(body), + signal: controller.signal, + cache: "no-store", + }); + + if (res.status === 200 || res.status === 204) { + return NextResponse.next(); + } + + // 실패 처리 1) 에러 페이지로 redirect (추천) + const errUrl = new URL("/redirect/error", req.url); + errUrl.searchParams.set("code", String(res.status)); + errUrl.searchParams.set("sid", req.nextUrl.searchParams.get("sid") ?? ""); + return NextResponse.redirect(errUrl, 307); + + // 실패 처리 2) 그냥 에러 응답으로 차단하고 싶으면 아래로 대체 + // const text = await res.text().catch(() => ""); + // return new NextResponse(text || "External API call failed", { status: 502 }); + + } catch (e) { + // 타임아웃/네트워크 오류 등 + const errUrl = new URL("/redirect/error", req.url); + errUrl.searchParams.set("code", "fetch_error"); + errUrl.searchParams.set("sid", req.nextUrl.searchParams.get("sid") ?? ""); + return NextResponse.redirect(errUrl, 307); + } finally { + clearTimeout(t); + } +}; \ No newline at end of file diff --git a/src/types/common.ts b/src/types/common.ts index a9d7e47..81f0b25 100644 --- a/src/types/common.ts +++ b/src/types/common.ts @@ -6,6 +6,9 @@ export type DataVerification = { export type RouteContext = { params: Promise<{ slug?: string[] }> }; +export type ErrorCode = "404" | "500"; +export type RedirectSlug = "complete" | "screen" | "quota"; + export type PageRequest = { pageIndex: number; pageSize: number;