重新加载页面时,Firebase身份验证返回false



我目前正在使用Firebase Integration和React进行一个项目。我可以注册和登录,但我确实想要一些Guard,以便在我连接时访问"已连接"的页面,或者如果我没有连接,则重定向到断开连接状态的默认页面。

我为拥有不同的Routes编码了以下内容,并将其设置在App.tsx文件中:

const ConnectedRoute: React.FC<RouteProps>  = ({ component, ...rest }) => {
var route = <Route />
var connected = isConnected()
console.log(connected)
if (connected){
route = <Route {...rest} component={component}/>
}
else{
route = <Route {...rest} render={() => <Redirect to ="/welcome" />} />
}
return route
}
const UnconnectedRoute: React.FC<RouteProps>  = ({ component, ...rest }) => {
var route = <Route />
var connected = isConnected()
console.log(connected)
if (connected){
route = <Route {...rest} render={() => <Redirect to ="/home" />} />
}
else{
route = <Route {...rest} component={component}/>
}
return route
}
const App: React.FC = () => {
return (
<IonApp>
<IonReactRouter>
<IonRouterOutlet>
<Route exact path="/" render={() => <Redirect to="/welcome" />} />
<UnconnectedRoute path="/welcome" component={UnconnectedHome} exact />
<ConnectedRoute path="/home" component={ConnectedHome} exact />
<UnconnectedRoute path="/login" component={Login} exact />
<UnconnectedRoute path="/register" component={Register} exact />
<ConnectedRoute path="/events/create" component={CreateEvent} exact />
</IonRouterOutlet>
</IonReactRouter>
</IonApp>
)
};

对于firebase初始化,我做了以下操作:

export async function initializeApp(){
console.log("Checking if app is initialized...")
if (firebase.apps.length == 0){
console.log("App initializing...")
firebase.initializeApp(firebaseConfig);
await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
}
}

知道用户是否连接(作为cookie(的功能是这样的:

export function isConnected(){
const res = firebase.auth().currentUser
console.log(res)
return res !== null
}

尽管如此,当我重新加载选项卡时,它总是返回我FALSE

所以,我想知道如何在应用程序发布之前初始化firebase服务器?这是当前的问题吗?我目前对此一无所知,这让我非常沮丧。。。

如果你已经遇到这样的问题,那真的会对我有所帮助!

谢谢!

Firebase身份验证将用户的身份验证状态保存在本地存储中。但是,当您加载一个新页面(或重新加载现有页面(时,它必须与服务器检查身份验证状态是否仍然有效。此检查需要一些时间,在此期间还没有当前用户。

绕过这种竞争条件的典型方法是使用身份验证状态侦听器来检测当前用户:

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in, redirect to "connected" pages
} else {
// No user is signed in, probably require them to sign in
}
});

我试图用代码在注释中回答,但没有成功。

我现在这样做了(不是很好,但至少它有效(:

const connectedPaths = 
[
"/home",
"/events/create"           
]
const unconnectedPaths = 
[
"/welcome",
"/login", 
"register"
]
firebase.initializeApp(firebaseConfig);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
if (!connectedPaths.includes(window.location.pathname)) window.location.href = "/home"
} 
else {
if (!unconnectedPaths.includes(window.location.pathname)) window.location.href = "/welcome"
}
});

相关内容

最新更新