gpt4 book ai didi

firebase - 如何使用 firebase auth 限制对 next.js 中页面的访问?

转载 作者:行者123 更新时间:2023-12-04 13:02:03 25 4
gpt4 key购买 nike

我正在开发一个使用 firebase 的 next.js 应用程序。我需要使用 firebase auth 包来限制对页面的访问。 with-firebase-authentication 示例不显示多个页面的身份验证。

import React from 'react';
import Router from 'next/router';

import { firebase } from '../../firebase';
import * as routes from '../../constants/routes';

const withAuthorization = (needsAuthorization) => (Component) => {
class WithAuthorization extends React.Component {
componentDidMount() {
firebase.auth.onAuthStateChanged(authUser => {
if (!authUser && needsAuthorization) {
Router.push(routes.SIGN_IN)
}
});
}

render() {
return (
<Component { ...this.props } />
);
}
}

return WithAuthorization;
}

export default withAuthorization;

最佳答案

这是一个 React Firebase Authentication例如,但它应该适用于 next.js以及。

主要思想是创建一个高阶组件,它检查用户是否通过身份验证并围绕它包装所有页面:

import React from 'react';

const withAuthentication = Component => {
class WithAuthentication extends React.Component {
render() {
return <Component {...this.props} />;
}
}

return WithAuthentication;
};

export default withAuthentication;

您可以覆盖 _app.js并且只返回 <Component {...pageProps} />如果用户通过身份验证。

你可以这样做:
const withAuthorization = (needsAuthorization) => (Component) => {
class WithAuthorization extends React.Component {
state = { authenticated: null }
componentDidMount() {
firebase.auth.onAuthStateChanged(authUser => {
if (!authUser && needsAuthorization) {
Router.push(routes.SIGN_IN)
} else {
// authenticated
this.setState({ authenticated: true })
}
});
}

render() {
if (!this.state.authenticated) {
return 'Loading...'
}
return (
<Component { ...this.props } />
);
}
}

return WithAuthorization;
}

最好是在服务器上处理这个。

关于firebase - 如何使用 firebase auth 限制对 next.js 中页面的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54522858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com