Files
o2o-site-AEO/solution/frontend/src/pages/SignupPage.tsx
T
HyeongBaeYangandClaude Opus 5 34d9d12c3f [fix] solution/frontend: 카카오 버튼이 정작 /login 에 안 떴다 — 로그인 폼이 세 벌이다
SignInForm 에만 붙였는데 `/login`·`/signup` 은 그 컴포넌트를 쓰지 않고 **각자 폼을 갖고
있다**(구글 버튼도 세 군데에 따로 적혀 있었다). 번들에는 키가 구워졌고 isKakaoLoginEnabled()
도 true 였는데 화면에만 없어서, 설정 문제로 보이는 종류였다.

- pages/LoginPage: 카카오 버튼 추가. returnTo 로 `from`(원래 가려던 곳)을 넘긴다
- pages/SignupPage: 가입도 같은 동작이라 같은 버튼을 쓴다(처음 온 회원번호면 백엔드가 생성)

lint(react-router typegen + tsc + eslint) 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-30 16:58:13 +09:00

213 lines
7.8 KiB
TypeScript

import {useState, type FormEvent} from 'react';
import {Link, Navigate, useNavigate} from 'react-router';
import {UserPlus} from 'lucide-react';
import {googleLogin, signup} from '@/api';
import {GoogleSignInButton} from '@/components/auth/GoogleSignInButton';
import {KakaoSignInButton} from '@/components/auth/KakaoSignInButton';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {isGoogleLoginEnabled} from '@/lib/googleIdentity';
import {isKakaoLoginEnabled} from '@/lib/kakaoIdentity';
import {notify, notifyApiError} from '@/lib/notify';
import {establishSession} from '@/lib/session';
import {useAuthStore} from '@/stores/auth';
/** 회원가입. */
const ID_RE = /^[a-zA-Z][a-zA-Z0-9._-]{3,19}$/;
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const MIN_PASSWORD_LEN = 8;
export function SignupPage() {
const navigate = useNavigate();
const user = useAuthStore((s) => s.user);
const [form, setForm] = useState({
id: '',
password: '',
passwordConfirm: '',
name: '',
email: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);
if (user) return <Navigate to="/sites" replace />;
const set = (key: keyof typeof form) => (e: {target: {value: string}}) =>
setForm((prev) => ({...prev, [key]: e.target.value}));
const validate = (): string | null => {
if (!ID_RE.test(form.id)) return '아이디는 영문으로 시작하는 4~20자입니다(영문·숫자·. _ - 사용).';
if (form.password.length < MIN_PASSWORD_LEN) return `비밀번호는 ${MIN_PASSWORD_LEN}자 이상이어야 합니다.`;
if (form.password !== form.passwordConfirm) return '비밀번호가 서로 다릅니다.';
if (!EMAIL_RE.test(form.email)) return '이메일 형식을 확인해 주세요.';
return null;
};
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
const invalid = validate();
if (invalid) {
notify.error(invalid);
return;
}
setIsSubmitting(true);
try {
const res = await signup({
id: form.id.trim(),
password: form.password,
name: form.name.trim() || null,
email: form.email.trim(),
});
if (res.result?.success === false) {
notifyApiError({data: res}, '가입하지 못했습니다.');
return;
}
// 가입 응답에 토큰이 실려 온다 — 방금 정한 비밀번호를 다시 치게 하지 않는다.
if (!(await establishSession(res, form.id.trim()))) {
notifyApiError({data: res}, '가입은 됐지만 로그인 토큰이 오지 않았습니다. 다시 로그인해 주세요.');
navigate('/login', {replace: true});
return;
}
notify.success('가입이 완료되었습니다.');
navigate('/sites', {replace: true});
} catch (error) {
notifyApiError(error, '가입하지 못했습니다.');
} finally {
setIsSubmitting(false);
}
};
// 구글은 가입과 로그인이 같은 동작이다 — 처음 온 계정이면 백엔드가 그 자리에서 만든다.
const handleGoogle = async (credential: string) => {
setIsSubmitting(true);
try {
const res = await googleLogin({credential});
if (res.result?.success === false) {
notifyApiError({data: res}, '구글로 가입하지 못했습니다.');
return;
}
if (!(await establishSession(res, ''))) {
notifyApiError({data: res}, '로그인 응답에 토큰이 없습니다.');
return;
}
navigate('/sites', {replace: true});
} catch (error) {
notifyApiError(error, '구글로 가입하지 못했습니다.');
} finally {
setIsSubmitting(false);
}
};
return (
<div className="flex min-h-screen items-center justify-center bg-muted/30 px-4 py-8">
<form
onSubmit={handleSubmit}
className="w-full max-w-sm space-y-4 rounded-2xl border border-border bg-card p-7"
>
<div className="space-y-1 text-center">
{/* 로고는 어디서든 랜딩으로 돌아가는 문이다. */}
<Link to="/" className="mx-auto mb-3 block w-fit">
<img src="/brand/web4ai-wordmark.svg" alt="Web4Ai" className="h-9 w-auto" />
</Link>
<h1 className="text-sm font-medium text-muted-foreground">회원가입</h1>
<p className="text-xs text-muted-foreground">내 가게 사이트를 만들려면 계정이 필요합니다.</p>
</div>
<div className="space-y-3">
<div>
<label htmlFor="signup-id" className="mb-1.5 block text-xs font-semibold">
아이디
</label>
<Input
id="signup-id"
value={form.id}
onChange={set('id')}
autoComplete="username"
placeholder="영문으로 시작하는 4~20자"
required
/>
</div>
<div>
<label htmlFor="signup-pw" className="mb-1.5 block text-xs font-semibold">
비밀번호
</label>
<Input
id="signup-pw"
type="password"
value={form.password}
onChange={set('password')}
autoComplete="new-password"
placeholder={`${MIN_PASSWORD_LEN}자 이상`}
required
/>
</div>
<div>
<label htmlFor="signup-pw2" className="mb-1.5 block text-xs font-semibold">
비밀번호 확인
</label>
<Input
id="signup-pw2"
type="password"
value={form.passwordConfirm}
onChange={set('passwordConfirm')}
autoComplete="new-password"
required
/>
</div>
<div>
<label htmlFor="signup-name" className="mb-1.5 block text-xs font-semibold">
이름
</label>
<Input id="signup-name" value={form.name} onChange={set('name')} autoComplete="name" />
</div>
<div>
<label htmlFor="signup-email" className="mb-1.5 block text-xs font-semibold">
이메일
</label>
<Input
id="signup-email"
type="email"
value={form.email}
onChange={set('email')}
autoComplete="email"
required
/>
</div>
</div>
<Button type="submit" variant="primary" className="w-full" isLoading={isSubmitting}>
<UserPlus />
<span>가입하기</span>
</Button>
{(isKakaoLoginEnabled() || isGoogleLoginEnabled()) && (
<>
<div className="flex items-center gap-2">
<span className="h-px flex-1 bg-border" />
<span className="text-[11px] text-muted-foreground">또는</span>
<span className="h-px flex-1 bg-border" />
</div>
{/* ★ 카카오는 가입과 로그인이 같은 동작이다 — 처음 온 회원번호면 백엔드가 그 자리에서
계정을 만든다. 그래서 두 화면이 같은 버튼을 쓴다. */}
<KakaoSignInButton label="카카오로 가입하기" />
{isGoogleLoginEnabled() && (
<GoogleSignInButton onCredential={handleGoogle} text="signup_with" />
)}
</>
)}
<p className="text-center text-[11px] leading-relaxed text-muted-foreground">
이미 계정이 있으신가요?{' '}
<Link to="/login" className="font-medium text-primary underline-offset-2 hover:underline">
로그인
</Link>
</p>
</form>
</div>
);
}
// 라우트 모듈은 default export 를 요구한다(routes.ts 가 이 파일을 가리킨다).
export default SignupPage;