48 lines
2.3 KiB
TypeScript
48 lines
2.3 KiB
TypeScript
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen';
|
|
import { GoogleSignin, isErrorWithCode, isSuccessResponse, statusCodes } from '@react-native-google-signin/google-signin';
|
|
import { useMutation, useQuery } from '@tanstack/react-query';
|
|
import { useState } from 'react';
|
|
import { Platform, Pressable, View } from 'react-native';
|
|
import { Text } from '@/components/text';
|
|
|
|
/** 구글로 계속하기. 서버에 클라이언트 ID가 없거나 안드로이드가 아니면 그리지 않는다 */
|
|
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
|
|
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity, enabled: Platform.OS === 'android' }).data?.google_client_id;
|
|
const login = useMutation(googleLoginMutation());
|
|
const [busy, setBusy] = useState(false);
|
|
const [broken, setBroken] = useState(false);
|
|
|
|
const press = async () => {
|
|
if (!clientId) return;
|
|
setBroken(false);
|
|
setBusy(true);
|
|
try {
|
|
GoogleSignin.configure({ webClientId: clientId });
|
|
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
|
|
const res = await GoogleSignin.signIn();
|
|
if (!isSuccessResponse(res)) return;
|
|
const token = res.data.idToken;
|
|
if (!token) return onFail();
|
|
login.mutate({ body: { credential: token } }, { onSuccess: onResult, onError: onFail });
|
|
} catch (e) {
|
|
if (isErrorWithCode(e) && e.code === statusCodes.IN_PROGRESS) return;
|
|
console.error('[google] sign in', e);
|
|
setBroken(true);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
if (Platform.OS !== 'android' || !clientId) return null;
|
|
const pending = busy || login.isPending;
|
|
return (
|
|
<View className="gap-2">
|
|
<Pressable onPress={press} disabled={pending} className="rounded-full border-[1.5px] border-line bg-white p-3 disabled:opacity-60" accessibilityRole="button">
|
|
<Text className="text-center text-[15px] font-extrabold text-[#28304a]">{pending ? '구글로 로그인 중…' : '구글로 계속하기'}</Text>
|
|
</Pressable>
|
|
{broken && <Text className="text-center text-[13px] font-bold text-ink3">구글 로그인을 하지 못했어요. 잠시 뒤에 다시 해 주세요.</Text>}
|
|
</View>
|
|
);
|
|
}
|