261102_02_ENH: 공용 인증 쿠키 도메인 적용 조건 수정 및 외부 링크 인증 탭별 분리
This commit is contained in:
@@ -1,11 +1,9 @@
|
|||||||
import { cookies } from "next/headers";
|
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
|
|
||||||
export default async function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
export const dynamic = "force-dynamic";
|
||||||
const cookieStore = await cookies();
|
|
||||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
export default function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||||
if (!accessToken) redirect("/logout");
|
// External JWTs live in this tab, so authentication is checked after hydration.
|
||||||
|
// Every BFF/API request still enforces verified server authentication and scope.
|
||||||
return <AppMainLayout>{children}</AppMainLayout>;
|
return <AppMainLayout>{children}</AppMainLayout>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,18 +3,20 @@
|
|||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useLogoutMutation } from "@/query/auth";
|
import { useLogoutMutation } from "@/query/auth";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
|
|
||||||
export default function LogoutPage() {
|
export default function LogoutPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { hydrated } = useAuth();
|
||||||
const logoutMutation = useLogoutMutation();
|
const logoutMutation = useLogoutMutation();
|
||||||
const started = useRef(false);
|
const started = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (started.current) return;
|
if (!hydrated || started.current) return;
|
||||||
started.current = true;
|
started.current = true;
|
||||||
void logoutMutation.mutateAsync().finally(() => router.replace("/login"));
|
void logoutMutation.mutateAsync().finally(() => router.replace("/login"));
|
||||||
}, [logoutMutation, router]);
|
}, [hydrated, logoutMutation, router]);
|
||||||
|
|
||||||
return <LoadingOverlayAdapter force label="로그아웃 중" />;
|
return <LoadingOverlayAdapter force label="로그아웃 중" />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import {
|
import {
|
||||||
bookmarkUpstreamPath,
|
bookmarkUpstreamPath,
|
||||||
isBookmarkCreatePath,
|
isBookmarkCreatePath,
|
||||||
@@ -9,7 +8,6 @@ import {
|
|||||||
isBookmarkListPath,
|
isBookmarkListPath,
|
||||||
} from "@/lib/project-proxy-policy";
|
} from "@/lib/project-proxy-policy";
|
||||||
import { isBookmarkPage, readBookmarkSaveRequest } from "@/types/bookmark";
|
import { isBookmarkPage, readBookmarkSaveRequest } from "@/types/bookmark";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
const notFound = () =>
|
const notFound = () =>
|
||||||
@@ -19,7 +17,7 @@ const unauthorized = () =>
|
|||||||
const badRequest = () =>
|
const badRequest = () =>
|
||||||
NextResponse.json({ message: "북마크 저장 내용을 확인해 주세요." }, { status: 400 });
|
NextResponse.json({ message: "북마크 저장 내용을 확인해 주세요." }, { status: 400 });
|
||||||
const noStore = { headers: { "Cache-Control": "no-store" } };
|
const noStore = { headers: { "Cache-Control": "no-store" } };
|
||||||
const loggedIn = async () => !!(await cookies()).get(CookieKeys.AuthToken)?.value;
|
const loggedIn = async () => !!(await getServerAccessToken());
|
||||||
|
|
||||||
export async function GET(request: NextRequest, context: RouteContext) {
|
export async function GET(request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import {
|
import {
|
||||||
derivedUpstreamPath,
|
derivedUpstreamPath,
|
||||||
isDerivedCreatePath,
|
isDerivedCreatePath,
|
||||||
@@ -9,7 +8,6 @@ import {
|
|||||||
isDerivedListPath,
|
isDerivedListPath,
|
||||||
} from "@/lib/project-proxy-policy";
|
} from "@/lib/project-proxy-policy";
|
||||||
import { readDerivedSaveRequest } from "@/types/derived";
|
import { readDerivedSaveRequest } from "@/types/derived";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
const notFound = () =>
|
const notFound = () =>
|
||||||
@@ -17,7 +15,7 @@ const notFound = () =>
|
|||||||
const unauthorized = () =>
|
const unauthorized = () =>
|
||||||
NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
const noStore = { headers: { "Cache-Control": "no-store" } };
|
const noStore = { headers: { "Cache-Control": "no-store" } };
|
||||||
const loggedIn = async () => !!(await cookies()).get(CookieKeys.AuthToken)?.value;
|
const loggedIn = async () => !!(await getServerAccessToken());
|
||||||
|
|
||||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { exportTarget } from "@/lib/project-proxy-policy";
|
import { exportTarget } from "@/lib/project-proxy-policy";
|
||||||
import { readExcelRequest, readRawDataRequest } from "@/types/export";
|
import { readExcelRequest, readRawDataRequest } from "@/types/export";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
// Workbooks for large projects take a while to build on the server.
|
// Workbooks for large projects take a while to build on the server.
|
||||||
@@ -20,7 +18,7 @@ async function download(request: NextRequest, context: RouteContext, method: "GE
|
|||||||
const target = exportTarget(method, slug);
|
const target = exportTarget(method, slug);
|
||||||
if (!target)
|
if (!target)
|
||||||
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
if (target.body !== "none") {
|
if (target.body !== "none") {
|
||||||
|
|||||||
13
src/app/api/external/[urlkey]/login/route.ts
vendored
13
src/app/api/external/[urlkey]/login/route.ts
vendored
@@ -1,21 +1,17 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
|
||||||
import { serverEnv } from "@/lib/env.server";
|
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isRecord } from "@/types/kart";
|
import { isRecord } from "@/types/kart";
|
||||||
import { isExternalSession, isUrlKey } from "@/types/share";
|
import { isExternalSession, isUrlKey } from "@/types/share";
|
||||||
|
|
||||||
export async function POST(_request: NextRequest, context: { params: Promise<{ urlkey: string }> }) {
|
export async function POST(_request: NextRequest, context: { params: Promise<{ urlkey: string }> }) {
|
||||||
const { urlkey } = await context.params;
|
const { urlkey } = await context.params;
|
||||||
let response: NextResponse;
|
let response: NextResponse;
|
||||||
let token = "";
|
|
||||||
try {
|
try {
|
||||||
if (!isUrlKey(urlkey)) {
|
if (!isUrlKey(urlkey)) {
|
||||||
response = NextResponse.json({ message: "공유 링크를 찾을 수 없습니다." }, { status: 404 });
|
response = NextResponse.json({ message: "공유 링크를 찾을 수 없습니다." }, { status: 404 });
|
||||||
} else {
|
} else {
|
||||||
// Link login replaces the previous identity, including an expired credential cookie.
|
// A link login issues a tab-scoped credential without touching normal-login cookies.
|
||||||
const api = await createServerApi(false);
|
const api = await createServerApi(false);
|
||||||
const result = await api.post<unknown>(`/external/${urlkey}/login`, null, { cache: "no-store" });
|
const result = await api.post<unknown>(`/external/${urlkey}/login`, null, { cache: "no-store" });
|
||||||
const accessToken = isRecord(result) ? result.accessToken : null;
|
const accessToken = isRecord(result) ? result.accessToken : null;
|
||||||
@@ -23,8 +19,7 @@ export async function POST(_request: NextRequest, context: { params: Promise<{ u
|
|||||||
typeof accessToken !== "string" || !accessToken) {
|
typeof accessToken !== "string" || !accessToken) {
|
||||||
response = NextResponse.json({ message: "공유 링크 로그인 응답을 확인해 주세요." }, { status: 502 });
|
response = NextResponse.json({ message: "공유 링크 로그인 응답을 확인해 주세요." }, { status: 502 });
|
||||||
} else {
|
} else {
|
||||||
token = accessToken;
|
response = NextResponse.json({ user: result.user, link: result.link, accessToken });
|
||||||
response = NextResponse.json({ user: result.user, link: result.link });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -32,9 +27,5 @@ export async function POST(_request: NextRequest, context: { params: Promise<{ u
|
|||||||
response = new NextResponse(failure.body, { status: failure.status, headers: failure.headers });
|
response = new NextResponse(failure.body, { status: failure.status, headers: failure.headers });
|
||||||
}
|
}
|
||||||
response.headers.set("Cache-Control", "no-store");
|
response.headers.set("Cache-Control", "no-store");
|
||||||
response.cookies.set(CookieKeys.AuthToken, token, {
|
|
||||||
httpOnly: true, secure: ["prod", "production"].includes(serverEnv.ENV),
|
|
||||||
sameSite: "lax", path: "/", maxAge: token ? AUTH_COOKIE_MAX_AGE : 0,
|
|
||||||
});
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { isImportPath } from "@/lib/project-proxy-policy";
|
import { isImportPath } from "@/lib/project-proxy-policy";
|
||||||
import { readImportResult } from "@/types/export";
|
import { readImportResult } from "@/types/export";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
// Imports replace project data on the server and may run for minutes.
|
// Imports replace project data on the server and may run for minutes.
|
||||||
@@ -15,7 +13,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
if (!isImportPath(slug))
|
if (!isImportPath(slug))
|
||||||
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
let file: File;
|
let file: File;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isProjectRef, isRecord } from "@/types/kart";
|
import { isProjectRef, isRecord } from "@/types/kart";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "로그인이 필요합니다." },
|
{ message: "로그인이 필요합니다." },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
{ status: 400 },
|
{ status: 400 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const serverApi = await createServerApi();
|
const serverApi = await createServerApi(false);
|
||||||
const result = await serverApi.post<unknown>(
|
const result = await serverApi.post<unknown>(
|
||||||
"/auth/login",
|
"/auth/login",
|
||||||
{ userId: body.userId.trim(), userPw: body.userPw },
|
{ userId: body.userId.trim(), userPw: body.userPw },
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { readReportBatch } from "@/lib/report-contract";
|
import { readReportBatch } from "@/lib/report-contract";
|
||||||
import {
|
import {
|
||||||
isProjectReadPath,
|
isProjectReadPath,
|
||||||
projectReadQuery,
|
projectReadQuery,
|
||||||
isReportStreamPath,
|
isReportStreamPath,
|
||||||
} from "@/lib/project-proxy-policy";
|
} from "@/lib/project-proxy-policy";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
export async function GET(request: NextRequest, context: RouteContext) {
|
export async function GET(request: NextRequest, context: RouteContext) {
|
||||||
@@ -18,7 +16,7 @@ export async function GET(request: NextRequest, context: RouteContext) {
|
|||||||
{ message: "지원하지 않는 경로입니다." },
|
{ message: "지원하지 않는 경로입니다." },
|
||||||
{ status: 404 },
|
{ status: 404 },
|
||||||
);
|
);
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "로그인이 필요합니다." },
|
{ message: "로그인이 필요합니다." },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
@@ -49,7 +47,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
{ message: "지원하지 않는 경로입니다." },
|
{ message: "지원하지 않는 경로입니다." },
|
||||||
{ status: 404 },
|
{ status: 404 },
|
||||||
);
|
);
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "로그인이 필요합니다." },
|
{ message: "로그인이 필요합니다." },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { isQuotaListPath, isQuotaResultPath } from "@/lib/project-proxy-policy";
|
import { isQuotaListPath, isQuotaResultPath } from "@/lib/project-proxy-policy";
|
||||||
import { readQuotaRequest } from "@/types/quota";
|
import { readQuotaRequest } from "@/types/quota";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
const notFound = () =>
|
const notFound = () =>
|
||||||
@@ -15,7 +13,7 @@ const unauthorized = () =>
|
|||||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
if (!isQuotaListPath(slug)) return notFound();
|
if (!isQuotaListPath(slug)) return notFound();
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
|
if (!(await getServerAccessToken())) return unauthorized();
|
||||||
try {
|
try {
|
||||||
const serverApi = await createServerApi();
|
const serverApi = await createServerApi();
|
||||||
const result = await serverApi.get<unknown>(
|
const result = await serverApi.get<unknown>(
|
||||||
@@ -31,7 +29,7 @@ export async function GET(_request: NextRequest, context: RouteContext) {
|
|||||||
export async function POST(request: NextRequest, context: RouteContext) {
|
export async function POST(request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
if (!isQuotaResultPath(slug)) return notFound();
|
if (!isQuotaResultPath(slug)) return notFound();
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
|
if (!(await getServerAccessToken())) return unauthorized();
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = readQuotaRequest(await request.json());
|
body = readQuotaRequest(await request.json());
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import { cookies } from "next/headers";
|
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isProjectRef, isRecord } from "@/types/kart";
|
import { isProjectRef, isRecord } from "@/types/kart";
|
||||||
import { isShareLink } from "@/types/share";
|
import { isShareLink } from "@/types/share";
|
||||||
|
|
||||||
@@ -12,7 +10,7 @@ export async function POST(request: NextRequest, context: {
|
|||||||
const params = await context.params;
|
const params = await context.params;
|
||||||
const project = { projectType: params.projectType === "0" ? 0 : params.projectType === "1" ? 1 : null, pkey: params.pkey };
|
const project = { projectType: params.projectType === "0" ? 0 : params.projectType === "1" ? 1 : null, pkey: params.pkey };
|
||||||
if (!isProjectRef(project)) return NextResponse.json({ message: "프로젝트를 확인해 주세요." }, { status: 400 });
|
if (!isProjectRef(project)) return NextResponse.json({ message: "프로젝트를 확인해 주세요." }, { status: 400 });
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
try { body = await request.json(); } catch { body = null; }
|
try { body = await request.json(); } catch { body = null; }
|
||||||
|
|||||||
@@ -20,13 +20,14 @@ export function AppMainLayout({ children }: { children: ReactNode }) {
|
|||||||
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
|
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hydrated && !auth.user) router.replace("/logout");
|
if (hydrated && !auth.user) router.replace("/logout");
|
||||||
|
else if (hydrated && external && !auth.accessToken) router.replace("/logout");
|
||||||
// Legacy Main sends shared-link users (isAdmin > 8) to Logout, ending the External session.
|
// Legacy Main sends shared-link users (isAdmin > 8) to Logout, ending the External session.
|
||||||
else if (hydrated && external && pathname === "/") router.replace("/logout");
|
else if (hydrated && external && pathname === "/") router.replace("/logout");
|
||||||
else if (hydrated && !externalAllowed)
|
else if (hydrated && !externalAllowed)
|
||||||
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
|
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
|
||||||
}, [hydrated, auth.user, auth.external, external, externalAllowed, pathname, router]);
|
}, [hydrated, auth.user, auth.external, auth.accessToken, external, externalAllowed, pathname, router]);
|
||||||
const hasSidebar = sideMenus.length > 0;
|
const hasSidebar = sideMenus.length > 0;
|
||||||
if (!hydrated || !auth.user || !externalAllowed)
|
if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken))
|
||||||
return (
|
return (
|
||||||
<p
|
<p
|
||||||
role="status"
|
role="status"
|
||||||
|
|||||||
@@ -7,29 +7,28 @@ import { useSetAtom } from "jotai";
|
|||||||
import { apiError } from "@kri/common/http";
|
import { apiError } from "@kri/common/http";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useResetSession } from "@/hooks/useResetSession";
|
import { useResetSession } from "@/hooks/useResetSession";
|
||||||
import { notifyAuthChange } from "@/lib/auth-change";
|
|
||||||
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { authApi } from "@/lib/http-client";
|
||||||
import { isExternalSession, reportUrl, type ExternalSession } from "@/types/share";
|
import { isExternalLoginResponse, reportUrl, type ExternalLoginResponse } from "@/types/share";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
|
|
||||||
export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { hydrated, setAuth, logout } = useAuth();
|
const { hydrated, setAuth } = useAuth();
|
||||||
const setProject = useSetAtom(selectedProjectAtom);
|
const setProject = useSetAtom(selectedProjectAtom);
|
||||||
const resetSession = useResetSession();
|
const resetSession = useResetSession();
|
||||||
const pending = useRef<Promise<ExternalSession> | null>(null);
|
const pending = useRef<Promise<ExternalLoginResponse> | null>(null);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hydrated) return;
|
if (!hydrated) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
const enter = async () => {
|
const enter = async () => {
|
||||||
logout();
|
setAuth({ mode: "external", user: null });
|
||||||
await resetSession();
|
await resetSession();
|
||||||
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
const result = await authApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
||||||
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
||||||
});
|
});
|
||||||
if (!isExternalSession(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
if (!isExternalLoginResponse(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
// Reuse the request during StrictMode effect replay; each entry records one landing.
|
// Reuse the request during StrictMode effect replay; each entry records one landing.
|
||||||
@@ -37,17 +36,15 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
|||||||
void pending.current.then((result) => {
|
void pending.current.then((result) => {
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
||||||
setAuth({ user: result.user, external: result.link });
|
setAuth({ mode: "external", user: result.user, external: result.link, accessToken: result.accessToken });
|
||||||
notifyAuthChange(result.link.realUrl);
|
|
||||||
router.replace(reportUrl(result.link.realUrl) as Route);
|
router.replace(reportUrl(result.link.realUrl) as Route);
|
||||||
}).catch((reason: unknown) => {
|
}).catch((reason: unknown) => {
|
||||||
if (active) {
|
if (active) {
|
||||||
notifyAuthChange("/login");
|
|
||||||
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return () => { active = false; };
|
return () => { active = false; };
|
||||||
}, [hydrated, logout, setAuth, setProject, resetSession, router, urlKey]);
|
}, [hydrated, setAuth, setProject, resetSession, router, urlKey]);
|
||||||
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
||||||
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { atom, useAtom, useAtomValue } from "jotai";
|
||||||
|
import type { SetStateAction } from "react";
|
||||||
import type { LoginUser } from "@kri/common";
|
import type { LoginUser } from "@kri/common";
|
||||||
import { isRecord, isLoginUser } from "@/types/kart";
|
import { isRecord, isLoginUser } from "@/types/kart";
|
||||||
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
|
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
|
||||||
@@ -10,25 +11,27 @@ import {
|
|||||||
getLocalStorage,
|
getLocalStorage,
|
||||||
removeLocalStorage,
|
removeLocalStorage,
|
||||||
setLocalStorage,
|
setLocalStorage,
|
||||||
|
getSessionStorage,
|
||||||
|
setSessionStorage,
|
||||||
|
removeSessionStorage,
|
||||||
} from "@/store/storage/secure-storage";
|
} from "@/store/storage/secure-storage";
|
||||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||||
import { isExternalSession, isExternalUser, type ShareLink } from "@/types/share";
|
import { isExternalUser, type ShareLink } from "@/types/share";
|
||||||
|
import { isExternalAuth, type ExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
export type AuthState = CommonAuthState<LoginUser> & { external?: ShareLink };
|
export type AuthState = CommonAuthState<LoginUser> & { external?: ShareLink; accessToken?: string; mode?: "external" };
|
||||||
const initialAuthState: AuthState = { user: null };
|
const initialAuthState: AuthState = { user: null };
|
||||||
|
|
||||||
const isPersistedAuthState = (value: unknown): value is AuthState =>
|
const isPersistedAuthState = (value: unknown): value is AuthState =>
|
||||||
isRecord(value) && isLoginUser(value.user) &&
|
isRecord(value) && isLoginUser(value.user) && !isExternalUser(value.user) &&
|
||||||
(isExternalUser(value.user)
|
value.accessToken === undefined && value.external === undefined;
|
||||||
? isExternalSession({ user: value.user, link: value.external })
|
|
||||||
: value.external === undefined);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
|
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
|
||||||
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
|
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
|
||||||
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
|
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
|
||||||
*/
|
*/
|
||||||
export const authStateAtom = createPersistentAtom<AuthState>(
|
const normalAuthStateAtom = createPersistentAtom<AuthState>(
|
||||||
StorageKeys.AuthState,
|
StorageKeys.AuthState,
|
||||||
initialAuthState,
|
initialAuthState,
|
||||||
{
|
{
|
||||||
@@ -43,6 +46,48 @@ export const authStateAtom = createPersistentAtom<AuthState>(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const sessionStorage = { get: getSessionStorage, set: setSessionStorage, remove: removeSessionStorage };
|
||||||
|
const authModeAtom = createPersistentAtom<"normal" | "external">(StorageKeys.AuthMode, "normal", {
|
||||||
|
storage: sessionStorage,
|
||||||
|
validate: (value): value is "normal" | "external" => value === "normal" || value === "external",
|
||||||
|
shouldRemove: (value) => value === "normal",
|
||||||
|
});
|
||||||
|
const externalAuthStateAtom = createPersistentAtom<ExternalAuth | null>(StorageKeys.ExternalAuth, null, {
|
||||||
|
storage: sessionStorage,
|
||||||
|
validate: (value): value is ExternalAuth | null => value === null || isExternalAuth(value),
|
||||||
|
});
|
||||||
|
const emptyExternalAuth: ExternalAuth = { mode: "external", user: null };
|
||||||
|
|
||||||
|
export const authStateAtom = Object.assign(atom(
|
||||||
|
(get): AuthState => {
|
||||||
|
const normal = get(normalAuthStateAtom);
|
||||||
|
const mode = get(authModeAtom);
|
||||||
|
const external = get(externalAuthStateAtom);
|
||||||
|
if (mode === "external") return external ?? emptyExternalAuth;
|
||||||
|
return normal;
|
||||||
|
},
|
||||||
|
(get, set, action: SetStateAction<AuthState>) => {
|
||||||
|
const previous = get(authStateAtom);
|
||||||
|
const next = typeof action === "function" ? action(previous) : action;
|
||||||
|
if (next.mode === "external" || isExternalUser(next.user)) {
|
||||||
|
set(authModeAtom, "external");
|
||||||
|
set(externalAuthStateAtom, { ...next, mode: "external" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!next.user && previous.mode === "external") {
|
||||||
|
set(authModeAtom, "external");
|
||||||
|
set(externalAuthStateAtom, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
set(authModeAtom, "normal");
|
||||||
|
set(externalAuthStateAtom, null);
|
||||||
|
set(normalAuthStateAtom, { user: next.user });
|
||||||
|
},
|
||||||
|
), {
|
||||||
|
hydratedAtom: atom((get) => get(normalAuthStateAtom.hydratedAtom) &&
|
||||||
|
get(authModeAtom.hydratedAtom) && get(externalAuthStateAtom.hydratedAtom)),
|
||||||
|
});
|
||||||
|
|
||||||
export function useAuth() {
|
export function useAuth() {
|
||||||
const [auth, setAuth] = useAtom(authStateAtom);
|
const [auth, setAuth] = useAtom(authStateAtom);
|
||||||
const hydrated = useAtomValue(authStateAtom.hydratedAtom);
|
const hydrated = useAtomValue(authStateAtom.hydratedAtom);
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { createPersistentAtom } from "@kri/common/jotai";
|
|||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { isExternalUser } from "@/types/share";
|
import { isExternalUser } from "@/types/share";
|
||||||
import {
|
import {
|
||||||
getLocalStorage,
|
|
||||||
getSessionStorage,
|
getSessionStorage,
|
||||||
removeSessionStorage,
|
removeSessionStorage,
|
||||||
setSessionStorage,
|
setSessionStorage,
|
||||||
@@ -24,25 +23,13 @@ const isSelectedProject = (value: unknown): value is SelectedProject =>
|
|||||||
value.userId !== "" &&
|
value.userId !== "" &&
|
||||||
isProjectRef(value.project));
|
isProjectRef(value.project));
|
||||||
|
|
||||||
/** Each tab owns its selection; copy a legacy selection only on its first hydration. */
|
/** Each tab owns its selection. */
|
||||||
export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
||||||
StorageKeys.SelectedProject,
|
StorageKeys.SelectedProject,
|
||||||
null,
|
null,
|
||||||
{
|
{
|
||||||
storage: {
|
storage: {
|
||||||
get: <T,>(key: string): T | null => {
|
get: getSessionStorage,
|
||||||
const stored = getSessionStorage<T>(key);
|
|
||||||
if (stored !== null) return stored;
|
|
||||||
const migrationKey = key + ":session-migrated";
|
|
||||||
if (getSessionStorage(migrationKey)) return null;
|
|
||||||
setSessionStorage(migrationKey, true);
|
|
||||||
const legacy = getLocalStorage<T>(key);
|
|
||||||
if (isSelectedProject(legacy) && legacy !== null) {
|
|
||||||
setSessionStorage(key, legacy);
|
|
||||||
return legacy;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
set: setSessionStorage,
|
set: setSessionStorage,
|
||||||
remove: removeSessionStorage,
|
remove: removeSessionStorage,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { reportUrl } from "@/types/share";
|
import { readExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
// Set false to disable only cross-tab notifications and their listener.
|
// Set false to disable only cross-tab notifications and their listener.
|
||||||
const AUTH_CHANGE_SYNC_ENABLED = true;
|
const AUTH_CHANGE_SYNC_ENABLED = true;
|
||||||
const CHANNEL = "kart:auth-change";
|
const CHANNEL = "kart:internal-auth-change";
|
||||||
let channel: BroadcastChannel | undefined;
|
let channel: BroadcastChannel | undefined;
|
||||||
|
|
||||||
function authChannel() {
|
function authChannel() {
|
||||||
@@ -15,7 +15,7 @@ function authChannel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function notifyAuthChange(path: string) {
|
export function notifyAuthChange(path: "/" | "/login") {
|
||||||
authChannel()?.postMessage(path);
|
authChannel()?.postMessage(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,10 +23,11 @@ export function subscribeToAuthChanges() {
|
|||||||
const listener = authChannel();
|
const listener = authChannel();
|
||||||
if (!listener) return;
|
if (!listener) return;
|
||||||
listener.onmessage = (event: MessageEvent<unknown>) => {
|
listener.onmessage = (event: MessageEvent<unknown>) => {
|
||||||
const path = event.data === "/" || event.data === "/login"
|
// A normal-login change must not navigate an independently authenticated link tab.
|
||||||
? event.data : reportUrl(event.data);
|
if (readExternalAuth()) return;
|
||||||
|
if (event.data !== "/" && event.data !== "/login") return;
|
||||||
// A full navigation discards this tab's cache/state without clearing the new cookie.
|
// A full navigation discards this tab's cache/state without clearing the new cookie.
|
||||||
if (path) window.location.replace(path);
|
window.location.replace(event.data);
|
||||||
};
|
};
|
||||||
return () => {
|
return () => {
|
||||||
listener.close();
|
listener.close();
|
||||||
|
|||||||
@@ -7,9 +7,7 @@ import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|||||||
/** Issue/renew the normal-login cookie, or expire it when the token is empty. */
|
/** Issue/renew the normal-login cookie, or expire it when the token is empty. */
|
||||||
export function setAuthCookie(response: NextResponse, token: string): void {
|
export function setAuthCookie(response: NextResponse, token: string): void {
|
||||||
const production = serverEnv.ENV === "prod";
|
const production = serverEnv.ENV === "prod";
|
||||||
const domain = production ? serverEnv.AUTH_COOKIE_DOMAIN : undefined;
|
const domain = serverEnv.AUTH_COOKIE_DOMAIN;
|
||||||
if (production && !domain)
|
|
||||||
throw new Error("AUTH_COOKIE_DOMAIN must be configured when ENV is prod.");
|
|
||||||
|
|
||||||
const options = {
|
const options = {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
@@ -30,6 +28,6 @@ export function setAuthCookie(response: NextResponse, token: string): void {
|
|||||||
response.headers.append("Set-Cookie", header);
|
response.headers.append("Set-Cookie", header);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (production) append("", undefined, 0);
|
if (domain) append("", undefined, 0);
|
||||||
append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0);
|
append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0);
|
||||||
}
|
}
|
||||||
|
|||||||
29
src/lib/external-auth.ts
Normal file
29
src/lib/external-auth.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { LoginUser } from "@kri/common";
|
||||||
|
import { getSessionStorage } from "@/store/storage/secure-storage";
|
||||||
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||||
|
import { isRecord } from "@/types/kart";
|
||||||
|
import { isExternalSession, type ShareLink } from "@/types/share";
|
||||||
|
|
||||||
|
export type ExternalAuth = {
|
||||||
|
mode: "external";
|
||||||
|
user: LoginUser | null;
|
||||||
|
external?: ShareLink;
|
||||||
|
accessToken?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isExternalAuth(value: unknown): value is ExternalAuth {
|
||||||
|
if (!isRecord(value) || value.mode !== "external") return false;
|
||||||
|
if (value.user === null) return value.external === undefined && value.accessToken === undefined;
|
||||||
|
return isExternalSession({ user: value.user, link: value.external }) &&
|
||||||
|
(value.accessToken === undefined || typeof value.accessToken === "string");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The mode survives missing/invalid token data so requests never fall back to the normal cookie. */
|
||||||
|
export function readExternalAuth(): ExternalAuth | null {
|
||||||
|
if (getSessionStorage(StorageKeys.AuthMode) !== "external") return null;
|
||||||
|
const value = getSessionStorage(StorageKeys.ExternalAuth);
|
||||||
|
if (isExternalAuth(value)) return value;
|
||||||
|
return { mode: "external", user: null };
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { apiError, createHttpClient, redirectToLogout } from "@kri/common/http";
|
import { apiError, createHttpClient, HttpError, redirectToLogout } from "@kri/common/http";
|
||||||
import { clientEnv } from "@/lib/env.client";
|
import { clientEnv } from "@/lib/env.client";
|
||||||
import { announceProjectAccess, projectFromRequest } from "@/lib/project-access";
|
import { announceProjectAccess, projectFromRequest } from "@/lib/project-access";
|
||||||
|
import { readExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
const resolveBaseUrl = () =>
|
const resolveBaseUrl = () =>
|
||||||
typeof window === "undefined"
|
typeof window === "undefined"
|
||||||
@@ -8,9 +9,18 @@ const resolveBaseUrl = () =>
|
|||||||
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
||||||
|
|
||||||
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
||||||
|
getToken: () => {
|
||||||
|
const external = readExternalAuth();
|
||||||
|
if (!external) return null;
|
||||||
|
if (!external.accessToken) {
|
||||||
|
redirectToLogout();
|
||||||
|
throw new HttpError(401, { message: "공유 링크 인증이 필요합니다." }, "");
|
||||||
|
}
|
||||||
|
return external.accessToken;
|
||||||
|
},
|
||||||
onForbidden: (error) => {
|
onForbidden: (error) => {
|
||||||
const info = apiError(error);
|
const info = apiError(error);
|
||||||
if (info.code === "EXTERNAL_SCOPE_DENIED" || info.code === "PROJECT_IDENTITY_REQUIRED") {
|
if (readExternalAuth() || info.code === "EXTERNAL_SCOPE_DENIED" || info.code === "PROJECT_IDENTITY_REQUIRED") {
|
||||||
redirectToLogout();
|
redirectToLogout();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -20,3 +30,10 @@ export const nextApi = createHttpClient(resolveBaseUrl(), {
|
|||||||
},
|
},
|
||||||
onResponseError: false,
|
onResponseError: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Login/logout BFF operations must also work before an External JWT is available.
|
||||||
|
export const authApi = createHttpClient(resolveBaseUrl(), {
|
||||||
|
onUnauthorized: false,
|
||||||
|
onForbidden: false,
|
||||||
|
onResponseError: false,
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
import { cookies } from "next/headers";
|
import { cookies, headers } from "next/headers";
|
||||||
import { createHttpClient } from "@kri/common/http";
|
import { createHttpClient } from "@kri/common/http";
|
||||||
import { serverEnv } from "@/lib/env.server";
|
import { serverEnv } from "@/lib/env.server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||||
|
|
||||||
|
export async function getServerAccessToken(): Promise<string | null> {
|
||||||
|
const authorization = (await headers()).get("authorization");
|
||||||
|
// Explicit credentials take precedence even when malformed; never use the normal
|
||||||
|
// cookie as a fallback for an External request. The backend verifies the JWT.
|
||||||
|
if (authorization !== null) return /^Bearer ([^\s]+)$/i.exec(authorization)?.[1] ?? null;
|
||||||
|
return (await cookies()).get(CookieKeys.AuthToken)?.value ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
export async function createServerApi(authenticated = true) {
|
export async function createServerApi(authenticated = true) {
|
||||||
const cookieStore = await cookies();
|
let accessToken: string | null = null;
|
||||||
const accessToken = authenticated ? cookieStore.get(CookieKeys.AuthToken)?.value ?? null : null;
|
if (authenticated) accessToken = await getServerAccessToken();
|
||||||
return createHttpClient(serverEnv.API_SERVER, {
|
return createHttpClient(serverEnv.API_SERVER, {
|
||||||
getToken: () => accessToken,
|
getToken: () => accessToken,
|
||||||
defaultHeaders: { "content-type": "application/json" },
|
defaultHeaders: { "content-type": "application/json" },
|
||||||
|
|||||||
@@ -5,15 +5,16 @@ import { useMutation } from "@tanstack/react-query";
|
|||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useResetSession } from "@/hooks/useResetSession";
|
import { useResetSession } from "@/hooks/useResetSession";
|
||||||
import { notifyAuthChange } from "@/lib/auth-change";
|
import { notifyAuthChange } from "@/lib/auth-change";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { authApi } from "@/lib/http-client";
|
||||||
import { isLoginUser } from "@/types/kart";
|
import { isLoginUser } from "@/types/kart";
|
||||||
|
import { readExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
export function useLoginMutation() {
|
export function useLoginMutation() {
|
||||||
const { setFromLoginResponse } = useAuth();
|
const { setFromLoginResponse } = useAuth();
|
||||||
const resetSession = useResetSession();
|
const resetSession = useResetSession();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (request: LoginRequest) => {
|
mutationFn: async (request: LoginRequest) => {
|
||||||
const user = await nextApi.post<unknown>("/login", request, {
|
const user = await authApi.post<unknown>("/login", request, {
|
||||||
skipUnauthorizedHandler: true,
|
skipUnauthorizedHandler: true,
|
||||||
skipForbiddenHandler: true,
|
skipForbiddenHandler: true,
|
||||||
skipResponseErrorHandler: true,
|
skipResponseErrorHandler: true,
|
||||||
@@ -32,17 +33,21 @@ export function useLoginMutation() {
|
|||||||
export function useLogoutMutation() {
|
export function useLogoutMutation() {
|
||||||
const { logout } = useAuth();
|
const { logout } = useAuth();
|
||||||
const resetSession = useResetSession();
|
const resetSession = useResetSession();
|
||||||
|
const externalSession = () => !!readExternalAuth();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: () =>
|
onMutate: () => ({ external: externalSession() }),
|
||||||
nextApi.post("/logout", null, {
|
mutationFn: async () => {
|
||||||
|
if (externalSession()) return;
|
||||||
|
await authApi.post("/logout", null, {
|
||||||
skipUnauthorizedHandler: true,
|
skipUnauthorizedHandler: true,
|
||||||
skipForbiddenHandler: true,
|
skipForbiddenHandler: true,
|
||||||
skipResponseErrorHandler: true,
|
skipResponseErrorHandler: true,
|
||||||
}),
|
});
|
||||||
onSettled: async () => {
|
},
|
||||||
|
onSettled: async (_data, _error, _variables, context) => {
|
||||||
await resetSession();
|
await resetSession();
|
||||||
logout();
|
logout();
|
||||||
notifyAuthChange("/login");
|
if (!context?.external) notifyAuthChange("/login");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
export const StorageKeys = {
|
export const StorageKeys = {
|
||||||
AuthState: "kri:authState",
|
AuthState: "kri:authState",
|
||||||
|
AuthMode: "kart:authMode",
|
||||||
|
ExternalAuth: "kart:externalAuth",
|
||||||
SelectedProject: "kart:selectedProject",
|
SelectedProject: "kart:selectedProject",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
||||||
export const StorageType: Record<StorageKey, "local" | "session"> = {
|
export const StorageType: Record<StorageKey, "local" | "session"> = {
|
||||||
[StorageKeys.AuthState]: "local",
|
[StorageKeys.AuthState]: "local",
|
||||||
|
[StorageKeys.AuthMode]: "session",
|
||||||
|
[StorageKeys.ExternalAuth]: "session",
|
||||||
[StorageKeys.SelectedProject]: "session",
|
[StorageKeys.SelectedProject]: "session",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,6 +15,12 @@ export type ShareLink = ProjectRef & {
|
|||||||
pageOnly: boolean;
|
pageOnly: boolean;
|
||||||
};
|
};
|
||||||
export type ExternalSession = { user: LoginUser; link: ShareLink };
|
export type ExternalSession = { user: LoginUser; link: ShareLink };
|
||||||
|
export type ExternalLoginResponse = ExternalSession & { accessToken: string };
|
||||||
|
|
||||||
|
export function isExternalLoginResponse(value: unknown): value is ExternalLoginResponse {
|
||||||
|
return isRecord(value) && typeof value.accessToken === "string" &&
|
||||||
|
value.accessToken.length > 0 && isExternalSession(value);
|
||||||
|
}
|
||||||
|
|
||||||
export function isExternalUser(user: LoginUser | null | undefined): boolean {
|
export function isExternalUser(user: LoginUser | null | undefined): boolean {
|
||||||
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
|
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
|
||||||
|
|||||||
Reference in New Issue
Block a user