在Firebase和Javascript中建立私人聊天

时间:2020-01-05 16:38:11

标签: javascript firebase google-cloud-firestore firebase-security

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

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

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

1 个答案:

答案 0 :(得分:1)

安全性规则未在您的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来构造的,因此无论哪个用户发送,它都将保持稳定。