[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

+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;
}