【问题标题】:Get all posts that were published in the last 12 hours获取过去 12 小时内发布的所有帖子
【发布时间】:2023-02-05 21:51:50
【问题描述】:

我正在尝试获取过去 12 小时内发布的所有帖子。我遇到的问题是我的安全规则似乎不允许我这样做。我不明白我的错误在哪里。

这是我的安全规则:

allow read : if resource.data.hour_limit > request.time;
//hour_limit is the time when the post document was created + 12 hours
          

这是我发送到我的数据库的查询:

//get the user document reference from its username
const usersCollRef = collection(db, 'users')
const userDocSnaps = (await getDocs(query(usersCollRef, where('username', '==', username)))).docs


//store the user document reference in a variable
const userDocRef = userDocSnaps[0].ref


//calculate timestamp of 12 hours ago from request time
const HOUR_LIMIT = Timestamp.fromMillis(Timestamp.now().toMillis() - Timestamp.fromMillis(hoursToSeconds(12) * 1000).toMillis())


//current query.................................................................................
const postsCollectionRef = collection(db, 'public_posts')
const postsQuery = query(postsCollectionRef,
        postsCollectionRef,
        orderBy('hour_limit','desc'),
        startAfter(lastPostTimestamp),
        endAt(HOUR_LIMIT),
        where('hour_limit','>',Timestamp.now()),
        limit(10),
)

const postsDocs = (await getDocs(postsQuery)).docs //this throws a missing permission error

我想查询作者发布的所有帖子,作为参考(userDocRef)存储在帖子文档中

我得到这个缺少权限的错误:

Error screenshot

提前致谢

【问题讨论】:

  • 您是否尝试查询集合中每个文档的十二小时差异,而不是在安全规则中应用此约束?

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


【解决方案1】:

您需要 request.resource 语法来访问数据

match /public_posts/{postID} {
    allow read : if request.resource.data.timestamp.toMillis() >= request.time.toMillis() - 43200000

【讨论】:

  • 这不起作用,因为 request.resource 是当您添加/设置包含新信息的文档时发送到数据库的对象,而我只获取该文档
猜你喜欢
  • 2013-10-20
  • 2022-11-17
  • 2015-11-26
  • 2012-07-05
  • 2016-04-11
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多