wr: 공통 모듈기반 로그인 변경

This commit is contained in:
2026-07-15 17:22:51 +09:00
parent c8c461e8e8
commit 2eb1809f36
26 changed files with 1301 additions and 380 deletions
+17
View File
@@ -0,0 +1,17 @@
import "@/src/app/styles/base.css";
export const metadata = {
title: "유역하수도 통합 정보플랫폼",
};
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ko">
<body>{children}</body>
</html>
);
}
+2
View File
@@ -0,0 +1,2 @@
import { LoginPage } from "@/src/auth/login";
export default LoginPage;
+3 -3
View File
@@ -6,7 +6,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { LoginApi } from "@/src/entities/auth/api/login-service";
import { authService } from "@/src/entities/auth";
import { CLAIM_NAME } from "@/src/shared/config";
import { getCookie } from "@/src/shared/lib";
@@ -125,7 +125,7 @@ export default function Page() {
const handleSilentRefresh = async () => {
try {
await LoginApi.silentRefresh();
await authService.silentRefresh();
} catch (error) {
console.error("Manual silent refresh failed:", error);
} finally {
@@ -145,7 +145,7 @@ export default function Page() {
) {
isRefreshingRef.current = true;
try {
await LoginApi.silentRefresh();
await authService.silentRefresh();
} catch (error) {
console.error("JWT test silent refresh failed:", error);
}
+87 -106
View File
@@ -1,125 +1,106 @@
/**
* 📄 Proxy Route
* API 프록시 라우트
*
* - 서버 API로의 요청 프록시 처리
* - 쿠키 기반 인증 토큰 및 리프레시 토큰 관리
* - POST 및 PUT 요청 핸들링
* - 사용자 인증 정보 검증 및 응답 처리
* - 에러 핸들링 및 상태 코드 반환
* - 사이트 ID 및 헤더 설정
*/
import {
ACCESS_TOKEN,
AUTH_USER_ID,
CLAIM_NAME,
REFRESH_TOKEN,
SERVER_API_URL,
SITE_ID,
} from "@/src/shared/config";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
const COOKIE_DOMAIN = process.env.NEXT_PUBLIC_COOKIE_DOMAIN;
const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token";
const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL || "";
const SITE_ID = process.env.NEXT_PUBLIC_SITE_ID || "WR";
async function handler(
request: Request,
params: { url: string[] },
method: "GET" | "POST" | "PUT" | "DELETE",
request: Request,
params: { url: string[] },
method: "GET" | "POST" | "PUT" | "DELETE",
) {
const cookieStore = await cookies();
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
};
let body = {};
const isRefreshHandler = params.url.includes("refresh");
const cookieStore = await cookies();
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
};
let body = {};
const isRefreshHandler = params.url.includes("refresh");
// silent refresh
if (isRefreshHandler) {
const refreshToken = cookieStore.get(REFRESH_TOKEN); // "refresh-token"
console.log("refreshToken", refreshToken?.value);
headers[CLAIM_NAME] = refreshToken?.value ?? ""; // "Authorization"
// silent refresh
if (isRefreshHandler) {
const refreshToken = cookieStore.get(REFRESH_TOKEN);
headers[CLAIM_NAME] = refreshToken?.value ?? "";
if (!headers[CLAIM_NAME]) { // "Authorization"
return NextResponse.json({ message: "Can't refresh" }, { status: 401 });
}
}
try {
if (!isRefreshHandler) {
body = await request.json();
if (!headers[CLAIM_NAME]) {
return NextResponse.json(
{ message: "Can't refresh" },
{ status: 401 },
);
}
}
const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, {
method,
headers,
body: JSON.stringify(body),
});
// console.log(result);
if (!result.ok) {
return NextResponse.json(
{ message: "first Invalid Credentials" },
{ status: result.status },
);
try {
if (!isRefreshHandler) {
body = await request.json();
}
const result = await fetch(
`${SERVER_API_URL}/${params.url.join("/")}`,
{
method,
headers,
body: JSON.stringify(body),
},
);
if (!result.ok) {
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
}
const accessToken = result.headers.get(ACCESS_TOKEN);
const refreshToken = result.headers.get(REFRESH_TOKEN);
const userId = result.headers.get(AUTH_USER_ID);
if (accessToken && userId) {
const response = NextResponse.json({
[ACCESS_TOKEN]: accessToken,
[AUTH_USER_ID]: userId,
});
if (refreshToken) {
cookieStore.set(REFRESH_TOKEN, refreshToken, {
httpOnly: true,
sameSite: "lax",
path: "/",
});
}
return response;
}
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
} catch (error) {
return NextResponse.json(
{ message: "Server Error", error },
{ status: 500 },
);
}
const accessToken = result.headers.get(ACCESS_TOKEN); // "access-token"
const refreshToken = result.headers.get(REFRESH_TOKEN); // "refresh-token" 신규 받아온 token
const userId = result.headers.get(AUTH_USER_ID); // "token-id"
if (accessToken && userId) {
const response = NextResponse.json({
[ACCESS_TOKEN]: accessToken,
[AUTH_USER_ID]: userId,
});
if (refreshToken) {
response.cookies.set(REFRESH_TOKEN, refreshToken, {
httpOnly: true,
sameSite: "lax", // 다른 사이트에서 들어오는 모든 요청에 대해 쿠키를 보내지 않는 가장 강력한 설정
domain: getCookieDomain(),
path: "/",
});
console.log("refresh cookie setting : " + refreshToken);
}
return response;
}
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
} catch (error) {
return NextResponse.json(
{ message: "Server Error", error },
{ status: 500 },
);
}
}
export async function POST(
request: Request,
props: { params: Promise<{ url: string[] }> },
request: Request,
props: { params: Promise<{ url: string[] }> },
) {
const params = await props.params;
return handler(request, params, "POST");
const params = await props.params;
return handler(request, params, "POST");
}
export async function PUT(
request: Request,
props: { params: Promise<{ url: string[] }> },
request: Request,
props: { params: Promise<{ url: string[] }> },
) {
const params = await props.params;
return handler(request, params, "PUT");
}
function getCookieDomain(): string | undefined {
if (typeof window === "undefined") return undefined;
if (COOKIE_DOMAIN) return COOKIE_DOMAIN;
const { hostname } = window.location;
if (hostname === "localhost" || hostname === "127.0.0.1") return undefined;
return hostname;
const params = await props.params;
return handler(request, params, "PUT");
}
-2
View File
@@ -1,2 +0,0 @@
import { LoginPage } from "@/src/features/auth/login";
export default LoginPage;
-12
View File
@@ -1,12 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
export async function GET(request: NextRequest) {
const hostname = request.nextUrl.hostname;
const redirectUrl = process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "https://portal.hasuon.or.kr";
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "con.mind-one.co.kr") {
return NextResponse.redirect(new URL("/", request.url)); // 로컬 및 개발 환경
} else {
return NextResponse.redirect(new URL(redirectUrl)); // 공단 환경
}
}