[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 통과.
This commit is contained in:
1 parent
c250b656fd
commit
48109fdc99
37 files changed
+1554
-62
No files matched your search
@@ -1,25 +1,34 @@
|
||||
import {useState, type FormEvent} from 'react';
|
||||
import {Navigate, useLocation, useNavigate} from 'react-router';
|
||||
import {Link, Navigate, useLocation, useNavigate} from 'react-router';
|
||||
import {LogIn} from 'lucide-react';
|
||||
import {login, me, UserRole} from '@/api';
|
||||
import {googleLogin, login} 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 {notifyApiError} from '@/lib/notify';
|
||||
import {toAuthUser, useAuthStore} from '@/stores/auth';
|
||||
import {establishSession} from '@/lib/session';
|
||||
import {useAuthStore} from '@/stores/auth';
|
||||
|
||||
export function LoginPage() {
|
||||
/**
|
||||
* 로그인 화면. **사장님 앱과 내부 운영 화면이 같이 쓴다.**
|
||||
*
|
||||
* ★ `selfServe` 로 갈린다 — 사장님 앱은 스스로 가입하고 구글로도 들어오지만, 내부 운영 계정은
|
||||
* 우리가 만들어 준다. 가입 링크를 두 곳에 다 두면 admin 라우터에 없는 `/signup` 으로 보내
|
||||
* 404 가 난다(admin/src/app/router.tsx 에 그 경로는 없다).
|
||||
*/
|
||||
export function LoginPage({selfServe = true}: {selfServe?: boolean}) {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const signIn = useAuthStore((s) => s.signIn);
|
||||
|
||||
const [id, setId] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// ★ 기본 도착지를 '/' 로 둔다. 앱마다 홈이 다르고(사장님 → 빌더, 내부 → 사업장 목록)
|
||||
// 각 라우터의 '/' 리다이렉트가 이미 그걸 안다. 여기 경로를 박으면 한쪽에서 404 다.
|
||||
const from = (location.state as {from?: string} | null)?.from ?? '/';
|
||||
// 각 라우터의 '/' 리다이렉트가 이미 그걸 안다. 여기 경로를 박으면 한쪽에서 404 다.
|
||||
const from = (location.state as {from?: string} | null)?.from ?? '/';
|
||||
|
||||
if (user) return <Navigate to={from} replace />;
|
||||
|
||||
@@ -32,20 +41,10 @@ const from = (location.state as {from?: string} | null)?.from ?? '/';
|
||||
notifyApiError({data: res}, '아이디 또는 비밀번호를 확인해 주세요.');
|
||||
return;
|
||||
}
|
||||
// ★ RemoveNoneResponse 라 성공 응답에서도 토큰 필드가 빠져 올 수 있다.
|
||||
// 빈 토큰으로 로그인 상태를 만들면 이후 모든 요청이 401 로 흐른다 — 여기서 끊는다.
|
||||
if (!res.access_token || !res.refresh_token) {
|
||||
if (!(await establishSession(res, id))) {
|
||||
notifyApiError({data: res}, '로그인 응답에 토큰이 없습니다.');
|
||||
return;
|
||||
}
|
||||
const tokens = {accessToken: res.access_token, refreshToken: res.refresh_token};
|
||||
|
||||
// 토큰을 먼저 심어야 뒤이은 me() 가 Authorization 을 달고 나간다.
|
||||
signIn(tokens, {userId: '', id, role: UserRole.USER});
|
||||
|
||||
const meRes = await me();
|
||||
// 신원이 안 왔으면 방금 심은 임시 사용자를 그대로 둔다 — 토큰은 유효하므로 화면은 진행시킨다.
|
||||
if (meRes.user_id && meRes.id) signIn(tokens, toAuthUser(meRes));
|
||||
navigate(from, {replace: true});
|
||||
} catch (error) {
|
||||
notifyApiError(error, '로그인에 실패했습니다.');
|
||||
@@ -54,6 +53,26 @@ const from = (location.state as {from?: string} | null)?.from ?? '/';
|
||||
}
|
||||
};
|
||||
|
||||
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(from, {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">
|
||||
<form
|
||||
@@ -66,9 +85,13 @@ const from = (location.state as {from?: string} | null)?.from ?? '/';
|
||||
alt="Web4Ai"
|
||||
className="mx-auto mb-3 h-9 w-auto"
|
||||
/>
|
||||
<h1 className="text-sm font-medium text-muted-foreground">관리자</h1>
|
||||
<h1 className="text-sm font-medium text-muted-foreground">
|
||||
{selfServe ? '로그인' : '관리자'}
|
||||
</h1>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
사업장·정보 확인·발행을 관리합니다.
|
||||
{selfServe
|
||||
? '내 가게 사이트를 만들고 발행합니다.'
|
||||
: '사업장·정보 확인·발행을 관리합니다.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -105,12 +128,25 @@ const from = (location.state as {from?: string} | null)?.from ?? '/';
|
||||
<span>로그인</span>
|
||||
</Button>
|
||||
|
||||
<p className="text-center text-[11px] leading-relaxed text-muted-foreground">
|
||||
빌더는 로그인 없이도 사용할 수 있습니다.{' '}
|
||||
<a href="/builder" className="font-medium text-primary underline-offset-2 hover:underline">
|
||||
빌더로 이동
|
||||
</a>
|
||||
</p>
|
||||
{selfServe && 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="continue_with" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{selfServe && (
|
||||
<p className="text-center text-[11px] leading-relaxed text-muted-foreground">
|
||||
아직 계정이 없으신가요?{' '}
|
||||
<Link to="/signup" className="font-medium text-primary underline-offset-2 hover:underline">
|
||||
회원가입
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user