You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查Firestore数组是否包含指定字段?实现FireCMS管理员身份验证

解决方案

1. 检查Firestore数组是否包含指定内容

根据数组存储的内容类型,采用不同的检查方式:

  • 普通值数组(字符串/数字等):直接用includes()方法
    // 示例:检查tags数组是否包含"admin"
    const hasAdminTag = entity.data.tags?.includes("admin");
    
  • 对象数组:用some()方法匹配对象字段
    // 示例:检查roles数组中是否有name为"admin"的对象
    const hasAdminRole = entity.data.roles?.some(item => item.name === "admin");
    
  • DocumentReference数组:通过引用的path或id属性判断
    // 示例:检查是否存在指向roles/admin的引用
    const hasAdminRef = entity.data.roles?.some(ref => ref.path === "roles/admin");
    

2. Admin UI身份验证实现

针对你的需求,修改authenticator.tsx代码,完成权限验证:

import {Authenticator} from "@camberi/firecms";
import {User as FirebaseUser} from "@firebase/auth";
import {userSchema} from "../schemas/user.schema";
import type {DocumentReference} from "firebase/firestore";

export const authenticator: Authenticator<FirebaseUser> = async ({ user, dataSource}) => {
    if (!user?.uid) return false;
    
    const entity = await dataSource.fetchEntity({
        path: `/users`,
        entityId: user.uid,
        schema: userSchema,
    });

    // 验证用户文档中是否存在roles/admin引用
    const isAdmin = entity.data.roles?.some((ref: DocumentReference) => 
        ref.path === "roles/admin" // 若引用路径带根斜杠则改为"/roles/admin"
    );

    if (isAdmin) return true;
    
    throw new Error('ERROR: Only admins allowed. Please contact your developer!');
};

关键说明:

  • 确保userSchema中roles字段已定义为引用数组类型(如referenceArray({ collection: "roles" })),这样entity.data.roles会被正确解析为DocumentReference数组。
  • 若你的Firestore引用完整路径包含根斜杠,需将判断条件改为ref.path === "/roles/admin"。
  • 使用可选链?.避免数组为undefined时抛出错误。

内容的提问来源于stack exchange,提问作者danieljancar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 16:39:21