add login

This commit is contained in:
jaehwang committed 2026-09-15 16:00:54 +09:00
1 parent b27a7b528a
commit c4efd6406d
22 files changed
+786 -17

No files matched your search

+4 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import Link from "next/link";
import Ado2Logo from "@/components/ado2-logo";
import AuthGate from "@/components/auth-gate";
import NavLink from "@/components/nav-link";
import { FEATURES } from "@/lib/features";
@@ -27,7 +28,9 @@ export default function Ado2Layout({ children }: { children: React.ReactNode })
<div className="sidebar-foot">무빙포스터 · 내부 빌드</div>
</aside>
<main className="main-content">
<div style={{ maxWidth: 1080, margin: "0 auto" }}>{children}</div>
<div style={{ maxWidth: 1080, margin: "0 auto" }}>
<AuthGate>{children}</AuthGate>
</div>
</main>
</>
);
+4 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import Link from "next/link";
import Ado2Logo from "@/components/ado2-logo";
import AuthGate from "@/components/auth-gate";
import NavLink from "@/components/nav-link";
import { FEATURES } from "@/lib/features";
@@ -38,7 +39,9 @@ export default function PlayreelLayout({ children }: { children: React.ReactNode
<div className="sidebar-foot">Playreel · an ADO2 product · 내부 빌드</div>
</aside>
<main className="main-content">
<div style={{ maxWidth: 1080, margin: "0 auto" }}>{children}</div>
<div style={{ maxWidth: 1080, margin: "0 auto" }}>
<AuthGate>{children}</AuthGate>
</div>
</main>
</>
);
+42
View File
@@ -0,0 +1,42 @@
"use client";
/** 로그인하지 않았으면 화면 대신 로그인만 보여준다 */
import { useState } from "react";
import { usePathname } from "next/navigation";
import GoogleSignIn from "@/components/google-sign-in";
import { signIn, useMe } from "@/lib/auth";
// 완성본 구경은 로그인 없이 연다. 백엔드의 /api/archive 와 같은 규칙
const OPEN_PATHS = ["/archive", "/playreel/archive"];
export default function AuthGate({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const { me, setMe } = useMe();
const [error, setError] = useState<string | null>(null);
if (OPEN_PATHS.some((open) => pathname === open || pathname.startsWith(`${open}/`))) {
return <>{children}</>;
}
if (me === null) {
return <p style={{ color: "var(--color-text-gray-400)" }}>확인하는 중…</p>;
}
if (me === false) {
return (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center",
gap: "1.5rem", paddingTop: "6rem" }}>
<h1 className="page-title">로그인이 필요합니다</h1>
<p className="page-subtitle">구글 계정으로 들어와 주세요.</p>
<GoogleSignIn onCredential={(credential) => {
setError(null);
signIn(credential).then(setMe).catch((failure) => setError((failure as Error).message));
}} />
{error && <p style={{ color: "#ff7a7a", fontSize: "var(--text-sm)" }}>{error}</p>}
</div>
);
}
return <>{children}</>;
}
+54
View File
@@ -0,0 +1,54 @@
"use client";
/** 구글이 그려주는 버튼. 우리가 모양을 흉내 내면 브랜드 규정에 걸린다 */
import { useEffect, useRef, useState } from "react";
import {
fetchConfig, loadGoogleIdentity, type GoogleButtonOptions,
} from "@/lib/auth";
export default function GoogleSignIn({ onCredential, text = "signin_with" }: {
onCredential: (credential: string) => void;
text?: GoogleButtonOptions["text"];
}) {
const host = useRef<HTMLDivElement>(null);
const [error, setError] = useState<string | null>(null);
// 콜백이 매 렌더마다 바뀌어도 구글에 다시 등록하지 않게 최신 것만 들고 있는다
const latest = useRef(onCredential);
latest.current = onCredential;
useEffect(() => {
let cancelled = false;
(async () => {
const config = await fetchConfig();
if (!config.enabled) throw new Error("구글 로그인이 설정되지 않았습니다");
const google = await loadGoogleIdentity();
if (cancelled || !host.current) return;
google.initialize({
client_id: config.client_id,
callback: (response) => {
if (response.credential) latest.current(response.credential);
},
auto_select: false,
cancel_on_tap_outside: true,
});
google.renderButton(host.current, {
type: "standard", theme: "filled_black", size: "large",
shape: "pill", text, logo_alignment: "center", width: 320,
});
})().catch((failure) => {
if (!cancelled) setError((failure as Error).message);
});
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [text]);
if (error) {
return <p style={{ color: "#ff7a7a", fontSize: "var(--text-sm)", margin: 0 }}>{error}</p>;
}
return <div ref={host} style={{ display: "flex", justifyContent: "center" }} />;
}
+122
View File
@@ -0,0 +1,122 @@
"use client";
/**
* 구글 로그인.
* 브라우저가 구글에서 받은 credential 을 서버에 한 번 넘기면, 그 뒤로는 HttpOnly 쿠키가
* 붙는다 — 토큰을 프론트가 들고 있지 않는다.
*
* GIS 스크립트는 여기서 붙인다. 로그인 화면에 오기 전에는 서드파티 요청을 만들지 않는다.
*/
import { useEffect, useState } from "react";
import { apiFetch } from "@/lib/api";
const SCRIPT_URL = "https://accounts.google.com/gsi/client?hl=ko";
const SCRIPT_ID = "google-identity-services";
export interface Me {
email: string;
name: string;
jobs_created: number;
job_limit: number;
jobs_left: number;
}
export interface AuthConfig {
enabled: boolean;
client_id: string;
}
type CredentialResponse = { credential?: string };
export type GoogleButtonOptions = {
type?: "standard" | "icon";
theme?: "outline" | "filled_blue" | "filled_black";
size?: "small" | "medium" | "large";
shape?: "rectangular" | "pill" | "circle" | "square";
text?: "signin_with" | "signup_with" | "continue_with" | "signin";
width?: number;
logo_alignment?: "left" | "center";
};
type GoogleIdApi = {
initialize(config: {
client_id: string;
callback: (response: CredentialResponse) => void;
auto_select?: boolean;
cancel_on_tap_outside?: boolean;
}): void;
renderButton(parent: HTMLElement, options: GoogleButtonOptions): void;
disableAutoSelect(): void;
};
declare global {
interface Window {
google?: { accounts?: { id?: GoogleIdApi } };
}
}
// 스크립트는 한 번만 받는다
let loading: Promise<GoogleIdApi> | null = null;
export function loadGoogleIdentity(): Promise<GoogleIdApi> {
const ready = window.google?.accounts?.id;
if (ready) return Promise.resolve(ready);
if (loading) return loading;
loading = new Promise<GoogleIdApi>((resolve, reject) => {
const done = () => {
const api = window.google?.accounts?.id;
if (api) resolve(api);
else reject(new Error("구글 스크립트에 accounts.id 가 없습니다"));
};
const fail = () => {
// 다음 시도에서 다시 받을 수 있게 비운다 — 광고 차단기나 사내망에서 한 번 막히는 일이 흔하다
loading = null;
reject(new Error("구글 로그인 스크립트를 받지 못했습니다"));
};
const existing = document.getElementById(SCRIPT_ID) as HTMLScriptElement | null;
if (existing) {
existing.addEventListener("load", done, { once: true });
existing.addEventListener("error", fail, { once: true });
return;
}
const script = document.createElement("script");
script.id = SCRIPT_ID;
script.src = SCRIPT_URL;
script.async = true;
script.defer = true;
script.addEventListener("load", done, { once: true });
script.addEventListener("error", fail, { once: true });
document.head.appendChild(script);
});
return loading;
}
export const fetchConfig = () => apiFetch<AuthConfig>("/api/auth/config");
export const signIn = (credential: string) =>
apiFetch<Me>("/api/auth/google", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ credential }),
});
export const signOut = () => apiFetch<{ ok: boolean }>("/api/auth/logout", { method: "POST" });
/** 로그인 여부. null 이면 아직 확인 중, false 면 로그아웃 상태 */
export function useMe() {
const [me, setMe] = useState<Me | null | false>(null);
const refresh = () =>
apiFetch<Me>("/api/auth/me").then(setMe).catch(() => setMe(false));
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- 최초 1회 확인
refresh();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { me, refresh, setMe };
}
+1 -1
View File
@@ -3,7 +3,7 @@
/**
* 브라우저 로컬 환경설정 — 게이트 자동 승인.
* 키 `playreel.autoApprove` = { fetch_confirm?: true, narration_confirm?: true }
* 대상은 크레딧이 들지 않고 되돌릴 수 있는 게이트(①·③)뿐. ②·④·⑤는 GATE_META.credits/비가역이라 제외.
* 대상은 되돌릴 수 있는 게이트(①·③)뿐. ②·④·⑤는 비가역이라 제외.
* 서버에는 저장하지 않는다(사용자별 계정 개념이 아직 없음). 서버 `approve` 자동 호출은 /playreel/[id] 에서.
*/