Чтобы заставить клиента «зарегистрироваться» на сервере, вы должны использовать метод User#getIdToken()
, вызывая firebase.auth().currentUser.getIdToken(true)
. Если пользователь был удален, его следует отклонить с кодом ошибки 'auth/user-token-expired'
.
Из документации React Native Firebase *1009*, я буду использовать его в качестве основы 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
получит событие с текущим объектом пользователя. Здесь мы добавляем запрос идентификатора токена.
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);
}
});
}