博客网站的Firestore规则

时间:2017-12-23 14:52:53

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

我有一个简单的博客网站,每个人都可以查看帖子,但只有管理员可以编辑它们。

帖子集合文档如下所示:

{
  title:"Hello World",
  body:"Hello Brian"
},
{
  title:"Gumdrops",
  body:"Goody, goody gumdrops"
},

管理员集合文档如下所示:

{
  email:"josh@email.com"
},
{
  email:"steve@email.com"
}

My Cloud Firestore规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{post} {
      allow read;
      allow write: if get(/databases/$(database)/documents/admins/$(admin)).data.email == request.auth.token.email;
    }
  }
}

我收到错误Error: Missing or insufficient permissions.

在客户端,我使用的是AngularFire2,我的代码看起来如此:

import { Component } from '@angular/core';
import { AuthService } from '../auth/auth.service';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';

export interface Post {
  id?: string;
  title: string;
  body: string;
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent {

  private postsCollection: AngularFirestoreCollection<Post>;
  public posts:any;

  constructor(
    private afs: AngularFirestore,
    public authService: AuthService
  ) {
    this.postsCollection = afs.collection<Post>('posts');

    this.posts = this.postsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Post;
        data.id = a.payload.doc.id;
        return data;
      });
    });
  }

  addPost(post) {
    this.postsCollection.add(post).then((ret) => {
    console.log('post added');
  }, (error) => {
    console.log(error);
  });
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

FINALLY得到了它!

我的firestore规则错了。我创建了一个名为users的集合。 id是用户的电子邮件地址,其admin字段设置为true

然后,以下规则仅允许用户集合中列出的管理员进行更改。

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow write: if get(/databases/$(database)/documents/users/$(request.auth.token.email)).data.admin == true;
    }
  }
}

耶!