import TableService from "../TableService"; import { AuthorityType } from "@prisma/client"; import { Policy, PolicyDefault } from "@lib/Policies"; import config from "@lib/config"; import { CRolePolicyContract } from "@lib/contracts/role-policy.contracts"; export default class RolePolicyTableService extends TableService { protected table = "RolePolicy"; async byId(id: string) { return this.pg.rolePolicy.findUnique({ where: { id } }); } async $upsertDefaultAuthorities() { const projectSlug = config.Server.projectSlug; const cairoProject = await this.pg.project.findUnique({ where: { slug: projectSlug } }); if (!cairoProject) throw new Error("Cairo Project Not Found!"); const project = cairoProject.id; const $chk = ({ id, name, policies }: PolicyDefault) => this.$upsertDefaultsAuthority(project, name, id, policies); await Promise.all(Object.values(config.RolePolicy).map($chk)); } private async $upsertDefaultsAuthority(projectId: string, name: string, id: string, userPolicies: Policy[]) { const rootAuthority = config.RolePolicy.Root.id; const authorityType = id === rootAuthority ? AuthorityType.Root : AuthorityType.RolePolicy; const authority = id === rootAuthority ? name : rootAuthority; // Set Root Authority to root if root const policies = Policy.asStrings(userPolicies); return this.pg.rolePolicy.upsert({ where: { id }, create: { projectId, id, name, policies, authority, authorityType }, update: { projectId, name, policies, authority, authorityType }, }); } async create(rp: CRolePolicyContract["Create"]) { return this.pg.rolePolicy.create({ data: rp }); } }