Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
refactor: move permissions into its own table
Brad Barbin46c656eb0adc
diff --git a/apps/carbon/app/components/Layout/Navigation/useModules.tsx b/apps/carbon/app/components/Layout/Navigation/useModules.tsxindex cb7f957318..033933ec07 100644--- a/apps/carbon/app/components/Layout/Navigation/useModules.tsx+++ b/apps/carbon/app/components/Layout/Navigation/useModules.tsx@@ -51,7 +51,7 @@ export function useModules() {{permission: "sales",name: "Sales",- to: path.to.quotes,+ to: path.to.salesOrders,icon: LuReceipt,},{diff --git a/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx b/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsxindex 7eb003aa8a..37b9f6cc82 100644--- a/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx+++ b/apps/carbon/app/modules/sales/ui/useSalesSubmodules.tsx@@ -6,14 +6,14 @@ const salesRoutes: AuthenticatedRouteGroup[] = [{name: "Manage",routes: [- {- name: "Quotations",- to: path.to.quotes,- },{name: "Sales Orders",to: path.to.salesOrders,},+ {+ name: "Quotations",+ to: path.to.quotes,+ },{name: "Customers",to: path.to.customers,diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.tsindex 71c64e6378..4dbead6bdf 100644--- a/apps/carbon/app/modules/users/users.server.ts+++ b/apps/carbon/app/modules/users/users.server.ts@@ -806,11 +806,10 @@ async function setUserPermissions(permissions: Record<string, string[]>) {const user = await client- .from("user")+ .from("userPermission").select("permissions").eq("id", userId)- .single();- if (user.error) return user;+ .maybeSingle();const currentPermissions = (user.data?.permissions ?? {}) as Record<string,@@ -827,9 +826,8 @@ async function setUserPermissions(});return client- .from("user")- .update({ permissions: newPermissions })- .eq("id", userId);+ .from("userPermission")+ .upsert({ id: userId, permissions: newPermissions });}export async function updateEmployee(@@ -985,7 +983,7 @@ export async function updatePermissions(}const permissionsUpdate = await getSupabaseServiceRole()- .from("user")+ .from("userPermission").update({ permissions: updatedPermissions }).eq("id", id);if (permissionsUpdate.error)diff --git a/apps/carbon/app/routes/x+/sales+/_layout.tsx b/apps/carbon/app/routes/x+/sales+/_layout.tsxindex a9e8cf3996..eb68783067 100644--- a/apps/carbon/app/routes/x+/sales+/_layout.tsx+++ b/apps/carbon/app/routes/x+/sales+/_layout.tsx@@ -12,7 +12,7 @@ export const meta: MetaFunction = () => {export const handle: Handle = {breadcrumb: "Sales",- to: path.to.quotes,+ to: path.to.salesOrders,module: "sales",};diff --git a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsxindex ddaf1d5709..12d4029f90 100644--- a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx+++ b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx@@ -3,6 +3,7 @@ import { validationError, validator } from "@carbon/remix-validated-form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";+import { getSupabaseServiceRole } from "~/lib/supabase";import type { CompanyPermission } from "~/modules/users";import {EmployeePermissionsForm,@@ -23,7 +24,7 @@ import { path } from "~/utils/path";import { error } from "~/utils/result";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {+ const { companyId } = await requirePermissions(request, {view: "users",role: "employee",});@@ -31,6 +32,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { employeeId } = params;if (!employeeId) throw notFound("employeeId not found");+ const client = getSupabaseServiceRole();const [rawClaims, employee, employeeTypes] = await Promise.all([getClaims(client, employeeId),getEmployee(client, employeeId, companyId),diff --git a/apps/docs/components/Home/components/features.tsx b/apps/docs/components/Home/components/features.tsxindex 828129f449..84183b3088 100644--- a/apps/docs/components/Home/components/features.tsx+++ b/apps/docs/components/Home/components/features.tsx@@ -20,7 +20,7 @@ const features = ["Built on best open-source technologies for incredible performance and security.",},{- name: "Open Source",+ name: "Open Core",icon: HiCode,description:"Unlike other open-source ERPs, you can use Carbon to build your own proprietary systems.",diff --git a/apps/docs/pages/core-concepts/permissions.mdx b/apps/docs/pages/core-concepts/permissions.mdxindex 3b101f54fd..9759c3dcfc 100644--- a/apps/docs/pages/core-concepts/permissions.mdx+++ b/apps/docs/pages/core-concepts/permissions.mdx@@ -8,12 +8,13 @@ description: Conventions for permissions in Carbon ERPThere are two types of permissions in the system:1. **Role permissions** - These are permissions that are specific to a role. These are in the `auth.users` and included in the JWT.-2. **Module permissions** - These are permissions that are specific to a module. The are store in the `public.user` table.+2. **Module permissions** - These are permissions that are specific to a module. They are stored in the `public.userPermission` table.For example, customers may be able to view the sales module, but a customer role limits the data to only their own sales, where an employee with the same permission can view all sales.Each user has a **role**, which may be one of the following:+- `owner`- `employee`- `customer`- `supplier`diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.tsindex 3c47b22cca..3542333a7b 100644--- a/packages/database/src/seed.ts+++ b/packages/database/src/seed.ts@@ -52,11 +52,18 @@ async function seed() {email: admin.email,firstName: admin.firstName,lastName: admin.lastName,- permissions,},]);if (upsertAdmin.error) throw upsertAdmin.error;+ const upsertPermissions = await supabaseAdmin.from("userPermission").upsert([+ {+ id: id,+ permissions,+ },+ ]);+ if (upsertPermissions.error) throw upsertPermissions.error;+// give the admin user all the claimsawait supabaseAdmin.auth.admin.updateUserById(id, {app_metadata: claims,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 0cd525892e..cde1764269 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -16059,7 +16059,6 @@ export type Database = {fullName: string | nullid: stringlastName: string- permissions: Json | nullupdatedAt: string | null}Insert: {@@ -16072,7 +16071,6 @@ export type Database = {fullName?: string | nullid: stringlastName: string- permissions?: Json | nullupdatedAt?: string | null}Update: {@@ -16085,7 +16083,6 @@ export type Database = {fullName?: string | nullid?: stringlastName?: string- permissions?: Json | nullupdatedAt?: string | null}Relationships: []@@ -16495,6 +16492,50 @@ export type Database = {},]}+ userPermission: {+ Row: {+ id: string+ permissions: Json | null+ }+ Insert: {+ id: string+ permissions?: Json | null+ }+ Update: {+ id?: string+ permissions?: Json | null+ }+ Relationships: [+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }userToCompany: {Row: {companyId: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 0cd525892e..cde1764269 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -16059,7 +16059,6 @@ export type Database = {fullName: string | nullid: stringlastName: string- permissions: Json | nullupdatedAt: string | null}Insert: {@@ -16072,7 +16071,6 @@ export type Database = {fullName?: string | nullid: stringlastName: string- permissions?: Json | nullupdatedAt?: string | null}Update: {@@ -16085,7 +16083,6 @@ export type Database = {fullName?: string | nullid?: stringlastName?: string- permissions?: Json | nullupdatedAt?: string | null}Relationships: []@@ -16495,6 +16492,50 @@ export type Database = {},]}+ userPermission: {+ Row: {+ id: string+ permissions: Json | null+ }+ Insert: {+ id: string+ permissions?: Json | null+ }+ Update: {+ id?: string+ permissions?: Json | null+ }+ Relationships: [+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "userPermission_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }userToCompany: {Row: {companyId: stringdiff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex 7b644530bb..2833ba3c6b 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -224,7 +224,7 @@ serve(async (req: Request) => {.execute();const user = await supabaseClient- .from("user")+ .from("userPermission").select("permissions").eq("id", userId).single();@@ -263,7 +263,7 @@ serve(async (req: Request) => {});const { error } = await supabaseClient- .from("user")+ .from("userPermission").update({ permissions: newPermissions }).eq("id", userId);if (error) throw new Error(error.message);diff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sqlindex 73f1e13895..d19ee200ec 100644--- a/packages/database/supabase/migrations/20230123004206_claims.sql+++ b/packages/database/supabase/migrations/20230123004206_claims.sql@@ -34,7 +34,7 @@ CREATE OR REPLACE FUNCTION get_my_permission(claim text) RETURNS "jsonb"AS $$DECLARE permissions jsonb;BEGIN- select coalesce(permissions->claim, null) from public.user into permissions where id = auth.uid()::text;+ select coalesce(permissions->claim, null) from public."userPermission" into permissions where id = auth.uid()::text;return permissions;END;@@ -66,7 +66,7 @@ CREATE OR REPLACE FUNCTION get_permission_companies(claim text) RETURNS text[]DECLARE retval text[];BEGIN-- TODO: (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->- select jsonb_to_text_array(coalesce(permissions->claim, '[]')) from public.user into retval where id = auth.uid()::text;+ select jsonb_to_text_array(coalesce(permissions->claim, '[]')) from public."userPermission" into retval where id = auth.uid()::text;return retval;END;@@ -91,7 +91,7 @@ CREATE OR REPLACE FUNCTION has_company_permission(claim text, company text) RETUpermission_value text[];BEGIN-- TODO: (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->claim- SELECT jsonb_to_text_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public.user WHERE id = auth.uid()::text;+ SELECT jsonb_to_text_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public."userPermission" WHERE id = auth.uid()::text;IF permission_value IS NULL THENreturn false;ELSIF '0' = ANY(permission_value::text[]) THEN@@ -111,7 +111,7 @@ CREATE OR REPLACE FUNCTION has_any_company_permission(claim text) RETURNS "bool"permission_value text[];BEGIN- SELECT jsonb_to_text_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public.user WHERE id = auth.uid()::text;+ SELECT jsonb_to_text_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public."userPermission" WHERE id = auth.uid()::text;IF permission_value IS NULL THENreturn false;ELSIF array_length(permission_value, 1) > 0 THEN@@ -140,7 +140,7 @@ CREATE OR REPLACE FUNCTION get_claims(uid text) RETURNS "jsonb"DECLARE perms jsonb;BEGINselect raw_app_meta_data from auth.users into claims where id = uid::uuid;- select permissions from public.user into perms where id = uid::text;+ select permissions from "userPermission" into perms where id = uid::text;return (claims || perms)::jsonb;END;diff --git a/packages/database/supabase/migrations/20230123004316_users.sql b/packages/database/supabase/migrations/20230123004316_users.sqlindex 81cbcdf614..6edd2fba1e 100644--- a/packages/database/supabase/migrations/20230123004316_users.sql+++ b/packages/database/supabase/migrations/20230123004316_users.sql@@ -7,7 +7,6 @@ CREATE TABLE "user" ("about" TEXT NOT NULL DEFAULT '',"avatarUrl" TEXT,"active" BOOLEAN DEFAULT TRUE,- "permissions" JSONB DEFAULT '{}',"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedAt" TIMESTAMP WITH TIME ZONE,@@ -16,12 +15,3 @@ CREATE TABLE "user" (CREATE UNIQUE INDEX "index_user_email_key" ON "user"("email");CREATE INDEX "index_user_fullName" ON "user"("fullName");--ALTER TABLE "user" ENABLE ROW LEVEL SECURITY;--CREATE POLICY "Claims admin can view/modify users" ON "user" FOR ALL USING (has_any_company_permission('users_update'));-CREATE POLICY "Users can modify themselves" ON "user" FOR UPDATE WITH CHECK (auth.uid() = id::uuid);-CREATE POLICY "Anyone that's authenticated can view users" ON "user" FOR SELECT USING (auth.role() = 'authenticated');--INSERT INTO "user" ("id", "email", "firstName", "lastName")-VALUES ('system', '[email protected]', 'System', 'Operation');diff --git a/packages/database/supabase/migrations/20230123004317_companies.sql b/packages/database/supabase/migrations/20230123004317_companies.sqlindex 8bf0c5a7e1..628aea5104 100644--- a/packages/database/supabase/migrations/20230123004317_companies.sql+++ b/packages/database/supabase/migrations/20230123004317_companies.sql@@ -80,3 +80,42 @@ CREATE POLICY "Employees with users_delete can delete userToCompany" ON "userToCUSING (has_company_permission('users_delete', "companyId"));++++ALTER TABLE "user" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Claims admin can view/modify users" ON "user" FOR ALL USING (has_any_company_permission('users_update'));+CREATE POLICY "Users can modify themselves" ON "user" FOR UPDATE WITH CHECK (auth.uid() = id::uuid);+CREATE POLICY "Users can view other users from their same company" ON "user" FOR SELECT USING (+ "id" IN (+ SELECT "userId" FROM "userToCompany" WHERE "companyId" IN (+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = auth.uid()::text+ )+ )+);++INSERT INTO "user" ("id", "email", "firstName", "lastName")+VALUES ('system', '[email protected]', 'System', 'Operation');+++CREATE TABLE "userPermission" (+ "id" TEXT NOT NULL,+ "permissions" JSONB DEFAULT '{}',++ CONSTRAINT "userPermission_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "userPermission_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE+);++ALTER TABLE "userPermission" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users can view their own permissions" ON "userPermission" FOR SELECT USING (TRUE);+CREATE POLICY "Users with users_update can view permissions of other users in their company" ON "userPermission" FOR SELECT USING (+ "id" IN (+ SELECT "userId" FROM "userToCompany" WHERE "companyId" IN (+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = auth.uid()::text+ )+ )+);++