Google SignIn در react-native با استفاده از Firebase auth

اگر به دنبال راه حلی بدون فایربیس هستید، من یک مقاله متوسط برای آن دارم: https://medium.com/@ibjects/google-signin-tutorial-for-react-native-81a57fb67b18
روشی مستقیم برای پیاده سازی ورود به سیستم گوگل در یک برنامه بومی react با استفاده از firebase.
کنسول Firebase
اضافه کردن Google از ارائه دهندگان اضافی.
خود را یادداشت کنید Web client ID.

پس از انجام آن باید به شکل زیر باشد:

React-Native
بیایید کتابخانه های مورد نیاز را نصب کنیم:
yarn add @react-native-firebase/app @react-native-firebase/auth
yarn add @react-native-google-signin/google-signin
ایجاد یک Login.tsx صفحه نمایش در اینجا چند چیز وجود دارد که با هم کار می کنند:
- چک کردن
onAuthStatusChangedاستفاده كردنauthاز جانب@react-native-firebase/authبرای بررسی وضعیت فعلی احراز هویت کاربر. - پیکربندی کنید
GoogleSigninاستفاده كردنGoogleSignin.configureجایی که ما ارائه خواهیم کردwebClientIdکه باید در زمان پیکربندی کناری کنسول firebase داشته باشید. - رسیدگی
onGoogleButtonPressوrenderGoogleSigninButtonهمانطور که ما در حال ایجاد دکمه خودمان برای راه اندازی a هستیمGoogleSigninدرخواست. - هنگامی که یک کاربر وارد سیستم می شود، a را رندر می کند
renderLogoutViewوreturnاجزای اصلی.
در زیر کد برای Login.tsx طبق لیست اعداد بالا تفکیک شده است:
// 1.
import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth';
// other imports and code
const [user, setUser] = React.useState();
function onAuthStatusChanged(user: FirebaseAuthTypes.User | null) {
setUser(user);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStatusChanged);
return subscriber; // unsubscribe on unmount
}, []);
// 2.
import { GoogleSignin } from "@react-native-google-signin/google-signin";
//... other imports and everything in 1.
GoogleSignin.configure({
webClientId: 'ADD_YOUR_KEY_HERE',
offlineAccess: true,
});
در صورت نیاز، جستجو کنید Web client ID به بالا مراجعه کنید تا بدانید از کجا آن را تهیه کنید.
// 3a. onGoogleButtonPress
async function onGoogleButtonPress() {
if (user) {
// user is already logged in so no need to do anything
return null;
}
try {
// Check if your device supports Google Play
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
// Get the users ID token
const { idToken, user, serverAuthCode } = await GoogleSignin.signIn(); // returns type: User
const { id, name, email, photo, familyName, givenName } = user;
console.log('serverAuthCode: ', serverAuthCode);
console.log('idToken: ', idToken);
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
} catch (error) {
console.error('ERROR: ', error);
return null;
}
}
با یک ساده GoogleSignin.signIn() به طور خودکار همه چیز را کنترل می کند.
اکنون مولفه دکمه ورود به سیستم گوگل را پیاده سازی می کنیم:
// 3b. renderGoogleSigninButton
const renderGoogleSigninButton = () => {
const buttonTitle = user ? `Signed in as: ${user.displayName}` : 'Continue with Google'
return (
onGoogleButtonPress().then((value: FirebaseAuthTypes.UserCredential | null) => {
// The onGoogleButtonPress will update the setUser state, so no action needed here
if (value) {
console.log('value.additionalInnfo: ', value.additionalUserInfo);
console.log('value.user: ', value.user);
}
}).catch((error) => {
if (isErrorWithCode(error)) {
switch (error.code) {
case statusCodes.SIGN_IN_CANCELLED:
// user cancelled the login flow
Alert.alert("User cancelled the login flow. Please try again.");
break;
case statusCodes.IN_PROGRESS:
// operation (eg. sign in) already in progress
Alert.alert("Sign In already in progress. Please wait.");
break;
case statusCodes.PLAY_SERVICES_NOT_AVAILABLE:
// play services not available or outdated
Alert.alert("Play services not available or outdated. Please update your play services.");
break;
default:
// some other error happened
Alert.alert("An unknown error occurred. Please try again later.");
}
} else {
// an error that's not related to google sign in occurred
Alert.alert("An error that's not related to google sign in occurred. Please try again later.");
}
})}>
{buttonTitle}
)
}
مرحله 4، اجازه دهید آن را به قسمت های کوچکتر تقسیم کنیم:
- پیاده سازی
signOutاستفاده كردنauth - اجرای الف
renderLogoutViewبرای پیاده سازی خروج. - صفحه اصلی
Componentsکه شامل دکمه های ورود و خروج است
// 4a.Implement `signOut` using `auth`
// src/api/FirebaseAuthUtils.ts
import auth from '@react-native-firebase/auth';
export function userLogout(): Promise {
return new Promise((resolve, reject) => {
auth()
.signOut()
.then(() => {
resolve('Logout Successful');
})
.catch(error => {
reject({
title: 'Error',
desc: error.message,
});
});
});
}
یک فایل جدید در src/api/FirebaseAuthUtils.ts و یک تابع خروج اضافه کرد.
همه چیز در زیر موجود است Login.tsx
// 4b. Implement a `renderLogoutView` to implement logout.
import { userLogout } from "../api/FirebaseAuthUtils";
//... other imports
const renderLogoutView = () => {
if (user) {
return (
{
userLogout().then((message) => {
Alert.alert(message);
}).catch(error => {
Alert.alert(error.title, error.desc);
});
}}>
Logout
)
}
}
// 4c. Main screen `Components` that include login and logout buttons
return (
{!user && <>
New or returning user, press{'\n'}
Continue with Google
to continue
{renderGoogleSigninButton()}
>}
{renderLogoutView()}
)
این همه کد مورد نیاز است. بعد بیایید تستش کنیم
آزمایش کردن
من روی شبیه ساز و دستگاه تست کردم، کار می کند.
من وارد نشده ام، بنابراین دکمه ورود را نشان می دهد:

من وارد سیستم شده ام، بنابراین دکمه خروج را نشان می دهد:

کاربر را برای تأیید به صفحه ورود به سیستم Google می برد.

تست خروج از سیستم و مطابق انتظار کار می کند.

خطاها
اگر این خطا را دریافت می کنید:
LOG ERROR: [Error: DEVELOPER_ERROR]
LOG ERROR: 10 DEVELOPER_ERROR
اضافه کردن SHA-1 و SHA-256. اگر فقط دارید debug ساخت و سپس فقط برای آن اضافه کنید در غیر این صورت کل 4 را اضافه کنید. 2 برای debug و 2 برای release:

در زیر دستوری وجود دارد که می توانید برای دریافت تمام اثر انگشت SHA موجود اجرا کنید:
cd android && ./gradlew signingReport
برای پیدا کردن به پایین اسکرول کنید > Task :app:signingReport. در اینجا می توانید تمام اثر انگشت SHA موجود را پیدا کنید. من فقط دارم debug بنابراین برای من release و debug کلیدها یکسان هستند، بنابراین در تصویر بالا فقط دو اثر انگشت SHA را مشاهده می کنید.

این حل می کند 10 DEVELOPER_ERROR.
اگر دریافت می کنید:
[Error: SIGN_IN_REQUIRED]
مطمئن شوید که شما signOut به درستی پیکربندی شده است. سعی کنید برنامه را حذف کرده و دوباره نصب کنید.



