使用Firebase和Java脚本进行私人聊天

问题描述 投票:0回答:1

我正在使用Firebase构建一个需要用户之间私人消息传递的应用程序。我需要为1-1聊天建立单个聊天,并将消息存储在Firestore中。

我的想法:我猜最好的方法是使用正确的安全规则为每个聊天构建单个集合。假设令牌ID为1234的用户想要与令牌ID为1111的用户交谈,将创建一个名为1234_1111的新集合(如果不存在),并且安全性将仅允许这两个用户进行读写。

我的问题:这是正确的方法吗?以及如何在Javascript中做到这一点?我不确定如何直接在JS代码中定义安全规则,也不确定如何使用两个用户ID创建集合。

javascript firebase google-cloud-firestore firebase-security
1个回答
0
投票

安全规则未在您的JavaScript代码中定义,它们是defined separately。尽管我将使用一个子集合,但您建议的建议是采取的合理方法,并且安全规则的简化版本可能类似于:

service cloud.firestore {
  match /databases/{database}/documents {
    match /dms/{idPair}/messages/{msgId} {
      allow read, write: if 
        idPair.split('_')[0] == request.auth.uid ||
        idPair.split('_')[1] == request.auth.uid;
    }
  }
}

然后,您可以在JS代码中执行以下操作:

// generate idPair
function dmCollection(uid) {
  const idPair = [firebase.auth().currentUser.uid, toUid].join('_').sort();
  return firebase.firestore().collection('dms').doc(idPair).collection('messages');
}

// send a DM
function sendDM(toUid, messageText) {
  return dmCollection(toUid).add({
    from: firebase.auth().currentUser.uid,
    text: messageText,
    sent: firebase.firestore.FieldValue.serverTimestamp(),
  });
}

// retrieve DMs
function messagesWith(uid) {
  return dmCollection(uid).orderBy('sent', 'desc').get();
}

请注意,idPair是通过加入一对已排序的UID构成的,因此无论哪个用户发送,它都将是稳定的。

© www.soinside.com 2019 - 2024. All rights reserved.