o2o-site-AEO/solution/frontend/src/pages/SignupPage.tsx
Mina Choi 48109fdc99 [feat] solution/backend,frontend: id/pw 가입 · 구글 로그인 — 계정을 만들 길이 없던 걸 연다
계정 생성 API 가 아예 없었다(그동안 users 를 손으로 INSERT 했다). 로그인 화면은 있는데
그 뒤에 설 계정을 만들 방법이 제품에 없는 상태였다.

- auth_service.signup: 가입 = **새 회사(테넌트) 1개 + 첫 계정 1개**. users.company_id 가
  NOT NULL 이고 모든 도메인이 company 로 스코프돼서, 회사 없는 계정은 아무것도 못 만든다
- services/external/google_identity: 구글 ID 토큰의 서명·iss·만료에 더해 **aud(우리 client_id)와
  email_verified 를 본다.** aud 검사가 빠지면 남의 앱에 발급된 '진짜' 구글 토큰으로 우리 계정에
  들어온다 — 서명도 발급자도 전부 맞으므로 다른 검사로는 안 걸린다
- users.provider/provider_uid 추가, password NULL 허용, id 20→64자(google_<sub> 가 20자를 넘는다).
  provider 에 server_default 를 같이 준 이유: ORM default 는 raw INSERT(테스트 시드)에 안 먹어서
  NOT NULL 컬럼이면 그 경로가 통째로 깨진다
- attempt_login: 소셜 계정을 먼저 끊는다. 안 끊으면 bcrypt 가 None 해시를 만나 500 이다
- 같은 이메일이라도 id/pw 계정과 구글 계정을 **잇지 않는다.** 이으면 계정 선점이다 —
  남의 이메일로 먼저 만들어 둔 계정에 그 사람의 구글 로그인이 들어간다 → DECISIONS 1-5
- LoginPage 는 admin 과 공유라 selfServe 로 갈랐다. admin 은 가입 링크도 구글 버튼도 안 뜬다
  (admin 라우터에 /signup 이 없어 404 가 난다)
- GOOGLE_CLIENT_ID 는 루트 .env 한 곳. compose 가 VITE_GOOGLE_CLIENT_ID 로 흘려보낸다 —
  두 곳에 적으면 백엔드 aud 대조와 화면 버튼이 조용히 갈라진다

★ 이미 도는 DB 는 init.sql 을 다시 적용해야 한다(말미 ALTER 섹션).

pytest: auth 13건 + 구글 토큰 검증 8건(진짜 RSA 서명으로 aud·iss·만료·email_verified·변조
거절 확인) 통과. 전체 527 passed / 8 failed(전부 기존 실패, 인증과 무관).
tsc·eslint·vite build 통과.
2026-09-02 09:33:59 +09:00

219 lines
7.9 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 {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {isGoogleLoginEnabled} from '@/lib/googleIdentity';
import {notify, notifyApiError} from '@/lib/notify';
import {establishSession} from '@/lib/session';
import {useAuthStore} from '@/stores/auth';
/**
* 회원가입. 가입 = **새 회사(테넌트) 1개 + 그 회사의 첫 계정 1개** 다(백엔드 auth_service.signup).
*
* ★ 여기 검사는 서버 규칙(services/auth_service.py 의 _LOGIN_ID_RE·_MIN_PASSWORD_LEN)의 사본이다.
* 두 벌이라 어긋날 수 있지만, 서버가 마지막 방어선이고 여기는 "제출 전에 알려주는" 역할이다.
* 규칙을 바꾸면 두 곳을 같이 고친다.
*/
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: '',
companyName: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);
if (user) return <Navigate to="/" 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(),
company_name: form.companyName.trim() || null,
});
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('/', {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('/', {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">
<img src="/brand/web4ai-wordmark.svg" alt="Web4Ai" className="mx-auto mb-3 h-9 w-auto" />
<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>
<label htmlFor="signup-company" className="mb-1.5 block text-xs font-semibold">
<span className="font-normal text-muted-foreground">()</span>
</label>
<Input
id="signup-company"
value={form.companyName}
onChange={set('companyName')}
placeholder="비우면 이름으로 채웁니다"
/>
</div>
</div>
<Button type="submit" variant="primary" className="w-full" isLoading={isSubmitting}>
<UserPlus />
<span></span>
</Button>
{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>
<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>
);
}