[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:
minaChoi committed 2026-09-02 09:33:59 +09:00
1 parent c250b656fd
commit 48109fdc99
37 files changed
+1554 -62

No files matched your search

+5
View File
@@ -9,3 +9,8 @@ VITE_PUBLISH_HOST=w4ai.o2o.kr
# 발행 사이트 렌더러 개발 서버. 에디터 상단 "발행본 사이트 열기" 가 이 주소를 연다.
VITE_SITE_PREVIEW_URL=http://localhost:3000
# 구글 로그인 클라이언트 ID. 비우면 구글 버튼이 아예 안 뜬다(누르면 실패하는 버튼을 두지 않는다).
# ★ 로컬에서 compose 없이 띄울 때만 쓴다. compose 로 띄우면 루트 .env 의 GOOGLE_CLIENT_ID 가
# 주입돼 이 값을 덮는다 — 백엔드의 aud 대조와 같은 값이어야 하므로 단일 출처는 루트 .env 다.
VITE_GOOGLE_CLIENT_ID=
@@ -25,7 +25,9 @@ import type {
import type {
HTTPValidationError,
ReqGoogleLogin,
ReqLogin,
ReqSignup,
ReqUpdateMe,
ResLogin,
ResMe,
@@ -105,6 +107,136 @@ export const useLogin = <TError = void | HTTPValidationError,
return useMutation(mutationOptions, queryClient);
}
/**
* id/pw 로 가입한다. 회사(테넌트) 1개가 함께 생기고, 성공하면 곧바로 로그인 토큰을 발급한다.
* @summary 회원가입
*/
export const signup = (
reqSignup: ReqSignup,
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResLogin>(
{url: `/v1/auth/signup`, method: 'POST',
headers: {'Content-Type': 'application/json', },
data: reqSignup, signal
},
options);
}
export const getSignupMutationOptions = <TError = void | HTTPValidationError,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext>, request?: SecondParameter<typeof customFetch>}
): UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext> => {
const mutationKey = ['signup'];
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof signup>>, {data: ReqSignup}> = (props) => {
const {data} = props ?? {};
return signup(data,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type SignupMutationResult = NonNullable<Awaited<ReturnType<typeof signup>>>
export type SignupMutationBody = ReqSignup
export type SignupMutationError = void | HTTPValidationError
/**
* @summary 회원가입
*/
export const useSignup = <TError = void | HTTPValidationError,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof signup>>,
TError,
{data: ReqSignup},
TContext
> => {
const mutationOptions = getSignupMutationOptions(options);
return useMutation(mutationOptions, queryClient);
}
/**
* 구글 ID 토큰(GIS credential)을 검증하고 JWT 토큰을 발급한다. 처음 온 계정은 그 자리에서 만든다.
* @summary 구글 로그인
*/
export const googleLogin = (
reqGoogleLogin: ReqGoogleLogin,
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResLogin>(
{url: `/v1/auth/google`, method: 'POST',
headers: {'Content-Type': 'application/json', },
data: reqGoogleLogin, signal
},
options);
}
export const getGoogleLoginMutationOptions = <TError = void | HTTPValidationError,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
): UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext> => {
const mutationKey = ['googleLogin'];
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof googleLogin>>, {data: ReqGoogleLogin}> = (props) => {
const {data} = props ?? {};
return googleLogin(data,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type GoogleLoginMutationResult = NonNullable<Awaited<ReturnType<typeof googleLogin>>>
export type GoogleLoginMutationBody = ReqGoogleLogin
export type GoogleLoginMutationError = void | HTTPValidationError
/**
* @summary 구글 로그인
*/
export const useGoogleLogin = <TError = void | HTTPValidationError,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof googleLogin>>,
TError,
{data: ReqGoogleLogin},
TContext
> => {
const mutationOptions = getGoogleLoginMutationOptions(options);
return useMutation(mutationOptions, queryClient);
}
/**
* refresh 토큰으로 access 토큰을 재발급한다.
* @summary 액세스 토큰 갱신
*/
@@ -0,0 +1,22 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
/**
* users.provider 코드값. 이 계정이 무엇으로 신원을 증명하는가.
한 계정은 수단 하나다 — 같은 이메일이라도 id/pw 계정과 구글 계정을 자동으로 잇지 않는다.
이으려면 "먼저 가입한 쪽의 소유"를 증명받아야 하는데, 그 증명 없이 이메일만 보고 이으면
남이 먼저 만들어 둔 계정에 내 구글 로그인이 들어간다(계정 선점). 보류 사유는 DECISIONS.md 1절.
*/
export type AuthProvider = typeof AuthProvider[keyof typeof AuthProvider];
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AuthProvider = {
LOCAL: 1,
GOOGLE: 2,
} as const;
@@ -7,6 +7,7 @@
export * from './auditCheckData';
export * from './auditCheckDataRecommendation';
export * from './authProvider';
export * from './buildStatus';
export * from './checkSlugParams';
export * from './companyData';
@@ -120,8 +121,12 @@ export * from './reqCreatePlace';
export * from './reqCreatePlaceOwnerUserId';
export * from './reqCreateUnit';
export * from './reqExtractFacts';
export * from './reqGoogleLogin';
export * from './reqLogin';
export * from './reqPublishLocalContent';
export * from './reqSignup';
export * from './reqSignupCompanyName';
export * from './reqSignupName';
export * from './reqSiteSlug';
export * from './reqSiteStatus';
export * from './reqSiteTemplate';
@@ -0,0 +1,16 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
/**
* 구글 로그인. 프론트(GIS)가 받은 ID 토큰을 그대로 넘긴다.
필드 이름이 `credential` 인 이유는 GIS 콜백이 주는 이름 그대로이기 때문이다 —
`access_token`/`id_token` 으로 바꿔 부르면 우리 토큰과 헷갈린다.
*/
export interface ReqGoogleLogin {
credential?: string;
}
@@ -0,0 +1,23 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
import type { ReqSignupName } from './reqSignupName';
import type { ReqSignupCompanyName } from './reqSignupCompanyName';
/**
* id/pw 가입. 가입 = 새 테넌트(회사) 1개 + 그 회사의 첫 계정 1개다.
★ 이메일을 필수로 받는 이유: 같은 이메일이 이미 구글로 가입돼 있는지 판단할 근거가 없으면
한 사람에게 계정이 둘 생긴다. 지금 이메일 인증 절차는 없다 — 소유 증명이 아니라
**중복 판정용** 이다.
*/
export interface ReqSignup {
id?: string;
password?: string;
name?: ReqSignupName;
email?: string;
company_name?: ReqSignupCompanyName;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
export type ReqSignupCompanyName = string | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
export type ReqSignupName = string | null;
@@ -10,6 +10,7 @@ import type { ResMeName } from './resMeName';
import type { ResMeEmail } from './resMeEmail';
import type { ResMeContactNumber } from './resMeContactNumber';
import type { UserRole } from './userRole';
import type { AuthProvider } from './authProvider';
import type { ResMeCompany } from './resMeCompany';
export interface ResMe {
@@ -21,5 +22,6 @@ export interface ResMe {
email?: ResMeEmail;
contact_number?: ResMeContactNumber;
role?: UserRole;
provider?: AuthProvider;
company?: ResMeCompany;
}
@@ -0,0 +1,76 @@
import {useEffect, useRef, useState} from 'react';
import {GOOGLE_CLIENT_ID, isGoogleLoginEnabled, loadGoogleIdentity} from '@/lib/googleIdentity';
/**
* 구글이 그려 주는 버튼을 그대로 쓴다.
*
* ★ 우리가 직접 만든 버튼을 쓰지 않는 이유: 구글 브랜드 가이드가 로고·문구·비율을 정해 두고,
* 그걸 어긋나게 그리면 심사에서 걸린다. renderButton 이 그 규격을 지켜 준다.
* ★ 스크립트가 안 오면(광고 차단기·사내망) 빈 칸이 남는다 — 안내 문구로 바꿔 준다.
* "눌러도 아무 일이 없는 자리"가 화면에 남는 게 제일 나쁘다.
*/
export function GoogleSignInButton({
onCredential,
text = 'continue_with',
}: {
onCredential: (credential: string) => void;
text?: 'continue_with' | 'signin_with' | 'signup_with';
}) {
const holder = useRef<HTMLDivElement>(null);
const [failed, setFailed] = useState(false);
// 콜백은 ref 로 들고 간다 — GIS 는 initialize 시점의 함수를 붙잡고 있어서,
// 의존성에 넣으면 렌더마다 버튼을 다시 그리게 된다.
const handler = useRef(onCredential);
handler.current = onCredential;
useEffect(() => {
if (!isGoogleLoginEnabled()) return;
let alive = true;
loadGoogleIdentity()
.then((api) => {
if (!alive || !holder.current) return;
api.initialize({
client_id: GOOGLE_CLIENT_ID,
callback: (res) => {
if (res.credential) handler.current(res.credential);
},
// 화면을 열자마자 마지막 계정으로 자동 로그인되는 동작은 끈다 —
// 계정이 여러 개인 사람이 원하지 않은 계정으로 들어간다.
auto_select: false,
});
api.renderButton(holder.current, {
type: 'standard',
theme: 'outline',
size: 'large',
shape: 'rectangular',
text,
locale: 'ko',
logo_alignment: 'center',
// GIS 는 숫자 px 만 받는다(최대 400). 컨테이너 폭이 잡히기 전이면 최소값으로 그린다.
width: holder.current.offsetWidth || 320,
});
})
.catch(() => {
if (alive) setFailed(true);
});
return () => {
alive = false;
};
}, [text]);
if (!isGoogleLoginEnabled()) return null;
if (failed) {
return (
<p className="text-center text-[11px] leading-relaxed text-muted-foreground">
구글 로그인을 불러오지 못했습니다. 아이디/비밀번호로 로그인해 주세요.
</p>
);
}
// 높이를 미리 잡아 둔다 — 버튼이 뒤늦게 그려지면서 아래 내용이 밀리지 않게.
return <div ref={holder} className="flex h-10 w-full items-center justify-center" />;
}
+3 -12
View File
@@ -1,6 +1,5 @@
import {getAccessToken, login, me} from '@/api';
import {UserRole} from '@/api';
import {toAuthUser, useAuthStore} from '@/stores/auth';
import {getAccessToken, login} from '@/api';
import {establishSession} from '@/lib/session';
/**
* 계정이 주입돼 있으면 화면을 열 때 조용히 세션을 확보한다.
@@ -28,15 +27,7 @@ export function ensureAutoSession(): Promise<void> {
pending = (async () => {
try {
const res = await login({id, password});
if (!res.access_token || !res.refresh_token) return;
const tokens = {accessToken: res.access_token, refreshToken: res.refresh_token};
// 순서가 중요하다. signIn 이 토큰을 저장하고, 그 토큰으로 me() 가 나간다 —
// 먼저 me() 를 부르면 토큰이 아직 없어 401 로 떨어진다(로그인 화면과 같은 순서다).
useAuthStore.getState().signIn(tokens, {userId: '', id, role: UserRole.USER});
const meRes = await me();
if (meRes.user_id && meRes.id) useAuthStore.getState().signIn(tokens, toAuthUser(meRes));
await establishSession(await login({id, password}), id);
} catch {
// 편의 기능이다 — 실패해도 화면을 막지 않는다(2단계가 안내를 띄운다).
} finally {
@@ -13,6 +13,12 @@ export const ERROR_MESSAGE: Record<string, string> = {
ACCOUNT_BLOCKED_USER: '차단된 계정입니다. 운영자에게 문의해 주세요.',
ACCOUNT_NOT_FOUND: '계정을 찾을 수 없습니다.',
ACCOUNT_FORBIDDEN: '이 작업을 할 권한이 없습니다.',
ACCOUNT_ALREADY_EXIST: '이미 사용 중인 아이디 또는 이메일입니다.',
// 자동 연결을 하지 않기로 한 결과라, "다시 시도" 가 아니라 **어느 쪽으로 들어가야 하는지**를 적는다.
ACCOUNT_PROVIDER_CONFLICT: '다른 방법으로 가입된 계정입니다. 처음 가입할 때 쓴 방법으로 로그인해 주세요.',
OAUTH_NOT_CONFIGURED: '구글 로그인이 아직 설정되지 않았습니다. 운영자에게 알려주세요.',
OAUTH_INVALID_TOKEN: '구글 로그인 정보를 확인하지 못했습니다. 다시 시도해 주세요.',
INVALID_REQUEST_DATA: '입력값을 다시 확인해 주세요.',
// 사업장 — 검증 게이트
PLACE_NOT_FOUND: '사업장을 찾을 수 없습니다.',
@@ -0,0 +1,91 @@
/**
* 구글 로그인(Google Identity Services) 어댑터.
*
* ★ 스크립트를 index.html 이 아니라 여기서 붙인다. client_id 가 없는 앱(내부 운영 화면)까지
* 구글 스크립트를 받아 오면, 쓰지도 않는 서드파티 요청이 모든 화면에 붙는다.
* ★ 여기서 받는 건 `credential`(구글 ID 토큰) 하나뿐이다. 그걸 백엔드에 넘기면 그다음부터는
* 우리 토큰이다 — 구글 토큰을 세션으로 들고 다니지 않는다.
* ★ client_id 는 비밀이 아니다(번들에 그대로 들어간다). 이 값으로 할 수 있는 건 "우리 앱 앞으로"
* 토큰을 받는 것뿐이고, 그 토큰이 우리 계정이 되려면 백엔드의 aud 대조를 통과해야 한다.
*/
const SCRIPT_URL = 'https://accounts.google.com/gsi/client';
const SCRIPT_ID = 'google-identity-services';
export const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID ?? '';
/** 빈 값이면 구글 로그인 자체를 화면에 올리지 않는다 — 누르면 실패하는 버튼을 두지 않는다. */
export function isGoogleLoginEnabled(): boolean {
return Boolean(GOOGLE_CLIENT_ID);
}
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';
locale?: string;
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> {
if (!isGoogleLoginEnabled()) return Promise.reject(new Error('GOOGLE_CLIENT_ID 없음'));
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('GIS 로드는 됐는데 accounts.id 가 없다'));
};
const fail = () => {
// 다음 시도에서 다시 받을 수 있게 비운다 — 광고 차단기·사내망에서 한 번 막히는 일이 흔하다.
loading = null;
reject(new Error('GIS 스크립트를 받지 못했다'));
};
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;
}
+24
View File
@@ -0,0 +1,24 @@
import {me, UserRole} from '@/api';
import type {ResLogin} from '@/api';
import {toAuthUser, useAuthStore} from '@/stores/auth';
/**
* 로그인 응답 → 세션. id/pw · 가입 · 구글이 **같은 마지막 단계**를 쓴다.
*
* ★ 순서가 중요하다. signIn 이 토큰을 먼저 저장해야 뒤이은 me() 가 Authorization 을 달고 나간다 —
* me() 를 먼저 부르면 토큰이 없어 401 로 떨어진다.
* ★ 성공 응답이라도 토큰이 없을 수 있다(RemoveNoneResponse 가 빈 필드를 통째로 지운다).
* 빈 토큰으로 로그인 상태를 만들면 이후 모든 요청이 401 로 흐르므로 여기서 끊는다.
*/
export async function establishSession(res: ResLogin, fallbackId: string): Promise<boolean> {
if (!res.access_token || !res.refresh_token) return false;
const tokens = {accessToken: res.access_token, refreshToken: res.refresh_token};
const store = useAuthStore.getState();
store.signIn(tokens, {userId: '', id: fallbackId, role: UserRole.USER});
const meRes = await me();
// 신원이 안 왔으면 방금 심은 임시 사용자를 그대로 둔다 — 토큰은 유효하므로 화면은 진행시킨다.
if (meRes.user_id && meRes.id) store.signIn(tokens, toAuthUser(meRes));
return true;
}
+62 -26
View File
@@ -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>
);
+218
View File
@@ -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>
);
}
+2
View File
@@ -7,6 +7,8 @@ interface ImportMetaEnv {
/** ⚠️ 번들에 구워진다 — 내부 테스트 호스트에서만 채운다(lib/autoSession). */
readonly VITE_AUTO_LOGIN_ID?: string;
readonly VITE_AUTO_LOGIN_PW?: string;
/** 구글 OAuth 클라이언트 ID. 비면 구글 로그인 버튼 자체가 안 뜬다(lib/googleIdentity). */
readonly VITE_GOOGLE_CLIENT_ID?: string;
}
interface ImportMeta {