{"version":3,"sources":["../../src/utilities/canAccessAdmin.ts"],"sourcesContent":["import type { PayloadRequest } from '../types/index.js'\n\nimport { UnauthorizedError } from '../errors/UnauthorizedError.js'\n\n/**\n * Protects admin-only routes, server functions, etc.\n * The requesting user must either:\n * a. pass the `access.admin` function on the `users` collection, if defined\n * b. match the `config.admin.user` property on the Payload config\n * c. if no user is present, and there are no users in the system, allow access (for first user creation)\n * @throws {Error} Throws an `Unauthorized` error if access is denied that can be explicitly caught\n */\nexport const canAccessAdmin = async ({ req }: { req: PayloadRequest }) => {\n const incomingUserSlug = req.user?.collection\n const adminUserSlug = req.payload.config.admin.user\n\n if (incomingUserSlug) {\n const adminAccessFn = req.payload.collections[incomingUserSlug]?.config.access?.admin\n\n if (adminAccessFn) {\n const canAccess = await adminAccessFn({ req })\n\n if (!canAccess) {\n throw new UnauthorizedError()\n }\n // Match the user collection to the global admin config\n } else if (adminUserSlug !== incomingUserSlug) {\n throw new UnauthorizedError()\n }\n } else {\n const hasUsers = await req.payload.find({\n collection: adminUserSlug,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n // If there are users, we should not allow access because of `/create-first-user`\n if (hasUsers.docs.length) {\n throw new UnauthorizedError()\n }\n }\n}\n"],"names":["UnauthorizedError","canAccessAdmin","req","incomingUserSlug","user","collection","adminUserSlug","payload","config","admin","adminAccessFn","collections","access","canAccess","hasUsers","find","depth","limit","pagination","docs","length"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,iCAAgC;AAElE;;;;;;;CAOC,GACD,OAAO,MAAMC,iBAAiB,OAAO,EAAEC,GAAG,EAA2B;IACnE,MAAMC,mBAAmBD,IAAIE,IAAI,EAAEC;IACnC,MAAMC,gBAAgBJ,IAAIK,OAAO,CAACC,MAAM,CAACC,KAAK,CAACL,IAAI;IAEnD,IAAID,kBAAkB;QACpB,MAAMO,gBAAgBR,IAAIK,OAAO,CAACI,WAAW,CAACR,iBAAiB,EAAEK,OAAOI,QAAQH;QAEhF,IAAIC,eAAe;YACjB,MAAMG,YAAY,MAAMH,cAAc;gBAAER;YAAI;YAE5C,IAAI,CAACW,WAAW;gBACd,MAAM,IAAIb;YACZ;QACA,uDAAuD;QACzD,OAAO,IAAIM,kBAAkBH,kBAAkB;YAC7C,MAAM,IAAIH;QACZ;IACF,OAAO;QACL,MAAMc,WAAW,MAAMZ,IAAIK,OAAO,CAACQ,IAAI,CAAC;YACtCV,YAAYC;YACZU,OAAO;YACPC,OAAO;YACPC,YAAY;QACd;QAEA,iFAAiF;QACjF,IAAIJ,SAASK,IAAI,CAACC,MAAM,EAAE;YACxB,MAAM,IAAIpB;QACZ;IACF;AACF,EAAC"}