Javascript 访问Firebase中的用户管理信息(ReactJS/Firebase自定义声明)
我正在对我的react应用程序使用firebase身份验证。在我的组件中,我使用以下内容:Javascript 访问Firebase中的用户管理信息(ReactJS/Firebase自定义声明),javascript,reactjs,firebase,firebase-authentication,Javascript,Reactjs,Firebase,Firebase Authentication,我正在对我的react应用程序使用firebase身份验证。在我的组件中,我使用以下内容: renderUser() { const user = firebase.auth().currentUser; console.log(user); return ( <div className="nav-actions-wrapper"> {user ? ( // Display post lin
renderUser() {
const user = firebase.auth().currentUser;
console.log(user);
return (
<div className="nav-actions-wrapper">
{user ? (
// Display post link here
<section className="nav-actions">
<a className="btn btn-primary mr-4" href="#" onClick={this.showPostShopPopup}>
Admin Post
</a>
<PostShopPopup
user={this.props.user}
status={this.state.postShopPopupStatus}
hidePopup={this.hidePostShopPopup}
/>
</section>
) : (
<section>
<a className="btn btn-outline-primary" href="#" onClick={this.showPopup}>
Log in
</a>
<LoginPopup status={this.state.popupStatus} hidePopup={this.hidePopup} />
</section>
)}
</div>
);
}
renderUser(){
const user=firebase.auth().currentUser;
console.log(用户);
返回(
{用户(
//在此处显示帖子链接
) : (
)}
);
}
我添加了一个自定义函数,通过自定义声明将提供的电子邮件设置为admin:true。现在,当我使用console.log(user)时,我在列表中看到admin:true
现在我如何访问它以便执行
{user.admin?…:}
?因为现在,当我这样做时,它会抛出一个错误,说无法读取null的属性“admin”
,即使在控制台日志中它被标记为admin:true
。自定义声明不能在对象中直接访问,以便您立即使用。您必须调用User对象才能获得声明。注意,它异步返回一个承诺并生成一个对象。此对象包含您要查找的代码段。首先在节点js服务器中运行此代码段
创建一个GET端点,只需发送一个简单的http请求,这样就可以运行并为要成为管理员的给定用户id创建一个自定义令牌(在Firebase令牌的customClaims字段中添加角色:“admin”)
Node.js:
admin.auth().setCustomUserClaims(${UID}, {admin: true}).then(claims =>
console.log(`CUSTOM CLAIMS ADDED: ${claims}`))
客户机(在我的例子中是有角度的,但逻辑是相同的,创建一个服务函数)
您需要来自身份验证模块的idTokenResult对象
async isAdmin() {
const { claims } = await firebase.auth().currentUser.getIdTokenResult()
return claims?.admin == true ? true || false
}
这将返回一个布尔值。您能否共享此
console.log(用户)的结果代码>?它返回一个包含用户所有信息的对象(email、emailVerified、photoURL等,以及一些其他不可读的对象和数组,包含奇怪的字母和东西),这只是带来了另一个问题,现在我的onlick={this.showPostPopup}
导致以下错误:无法读取未定义的属性“showPostShopPopup”
。我已经试着在我的构造函数中绑定它,但是它仍然会抛出错误。如果你有新问题,请单独发布,并解释什么东西现在不能按你期望的方式工作。