feat: 구글 로그인 — 로그인 창에 구글로 계속하기 버튼, 서버가 구글 ID 토큰 서명·클라이언트 ID·만료를 확인, 처음이면 자동 닉네임으로 가입(구글 이름·이메일은 저장 안 함)
This commit is contained in:
1 parent
eb2151164f
commit
4e9b0bacba
15 files changed
+407
-13
No files matched your search
@@ -25,6 +25,7 @@ import { track } from '../lib/analytics'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
import { GoogleButton } from './googleLogin'
|
||||
import { MixSheet } from './myGak'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { useSky } from './skyContext'
|
||||
@@ -808,13 +809,13 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
const signup = useMutation(signupMutation())
|
||||
const pending = login.isPending || signup.isPending
|
||||
|
||||
const done = (res: ResAuth) => {
|
||||
const done = (res: ResAuth, method: 'id' | 'google' = 'id') => {
|
||||
if (!res.result?.success || !res.access_token) {
|
||||
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')
|
||||
setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.'))
|
||||
return
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
|
||||
track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method })
|
||||
onLoggedIn()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
@@ -822,8 +823,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail })
|
||||
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail })
|
||||
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: (res) => done(res), onError: fail })
|
||||
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), onError: fail })
|
||||
}
|
||||
|
||||
if (me) return <MeSheet onDone={onDone} />
|
||||
@@ -832,7 +833,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
return (
|
||||
<Body>
|
||||
<form onSubmit={submit} className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<GoogleButton onResult={(res) => done(res, 'google')} onFail={fail} />
|
||||
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
|
||||
{(
|
||||
[
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { ResAuth } from '../api/client/types.gen'
|
||||
|
||||
type GoogleId = {
|
||||
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
|
||||
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
|
||||
}
|
||||
declare global {
|
||||
interface Window {
|
||||
google?: { accounts: { id: GoogleId } }
|
||||
}
|
||||
}
|
||||
|
||||
const SCRIPT = 'https://accounts.google.com/gsi/client'
|
||||
let loading: Promise<GoogleId> | null = null
|
||||
|
||||
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
|
||||
function loadGoogle(): Promise<GoogleId> {
|
||||
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
|
||||
loading ??= new Promise((resolve, reject) => {
|
||||
const s = document.createElement('script')
|
||||
s.src = SCRIPT
|
||||
s.async = true
|
||||
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
|
||||
s.onerror = () => {
|
||||
loading = null
|
||||
reject(new Error('gsi load failed'))
|
||||
}
|
||||
document.head.appendChild(s)
|
||||
})
|
||||
return loading
|
||||
}
|
||||
|
||||
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
|
||||
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
|
||||
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
|
||||
const login = useMutation(googleLoginMutation())
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const [broken, setBroken] = useState(false)
|
||||
const { mutate } = login
|
||||
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
|
||||
const cb = useRef({ onResult, onFail })
|
||||
useEffect(() => {
|
||||
cb.current = { onResult, onFail }
|
||||
}, [onResult, onFail])
|
||||
|
||||
useEffect(() => {
|
||||
if (!clientId || !box.current) return
|
||||
let alive = true
|
||||
loadGoogle().then(
|
||||
(g) => {
|
||||
if (!alive || !box.current) return
|
||||
g.initialize({
|
||||
client_id: clientId,
|
||||
ux_mode: 'popup',
|
||||
callback: (r) => {
|
||||
if (!r.credential) return cb.current.onFail()
|
||||
mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() })
|
||||
},
|
||||
})
|
||||
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[google] script', e)
|
||||
if (alive) setBroken(true)
|
||||
},
|
||||
)
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [clientId, mutate])
|
||||
|
||||
if (!clientId) return null
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
|
||||
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.</p>}
|
||||
<p className="m-0 flex items-center gap-2 text-[12.5px] font-bold text-(--ink3) before:h-px before:flex-1 before:bg-(--line) after:h-px after:flex-1 after:bg-(--line)">또는 아이디로</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user