【发布时间】:2020-01-14 13:53:36
【问题描述】:
在调用“createUserWithEmailAndPassword”或“signInWithEmailAndPassword”后,属性“currentUser”变成了“auth()”。即使我从 Firebase 控制台中删除了此用户,它在重新启动应用程序后仍保持完整状态。
应用启动时如何查看用户的授权?
【问题讨论】:
标签: firebase react-native firebase-authentication
在调用“createUserWithEmailAndPassword”或“signInWithEmailAndPassword”后,属性“currentUser”变成了“auth()”。即使我从 Firebase 控制台中删除了此用户,它在重新启动应用程序后仍保持完整状态。
应用启动时如何查看用户的授权?
【问题讨论】:
标签: firebase react-native firebase-authentication
要强制客户端与服务器“签入”,您可以通过调用firebase.auth().currentUser.getIdToken(true) 来使用User#getIdToken() 方法。如果用户已被删除,则应该以错误代码'auth/user-token-expired' 拒绝。
来自React Native Firebase Quick Start documentation,我将使用它作为 MWE 的基础:
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import auth from '@react-native-firebase/auth';
function App() {
// Set an initializing state whilst Firebase connects
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
// Handle user state changes
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
if (initializing) return null;
if (!user) {
return (
<View>
<Text>Login</Text>
</View>
);
}
return (
<View>
<Text>Welcome {user.email}</Text>
</View>
);
}
一旦用户登录或他们的缓存访问被恢复,onAuthStateChanged 将收到一个包含当前用户对象的事件。这里我们添加 ID 令牌请求。
function onAuthStateChanged(user) {
if (!user) {
// not logged in
setUser(user);
if (initializing) setInitializing(false);
return;
}
user.getIdToken(/* forceRefresh */ true)
.then(token => {
// if here, this user is still authorised.
setUser(user);
if (initializing) setInitializing(false);
}, error => {
if (error.code === 'auth/user-token-expired') {
// token invalidated. No action required as onAuthStateChanged will be fired again with null
} else {
console.error('Unexpected error: ' + error.code);
}
});
}
【讨论】: