flutter - 无法将 request.auth.id 与 Firestore 规则中的文档 ID 匹配
问题描述
我正在用 Flutter 开发一个应用程序。我在 Firestore 上有一个数据库,其结构为:Users/(UserID)/collection/document 这里 UserID 是创建 (UserID) 文档的用户的唯一 uid。该代码用于获取用户的 uid 是
user.uid;
其中 user 是 FirebaseUser 的一个实例。我正在尝试设置规则,以便仅当 request.auth.uid 与(UserID)文档ID匹配时,只有用户可以读/写。
service cloud.firestore {
match /databases/{database}/documents {
match /Users/{documentID} {
allow read, write: if isOwner(documentID);
}
function isOwner(documentID){
return request.auth.uid == documentID;
}
}
}
但是我对此有误
失败:状态{code=PERMISSION_DENIED,描述=缺少或权限不足。,原因=null}
这是执行查询的代码。
class EmployeeList extends StatefulWidget {
static bool isMale;
final String userId;
EmployeeList([this.userId]);
void setIsMale(bool gen) {
isMale = gen;
}
bool get getIsMale => isMale;
@override
State<StatefulWidget> createState() => _EmployeeList();
}
class _EmployeeList extends State<EmployeeList> {
String employeeName;
final TextEditingController textEditingController =
TextEditingController();
String gender;
int keyIndex;
CollectionReference listColRef;
bool firstTime;
Firestore db = Firestore.instance;
@override
void initState() {
gender = EmployeeList().getIsMale ? "Male" : "Female";
listColRef =
db.collection('Users').document(widget.userId).collection('EmployeeList');
print(widget.userId);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
appBar: AppBar(
title: Text('Employees'),
),
body: Padding(
padding: const EdgeInsets.all(5),
child: StreamBuilder<QuerySnapshot>(
stream: listColRef.where('Gender', isEqualTo:
gender).snapshots(),
这是数据库的结构:https ://imgur.com/a/aI6UikO
解决方案
您的数据库规则与您的查询不匹配。您的查询正在尝试使用该模式在集合下查找文档/Users/{userId}/EmployeeList
。但是您的规则只允许访问/Users/{documentID}
. 如果要允许访问嵌套子集合中的文档,则需要确保整个路径匹配。例如:
match /Users/{userId}/EmployeeList/{id} {
allow read, write: if isOwner(userId);
}
推荐阅读
- sql - Mysql prepare 语句不返回任何内容。没有语法错误。为什么?
- python - 如果前一行中的 ID 匹配,则累积计数 - Python/Pandas
- angular - 如何在按钮单击事件Angular 4后更改文本值
- object - 运行时错误对象变量或未设置变量
- spring - 如何使用通用 dao 和服务层获取特定的继承实体
- java - SimpleJdbcCall 总是省略函数调用中的第一个参数
- hive - 如何使用 hive 检查分区是否存在
- cuda - 入住率低的原因
- .net - 在 azure 中部署时无法创建绝对文件路径
- javascript - 将对象数组转换为对象对象并分配特定键