javascript - 如何防止重复投票react-firebase

标签 javascript reactjs firebase firebase-realtime-database firebase-security

我正在尝试防止 firebase 中的双重投票。我的想法是在 firebase 中创建一个投票对象,然后在每次有人投票时添加一个 user_id bool 值。所以 counterTips>votes>User_id1: true> UserId2: True。

这些是我的安全规则:

{

  "rules": {
    ".read": true,
    ".write": true,
      "CounterTips": {
     "votes": {
                "$uid": {
                    ".write": "auth.uid != null && auth.uid === $uid"
                }
              }
            }
  }


}

这就是我的数据库的结构方式

CounterTips 

 user_id: "rI9m9GEkyKhopAhaDNC8GNWPS943"

 vote: 5, 

 votes: 
1) bbz9MLo1u7T7zxugmHA806nMof93: true

我试图将当前用户 ID 插入 votes 对象,但只是得到一个静态字符串,其中显示 user_id: true。如何将实际的 user_id 推送到投票并防止该用户在安全规则中再次投票?

     upvotePost(key, vote, user_id) {

if (this.state.user_id !=null )
{

CounterTipsref.child("votes/${this.state.user_id}").once("value",snapshot => {
    if (snapshot.exists()){
      const userData = snapshot.val();
      console.log("exists!", userData);
    }


});
}

 else{
alert(this.state.user_id);
let user_id= this.state.user_id;
let votes = { [user_id]: true};

vote++;
CounterTipsRef.child(key).update({ 'vote': vote, 'votes': votes }); 
}
}
if (this.state.user_id==null) {

this.props.history.push('/login');
}


  }
}

最佳答案

您的问题是您正在使用以下表示法:

let votes = { user_id: true};

这里的user_id被视为属性的名称,而不是保存属性名称的变量。快速解决方法是使用 [] 表示法:

let votes = { };
votes[user_id] = true;

关于javascript - 如何防止重复投票react-firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213249/

相关文章:

javascript - 为什么我需要将匿名函数传递给 onClick 事件?

javascript - Chrome 显示加载 gif 的方式与 Safari 和 Firefox 不同

javascript - react native : How to pass props to 'routeMapper' of 'Navigator.NavigationBar' ?

get() 和 getAfter() 之间的 Firebase 安全规则区别

javascript - 如何使用云函数在 Firestore 中添加虚拟数据

javascript - 如何执行条件SQL查询,将结果打包为JSON,并发回客户端?

javascript - 如何计算交互式客户端的时间?

javascript - react 原生 + react 原生路由器通量 : Why is background color white during transition?

javascript - 是否可以仅更改material-ui中样式 Prop 中的一个属性

javascript - Firebase auth().signInWithEmailAndPassword 使用 try-catch async-await 未捕获错误