将 Apple Sign In 与 React Native Firebase 和 Firestore 一起使用时,如何检查用户是不是存在?
Posted
技术标签:
【中文标题】将 Apple Sign In 与 React Native Firebase 和 Firestore 一起使用时,如何检查用户是不是存在?【英文标题】:How can I check if User exists when using Apple Sign In with React Native Firebase and Firestore?将 Apple Sign In 与 React Native Firebase 和 Firestore 一起使用时,如何检查用户是否存在? 【发布时间】:2021-11-13 16:25:05 【问题描述】:我已经使用 Firebase 在我的 React Native App 中实现了 Apple 登录,并且登录过程运行良好。
我正在将用户详细信息添加到 Firestore 中名为“用户”的数据库集合中。
当用户重新登录时,从他们的个人资料添加到集合中的数据会被覆盖。
如何检查用户是否存在以便仅创建一次集合文档?
我的代码如下
appleSignIn: async () =>
try
const appleAuthRequestResponse = await appleAuth.performRequest(
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
);
if(!appleAuthRequestResponse.identityToken)
throw 'Apple Sign-In failed - no identify token returned';
const identityToken, nonce = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
await auth().signInWithCredential(appleCredential);
firestore().collection('users').doc(auth().currentUser.uid)
.set(
fname: appleAuthRequestResponse.fullName.givenName,
lname: appleAuthRequestResponse.fullName.familyName,
email: appleAuthRequestResponse.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: null,
)
catch (e)
console.log(e);
,
【问题讨论】:
【参考方案1】:您可以检查users
集合中是否存在用户。
...
await auth().signInWithCredential(appleCredential);
const existingUserDoc = await firestore().collection('users').doc(auth().currentUser.uid).get();
if (existingUserDoc && existingUserDoc.exists)
// you can do something here. user details already created.
else
firestore().collection('users').doc(auth().currentUser.uid)
.set(
fname: appleAuthRequestResponse.fullName.givenName,
lname: appleAuthRequestResponse.fullName.familyName,
email: appleAuthRequestResponse.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: null,
);
...
或者更简单的方法,如果用户文档存在,您可以通过firestore().collection('users').doc('uid').set(...)
执行。
...
await auth().signInWithCredential(appleCredential);
const existingUserDoc = await firestore().collection('users').doc(auth().currentUser.uid).get();
// ignore execution of setting user deatils.
if (!existingUserDoc && !existingUserDoc.exists)
firestore().collection('users').doc(auth().currentUser.uid)
.set(
fname: appleAuthRequestResponse.fullName.givenName,
lname: appleAuthRequestResponse.fullName.familyName,
email: appleAuthRequestResponse.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: null,
);
...
【讨论】:
以上是关于将 Apple Sign In 与 React Native Firebase 和 Firestore 一起使用时,如何检查用户是不是存在?的主要内容,如果未能解决你的问题,请参考以下文章
使用 Apple 登录按钮标题始终显示“SIGN_IN_WITH_APPLE”
Sign in with Apple(苹果授权登陆)服务端验证
Android Sign in with apple and firebase flutter