【发布时间】:2020-03-03 02:08:30
【问题描述】:
我想用 Angular 和 Firebase 制作一个应用程序。我想限制一个用户对我的数据库的读写访问。所以我制定了这个规则。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if "auth.uid === 'gzL3tHnx6JQexMuK4h2Nyo0thHS2'"
}
}
}
正如预期的那样,这会导致权限被拒绝错误。
框架使得从数据库中写入和获取数据、注册用户和登录变得非常简单。不幸的是,该框架不使用 HTTP 拦截器来附加 cred。到请求。可以以某种方式结合 AngularFirestore 和 AngularFire Auth 方法。下面的示例实现:
export class AppComponent {
private shirtCollection: AngularFirestoreCollection<Shirt>;
shirts: Observable<ShirtId[]>;
constructor(private readonly afs: AngularFirestore) {
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
}
private socialSignIn(provider: number): firebase.Promise<FirebaseAuthState> {
return this.af.auth.login({AuthProviders.Github, method: AuthMethods.Popup})
.then(() => this.updateUserData() )
.catch(error => console.log(error));
}
}
【问题讨论】:
-
请在每个帖子中限制自己一个问题。我在回答中使用安全规则纠正了您的错误。考虑将您的第二个问题拆分到另一个帖子中。
标签: angular firebase google-cloud-firestore angularfire firebase-security