feat(auth): 카카오 로그인 — o2o-castad-backend 인증 스택 이식

백엔드 (castad 와 동일 흐름, triplepick 스타일로 재작성):
- users/refresh_tokens 테이블 (신규 — create_all 로 자동 생성)
- 카카오 OAuth (code → 토큰 → 사용자 정보), aiohttp 대신 httpx
- JWT HS256 access 60분 / refresh 7일, Refresh Token Rotation
  (재사용 감지 시 TOKEN_REVOKED, castad 동일 에러 코드 체계)
- /api/auth/{kakao/login, kakao/callback, refresh, logout, me}
- 콜백 → 프론트 리다이렉트는 쿼리 대신 해시 프래그먼트로 토큰 전달
  (서버 로그·Referer 에 토큰 노출 방지 — castad 방식에서 한 단계 보강)
- 크레딧·소셜계정 연동 등 castad 전용 개념은 제외

프론트:
- lib/auth.ts — 토큰 보관·자동 갱신·/me 캐시·useAuth 훅
- Hero 에 카카오 로그인 버튼(브랜드 노랑) / 프로필 칩 + 로그아웃
- 투표 폼(Arena) 이메일을 로그인 계정 이메일로 자동 채움
  (기존 이메일 기반 투표·리더보드 파이프라인은 그대로 유지)

설정: KAKAO_CLIENT_ID/SECRET/REDIRECT_URI, JWT_SECRET (.env.example 참고)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
JinwooKimandClaude Opus 5 committed 2026-08-14 15:42:54 +09:00
1 parent e2d1647100
commit 7705099c64
11 files changed
+684 -4

No files matched your search

+6
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { outcomeLabel, pctParts, kickoffDisplay, winProb } from "@/lib/format";
import { type Lang, dict, teamShort } from "@/lib/i18n";
import { useAuth } from "@/lib/auth";
import type {
Outcome,
CrowdStats,
@@ -112,6 +113,11 @@ export default function Arena({
const [step, setStep] = useState<Step>("form");
const [recentEmails, setRecentEmails] = useState<string[]>(getRecentEmails);
const [email, setEmail] = useState(""); // 칸은 비우고, 입력/포커스 시 datalist 드롭다운으로만 자동완성
// 카카오 로그인 시 계정 이메일을 투표 이메일로 자동 채움 (수정은 자유)
const { user: authUser } = useAuth();
useEffect(() => {
if (authUser?.email) setEmail((cur) => cur || authUser.email!);
}, [authUser]);
const [notify, setNotify] = useState(true);
const [crowd, setCrowd] = useState<CrowdStats>(initialCrowd);
const [copied, setCopied] = useState(false);
+57 -4
View File
@@ -2,8 +2,54 @@ import { Link, useNavigate } from "react-router-dom";
import ShareButton from "./ShareButton";
import LangSwitch from "./LangSwitch";
import { type Lang, dict } from "@/lib/i18n";
import { useAuth } from "@/lib/auth";
import type { League } from "@/lib/types";
// 카카오 로그인 버튼(브랜드 노랑) ↔ 로그인 시 프로필 칩 + 로그아웃
function AuthChip({ lang }: { lang: Lang }) {
const { user, login, logout } = useAuth();
if (user) {
return (
<span className="flex items-center gap-1.5">
<span className="flex max-w-[130px] items-center gap-1.5 rounded-full border border-white/12 bg-white/8 py-1 pl-1 pr-2.5">
{user.profileImageUrl ? (
<img
src={user.profileImageUrl}
alt=""
className="h-5 w-5 rounded-full object-cover"
/>
) : (
<span className="grid h-5 w-5 place-items-center rounded-full bg-white/15 text-[10px]">
👤
</span>
)}
<span className="truncate text-[11px] font-bold text-white/85">
{user.nickname || user.email || "회원"}
</span>
</span>
<button
onClick={logout}
className="rounded-full border border-white/12 px-2 py-1 text-[10px] font-bold text-white/45 transition active:scale-95"
>
{lang === "en" ? "Sign out" : "로그아웃"}
</button>
</span>
);
}
return (
<button
onClick={login}
className="flex items-center gap-1 rounded-full bg-[#FEE500] px-2.5 py-1 text-[11px] font-extrabold text-[#191919] transition active:scale-95"
>
{/* 카카오 말풍선 심볼 */}
<svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="#191919">
<path d="M12 3C6.48 3 2 6.58 2 11c0 2.84 1.87 5.33 4.68 6.75-.15.53-.97 3.36-1 3.58 0 0-.02.17.09.24.11.07.24.02.24.02.32-.05 3.7-2.42 4.28-2.83.55.08 1.12.12 1.71.12 5.52 0 10-3.58 10-8S17.52 3 12 3z" />
</svg>
{lang === "en" ? "Sign in" : "로그인"}
</button>
);
}
type Share = { url: string; title: string; text: string };
// 브랜드 헤더 (대시보드·상세 공용). 경기별 후킹 카피는 상세 페이지에서 별도 노출.
@@ -31,7 +77,7 @@ export default function Hero({
};
return (
<header className="pt-5 text-center">
{back && (
{back ? (
<div className="mb-3 flex items-center justify-between">
<Link
to={home}
@@ -40,9 +86,16 @@ export default function Hero({
>
{t.back}
</Link>
{share && (
<ShareButton {...share} label={t.share} copiedLabel={t.shareCopied} />
)}
<span className="flex items-center gap-2">
<AuthChip lang={lang} />
{share && (
<ShareButton {...share} label={t.share} copiedLabel={t.shareCopied} />
)}
</span>
</div>
) : (
<div className="mb-1 flex justify-end">
<AuthChip lang={lang} />
</div>
)}
<div className="font-impact text-[44px] leading-none tracking-tight">
+130
View File
@@ -0,0 +1,130 @@
// 카카오 로그인 클라이언트 (o2o-castad 인증 이식과 짝).
// 토큰은 localStorage 보관, access 만료 시 refresh 로 1회 자동 갱신.
// 콜백은 백엔드가 `/#access_token=..&refresh_token=..` 으로 리다이렉트 — 앱 시작 시 캡처.
import { useEffect, useState } from "react";
const BASE = import.meta.env.VITE_API_BASE || "/api";
const KEY_ACCESS = "tp.auth.access";
const KEY_REFRESH = "tp.auth.refresh";
export interface AuthUser {
userUuid: string;
email: string | null;
nickname: string | null;
profileImageUrl: string | null;
}
// 콜백 해시에서 토큰 캡처 (main.tsx 렌더 전에 호출) — URL 에 토큰이 남지 않게 즉시 제거
export function captureAuthTokens(): void {
const h = window.location.hash;
if (!h.includes("access_token=")) return;
const params = new URLSearchParams(h.slice(1));
const access = params.get("access_token");
const refresh = params.get("refresh_token");
if (access && refresh) {
localStorage.setItem(KEY_ACCESS, access);
localStorage.setItem(KEY_REFRESH, refresh);
userCache = undefined; // 다음 getMe 에서 재조회
}
history.replaceState(null, "", window.location.pathname + window.location.search);
}
export function isLoggedIn(): boolean {
return !!localStorage.getItem(KEY_REFRESH);
}
function clearTokens(): void {
localStorage.removeItem(KEY_ACCESS);
localStorage.removeItem(KEY_REFRESH);
userCache = null;
notify();
}
async function tryRefresh(): Promise<boolean> {
const refresh = localStorage.getItem(KEY_REFRESH);
if (!refresh) return false;
const res = await fetch(`${BASE}/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: refresh }),
});
if (!res.ok) {
clearTokens(); // 만료/폐기 — 재로그인 필요
return false;
}
const d = await res.json();
localStorage.setItem(KEY_ACCESS, d.access_token);
localStorage.setItem(KEY_REFRESH, d.refresh_token); // rotation — 새 refresh 로 교체
return true;
}
// 인증 헤더로 호출, 401 이면 refresh 후 1회 재시도
async function authFetch(path: string, init?: RequestInit): Promise<Response> {
const call = () =>
fetch(`${BASE}${path}`, {
...init,
headers: {
...(init?.headers || {}),
Authorization: `Bearer ${localStorage.getItem(KEY_ACCESS) || ""}`,
},
});
let res = await call();
if (res.status === 401 && (await tryRefresh())) res = await call();
return res;
}
// /me 는 모듈 레벨 캐시 — 화면 여러 곳(Hero·Arena)에서 써도 1회만 조회
let userCache: AuthUser | null | undefined; // undefined=미조회, null=비로그인
let inflight: Promise<AuthUser | null> | null = null;
const listeners = new Set<() => void>();
const notify = () => listeners.forEach((fn) => fn());
export async function getMe(): Promise<AuthUser | null> {
if (userCache !== undefined) return userCache;
if (!isLoggedIn()) return (userCache = null);
inflight ??= (async () => {
try {
const res = await authFetch("/auth/me");
userCache = res.ok ? ((await res.json()) as AuthUser) : null;
} catch {
userCache = null;
} finally {
inflight = null;
}
notify();
return userCache;
})();
return inflight;
}
export async function startKakaoLogin(): Promise<void> {
const res = await fetch(`${BASE}/auth/kakao/login`);
const d = await res.json();
window.location.href = d.authUrl; // 카카오 인증 페이지로 이동
}
export async function logout(): Promise<void> {
const refresh = localStorage.getItem(KEY_REFRESH);
if (refresh) {
await fetch(`${BASE}/auth/logout`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: refresh }),
}).catch(() => {});
}
clearTokens();
}
// 로그인 상태 훅 — user(null=비로그인) 와 로그인/로그아웃 액션
export function useAuth() {
const [user, setUser] = useState<AuthUser | null>(userCache ?? null);
useEffect(() => {
const sync = () => setUser(userCache ?? null);
listeners.add(sync);
getMe().then(sync);
return () => {
listeners.delete(sync);
};
}, []);
return { user, login: startKakaoLogin, logout };
}
+3
View File
@@ -2,8 +2,11 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import { captureAuthTokens } from "./lib/auth";
import "./globals.css";
captureAuthTokens(); // 카카오 콜백 해시(#access_token=..) 캡처 — 라우터 마운트 전에
createRoot(document.getElementById("root")!).render(
<StrictMode>
<BrowserRouter>