今回は、ユーザーごとに複数データ持てるようにするためのルールと取得・登録処理について書いています。
ほかのユーザーのデータにはアクセスできず、書き込みもできないようにします。
目次
Collection作成
TasksというCollectionを例にしてみます。
フィールドにはtitle、userIdを入れます。
このuserIdがユーザーのトークンを格納する場所です。

フロント側のデータ取得
ログインしている前提ですが、以下のコードで自分のデータの取得と登録ができます。
const firebaseApp = firebase.initializeApp({
構成情報
});
const auth = firebase.auth();
export const db = firebaseApp.firestore();
...
必要なら以下のコードでログイン・サインアップなど
auth.signInWithEmailAndPassword(email, password);
auth.createUserWithEmailAndPassword(email, password);
auth.onAuthStateChanged((user: any) => {
// ログインState変更時の処理
});
...
// データ取得
db.collection("tasks").where("userId", "==", auth.currentUser.uid).onSnapshot((snapshot: any) => {
snapshot.docs.forEach(doc => {
// データ出力
console.log(doc.id);
console.log(doc.data().title);
console.log(doc.data().userId);
})
});
// データ登録
db.collection("tasks").add({ title: <タイトル>, userId: auth.currentUser.uid });
これだと、userIdに他ユーザーのトークンを指定すると、他ユーザーのデータも取得できてしまいます。
Cloud firestore側でルールを指定する必要があります。
firestoreのルール
こんな感じのルールにすると、自分のデータは自分のみが見れるようになります。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /tasks/{document} {
allow read: if request.auth.uid == resource.data.userId;
allow write: if request.auth.uid == request.resource.data.userId;
}
}
}
まずallow readのところ。
request.auth.uidはログインユーザーのトークンを表します。また、resource.data.userIdは保持されいているデータのユーザーのトークンを表します。
ログインしているユーザーのデータかどうかをチェックしているという内容です。
次にallow write。
request.resource.data.userIdは登録しようとしているトークンです。これがログイン中のユーザートークンと一致するかを見ています。
他ユーザーになりすまして登録できないようにしているということになります。