Skip to content
5 changes: 4 additions & 1 deletion frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";
import localFont from "next/font/local";

import { AuthGuard } from "@/components/auth/auth-guard";
import { ConsentGate } from "@/components/auth/consent-gate";
import { LoginRequiredProvider } from "@/components/auth/login-required";
import { BOTTOM_TAB_BAR_SPACE, BottomTabBar } from "@/components/layout/bottom-tab-bar";
import { StartupProvider } from "@/components/screens/startup-provider";
Expand Down Expand Up @@ -44,7 +45,9 @@ export default function RootLayout({ children }: LayoutProps<"/">) {
<LoginRequiredProvider>
<SiteHeader navigation={HEADER_NAV_ITEMS} />
<div className={cn("flex flex-1 flex-col", BOTTOM_TAB_BAR_SPACE)}>
<AuthGuard>{children}</AuthGuard>
<AuthGuard>
<ConsentGate>{children}</ConsentGate>
</AuthGuard>
</div>
<BottomTabBar />
</LoginRequiredProvider>
Expand Down
3 changes: 0 additions & 3 deletions frontend/src/components/auth/auth-callback-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { useEffect, useRef } from "react";
import { completeLogin } from "@/lib/api/auth";
import { loginHref, parseCallbackQuery } from "@/lib/auth";
import { takeLoginReturn } from "@/lib/return-to";
import { forgetTermsAgreement } from "@/lib/terms";

/**
* 로그인 콜백 (A27 이 돌려보내는 화면). 1회용 코드를 주소에서 바로 지우고 A01 로 교환한다.
Expand All @@ -26,8 +25,6 @@ export function AuthCallbackView() {
window.history.replaceState(null, "", window.location.pathname);

if (result.kind === "error") {
// 약관이 바뀌었으면 기억한 동의를 지우고 로그인 화면에서 다시 묻는다
if (result.error === "terms_outdated") forgetTermsAgreement();
router.replace(loginHref(result.error));
return;
}
Expand Down
294 changes: 294 additions & 0 deletions frontend/src/components/auth/consent-gate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
"use client";

import Link from "next/link";
import { CircleAlert, ShieldCheck } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useId, useState, useSyncExternalStore, type ReactNode } from "react";

import { SampleDataNotice } from "@/components/feedback/sample-data";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { ERROR_COPY, toErrorKind } from "@/lib/api/errors";
import { isMockMode } from "@/lib/api/mock";
import { agreeTerms, fetchTermsAgreed, isTermsOutdated, withdraw } from "@/lib/api/users";
import { loginHref } from "@/lib/auth";
import {
consentGateView,
forgetConsent,
getConsentStatus,
hasRememberedConsent,
rememberConsent,
setConsentStatus,
subscribeConsent,
toggleAll,
} from "@/lib/consent";
import { getSessionStatus } from "@/lib/session";
import { PRIVACY_HREF, TERMS_HREF, TERMS_VERSION } from "@/lib/terms";
import { useSessionStatus } from "@/lib/use-session";
import { cn } from "@/lib/utils";

/**
* 로그인 직후 약관 동의 단계 (Jira SCRUM-211, 기획 M10 R8, Notion API 명세서 A28·A34·A30).
* 로그인한 상태에서 A28 의 terms_agreed 가 false 면(신규 가입·약관 버전 변경) 닫을 수 없는 창(휴대폰 폭은 하단, 넓은 화면은 가운데)으로 동의를 받는다.
* 동의하면 A34 를 부르고 지금 화면(로그인 전에 보던 화면)을 그대로 쓴다. 거부하면 A30 으로 계정을 지우고 로그인 화면으로 간다.
* 동의하기 전에는 보호 화면을 그리지 않는다. 다른 API 가 403 terms_not_agreed 를 줘도 이 창을 다시 띄운다.
*/
export function ConsentGate({ children }: { children: ReactNode }) {
const session = useSessionStatus();
const pathname = usePathname() ?? "/";
const status = useSyncExternalStore(subscribeConsent, getConsentStatus, () => "unknown" as const);

// 로그인 상태가 바뀌거나 다시 확인할 때(unknown) A28 로 동의 여부를 본다
useEffect(() => {
if (session !== "logged_in") {
forgetConsent();
setConsentStatus("unknown");
return;
}
if (status !== "unknown") return;
if (hasRememberedConsent(TERMS_VERSION)) {
setConsentStatus("agreed");
return;
}
// checking 으로 바꾸면 이 effect 가 다시 돌므로 요청을 취소하지 않고, 응답이 왔을 때 아직 로그인 상태인지 본다
setConsentStatus("checking");
fetchTermsAgreed()
.then((agreed) => {
if (getSessionStatus() !== "logged_in" || getConsentStatus() !== "checking") return;
if (agreed) rememberConsent(TERMS_VERSION);
setConsentStatus(agreed ? "agreed" : "needed");
})
.catch((error: unknown) => {
if (getSessionStatus() !== "logged_in" || getConsentStatus() !== "checking") return;
// 401 이면 세션이 지워져 위의 로그아웃 분기로 다시 온다
setConsentStatus(toErrorKind(error) === "unauthorized" ? "unknown" : "error");
});
}, [session, status]);

const view = consentGateView(session, status, pathname);

return (
<>
{view.holdProtected ? (
<main className="mx-auto flex w-full max-w-md flex-1 flex-col items-center justify-center px-4 py-16">
<p role="status" className="text-muted-foreground">
{status === "needed" ? "약관에 동의하면 이어서 볼 수 있어요." : "약관 동의 여부를 확인하는 중이에요…"}
</p>
</main>
) : (
children
)}
<Sheet open={view.sheet}>
<SheetContent
side="adaptive"
hideClose
// 동의하거나 거부해야 끝나는 단계라 바깥 누르기·Esc 로 닫지 않는다
onEscapeKeyDown={(event) => event.preventDefault()}
onInteractOutside={(event) => event.preventDefault()}
className="gap-0 overflow-y-auto"
>
{status === "error" ? (
<CheckFailed onRetry={() => setConsentStatus("unknown")} />
) : (
<ConsentForm onAgreed={() => setConsentStatus("agreed")} />
)}
</SheetContent>
</Sheet>
</>
);
}

function CheckFailed({ onRetry }: { onRetry: () => void }) {
return (
<>
<SheetHeader className="pr-5">
<SheetTitle className="text-lg font-extrabold text-foreground">약관 동의 여부를 확인하지 못했어요</SheetTitle>
<SheetDescription className="text-sm text-ink-500">
인터넷 연결을 확인한 뒤 다시 시도해 주세요. 확인되기 전에는 진단·계약서 기능을 쓸 수 없어요.
</SheetDescription>
</SheetHeader>
<div className="px-5 pb-[max(1.5rem,env(safe-area-inset-bottom))]">
<Button type="button" size="lg" className="w-full" onClick={onRetry}>
다시 시도
</Button>
</div>
</>
);
}

type FormError = { title: string; description: string };

function ConsentForm({ onAgreed }: { onAgreed: () => void }) {
const router = useRouter();
const allId = useId();
const termsId = useId();
const ageId = useId();
const [checks, setChecks] = useState({ terms: false, age: false });
const [step, setStep] = useState<"form" | "confirmDecline">("form");
const [busy, setBusy] = useState<"agree" | "decline" | null>(null);
const [error, setError] = useState<FormError | null>(null);
const all = checks.terms && checks.age;

async function agree() {
setBusy("agree");
setError(null);
try {
await agreeTerms(TERMS_VERSION);
rememberConsent(TERMS_VERSION);
onAgreed();
} catch (cause) {
setError(
isTermsOutdated(cause)
? { title: "약관이 바뀌었어요", description: "화면을 새로 고친 뒤 바뀐 약관을 확인하고 다시 동의해 주세요." }
: ERROR_COPY[toErrorKind(cause)],
);
} finally {
setBusy(null);
}
}

async function decline() {
setBusy("decline");
setError(null);
try {
await withdraw();
router.replace(loginHref());
} catch (cause) {
setError(ERROR_COPY[toErrorKind(cause)]);
setBusy(null);
}
}

if (step === "confirmDecline") {
return (
<>
<SheetHeader className="pr-5">
<SheetTitle className="text-lg font-extrabold text-foreground">동의하지 않고 나갈까요?</SheetTitle>
<SheetDescription className="text-sm text-ink-500">
필수 항목에 동의하지 않으면 서비스를 쓸 수 없어요. 방금 만든 계정은 바로 삭제되고, 다음에 다시 로그인하면
처음부터 동의를 받아요.
</SheetDescription>
</SheetHeader>
<div className="flex flex-col gap-2 px-5 pb-[max(1.5rem,env(safe-area-inset-bottom))]">
{error ? <FormAlert error={error} /> : null}
<Button type="button" size="lg" className="w-full" disabled={busy !== null} onClick={() => setStep("form")}>
다시 확인할게요
</Button>
<Button
type="button"
variant="ghost"
className="min-h-11 w-full text-destructive hover:bg-destructive-soft hover:text-destructive"
disabled={busy !== null}
aria-busy={busy === "decline"}
onClick={() => void decline()}
>
{busy === "decline" ? "계정을 삭제하는 중…" : "동의하지 않고 나가기"}
</Button>
</div>
</>
);
}

return (
<>
<SheetHeader className="pr-5">
<span className="inline-flex w-fit items-center gap-1 rounded-full bg-primary-soft px-2 py-0.5 text-[12px] font-extrabold text-primary">
<ShieldCheck className="size-3" aria-hidden="true" />
처음 한 번만
</span>
<SheetTitle className="text-lg font-extrabold text-foreground">서비스 이용에 동의해 주세요</SheetTitle>
<SheetDescription className="text-sm text-ink-500">
진단·계약서 확인을 쓰려면 아래 필수 항목에 동의해야 해요. 동의하면 보던 화면에서 바로 이어서 쓸 수 있어요.
</SheetDescription>
</SheetHeader>

<div className="flex flex-col gap-4 px-5 pb-[max(1.5rem,env(safe-area-inset-bottom))]">
{isMockMode() && <SampleDataNotice>예시 모드라 동의 기록은 이 브라우저에만 남아요.</SampleDataNotice>}

<fieldset className="flex flex-col rounded-xl border bg-card">
<legend className="sr-only">서비스 이용 동의</legend>
<div className={cn("flex min-h-14 items-center gap-3 rounded-t-xl px-4 py-3", all && "bg-primary-soft")}>
<Checkbox id={allId} checked={all} onCheckedChange={() => setChecks(toggleAll)} />
<Label htmlFor={allId} className="text-base leading-snug font-extrabold">
모두 동의해요
</Label>
</div>
<div className="border-t" />
<div className="flex min-h-11 items-start gap-3 px-4 py-3">
<Checkbox
id={termsId}
checked={checks.terms}
onCheckedChange={(value) => setChecks((prev) => ({ ...prev, terms: value === true }))}
className="mt-0.5"
/>
<div className="flex flex-col gap-1">
<Label htmlFor={termsId} className="text-base leading-snug font-semibold">
이용약관과 개인정보 처리방침에 동의해요 (필수)
</Label>
<p className="flex gap-3 text-sm">
<Link href={TERMS_HREF} className="text-primary underline underline-offset-2">
이용약관 보기
</Link>
<Link href={PRIVACY_HREF} className="text-primary underline underline-offset-2">
개인정보 처리방침 보기
</Link>
</p>
</div>
</div>
<div className="flex min-h-11 items-start gap-3 px-4 py-3">
<Checkbox
id={ageId}
checked={checks.age}
onCheckedChange={(value) => setChecks((prev) => ({ ...prev, age: value === true }))}
className="mt-0.5"
/>
<Label htmlFor={ageId} className="text-base leading-snug font-semibold">
만 14세 이상이에요 (필수)
</Label>
</div>
</fieldset>

{error ? <FormAlert error={error} /> : null}

<div className="flex flex-col gap-2">
<Button
type="button"
size="lg"
className="w-full"
disabled={!all || busy !== null}
aria-busy={busy === "agree"}
onClick={() => void agree()}
>
{busy === "agree" ? "저장하는 중…" : "동의하고 시작하기"}
</Button>
<Button
type="button"
variant="ghost"
className="min-h-11 w-full text-ink-500"
disabled={busy !== null}
onClick={() => {
setError(null);
setStep("confirmDecline");
}}
>
동의하지 않아요
</Button>
</div>
</div>
</>
);
}

function FormAlert({ error }: { error: FormError }) {
return (
<div role="alert" className="flex gap-2 rounded-xl border border-destructive/30 bg-card p-4">
<CircleAlert className="mt-0.5 size-5 shrink-0 text-destructive" aria-hidden="true" />
<div className="flex flex-col gap-1">
<p className="font-bold text-foreground">{error.title}</p>
<p className="text-sm text-muted-foreground">{error.description}</p>
</div>
</div>
);
}
Loading