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 to user table and out of jwt
Brad Barbin759a569a0475
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.tsindex d2d38ec123..3eaf3c609d 100644--- a/apps/carbon/app/modules/users/users.server.ts+++ b/apps/carbon/app/modules/users/users.server.ts@@ -78,17 +78,6 @@ export async function createCustomerAccount(const userId = invitation.data.user.id;- const claims = makeCustomerClaims(companyId);- const claimsUpdate = await setUserClaims(userId, {- role: "customer",- ...claims,- });-- if (claimsUpdate.error) {- await deleteAuthAccount(userId);- return error(claimsUpdate.error, "Failed to add user");- }-const insertUser = await createUser(client, {id: userId,email,@@ -103,16 +92,28 @@ export async function createCustomerAccount(if (!insertUser.data)return error(insertUser, "No data returned from create user");- const [updateContact, createCustomerAccount, userToCompany] =- await Promise.all([- client.from("customerContact").update({ userId }).eq("id", id),- insertCustomerAccount(client, {- id: userId,- customerId,- companyId,- }),- addUserToCompany(client, { userId, companyId }),- ]);+ const permissions = makeCustomerPermissions(companyId);+ const supabaseAdmin = getSupabaseServiceRole();++ const [+ updateContact,+ createCustomerAccount,+ userToCompany,+ claimsUpdate,+ permissionsUpdate,+ ] = await Promise.all([+ client.from("customerContact").update({ userId }).eq("id", id),+ insertCustomerAccount(client, {+ id: userId,+ customerId,+ companyId,+ }),+ addUserToCompany(client, { userId, companyId }),+ setUserClaims(supabaseAdmin, userId, {+ role: "customer",+ }),+ setUserPermissions(supabaseAdmin, userId, permissions),+ ]);if (updateContact.error) {await deleteAuthAccount(userId);@@ -132,6 +133,16 @@ export async function createCustomerAccount(return error(userToCompany.error, "Failed to add user to company");}+ if (claimsUpdate.error) {+ await deleteAuthAccount(userId);+ return error(claimsUpdate.error, "Failed to add user");+ }++ if (permissionsUpdate.error) {+ await deleteAuthAccount(userId);+ return error(permissionsUpdate.error, "Failed to add user permissions");+ }+return success("Customer account created");}}@@ -180,18 +191,6 @@ export async function createEmployeeAccount(const userId = invitation.data.user.id;- const claims = makeClaimsFromEmployeeType(employeeTypePermissions);- const claimsUpdate = await setUserClaims(userId, {- role: "employee",- ...claims,- });- if (claimsUpdate.error) {- await deleteAuthAccount(userId);- if (claimsUpdate.error) {- return error(claimsUpdate.error, "Failed to udpate user claims");- }- }-const insertUser = await createUser(client, {id: userId,email,@@ -206,14 +205,24 @@ export async function createEmployeeAccount(if (!insertUser.data)return error(insertUser, "No data returned from create user");- const [createEmployee, userToCompany] = await Promise.all([- insertEmployee(client, {- id: insertUser.data[0].id,- employeeTypeId: employeeType,- companyId,- }),- addUserToCompany(client, { userId, companyId }),- ]);+ const supabaseAdmin = getSupabaseServiceRole();+ const permissions = makePermissionsFromEmployeeType(+ employeeTypePermissions+ );++ const [createEmployee, userToCompany, claimsUpdate, permissionsUpdate] =+ await Promise.all([+ insertEmployee(client, {+ id: insertUser.data[0].id,+ employeeTypeId: employeeType,+ companyId,+ }),+ addUserToCompany(client, { userId, companyId }),+ setUserClaims(supabaseAdmin, userId, {+ role: "employee",+ }),+ setUserPermissions(supabaseAdmin, userId, permissions),+ ]);if (createEmployee.error) {await deleteAuthAccount(userId);@@ -225,6 +234,21 @@ export async function createEmployeeAccount(return error(userToCompany.error, "Failed to add user to company");}+ if (claimsUpdate.error) {+ await deleteAuthAccount(userId);+ if (claimsUpdate.error) {+ return error(claimsUpdate.error, "Failed to udpate user claims");+ }+ }++ if (permissionsUpdate.error) {+ await deleteAuthAccount(userId);+ return error(+ permissionsUpdate.error,+ "Failed to update user permissions"+ );+ }+return success("Employee account created");}}@@ -271,16 +295,6 @@ export async function createSupplierAccount(const userId = invitation.data.user.id;- const claims = makeSupplierClaims(companyId);- const claimsUpdate = await setUserClaims(userId, {- role: "supplier",- ...claims,- });- if (claimsUpdate.error) {- await deleteAuthAccount(userId);- return error(claimsUpdate.error, "Failed to create user");- }-const insertUser = await createUser(client, {id: userId,email,@@ -295,16 +309,28 @@ export async function createSupplierAccount(if (!insertUser.data)return error(insertUser, "No data returned from create user");- const [updateContact, createSupplierAccount, userToCompany] =- await Promise.all([- client.from("supplierContact").update({ userId }).eq("id", id),- insertSupplierAccount(client, {- id: insertUser.data[0].id,- supplierId,- companyId,- }),- addUserToCompany(client, { userId, companyId }),- ]);+ const supabaseAdmin = getSupabaseServiceRole();+ const permissions = makeSupplierPermissions(companyId);++ const [+ updateContact,+ createSupplierAccount,+ userToCompany,+ claimsUpdate,+ permissionsUpdate,+ ] = await Promise.all([+ client.from("supplierContact").update({ userId }).eq("id", id),+ insertSupplierAccount(client, {+ id: insertUser.data[0].id,+ supplierId,+ companyId,+ }),+ addUserToCompany(client, { userId, companyId }),+ setUserClaims(supabaseAdmin, userId, {+ role: "supplier",+ }),+ setUserPermissions(supabaseAdmin, userId, permissions),+ ]);if (updateContact.error) {await deleteAuthAccount(userId);@@ -324,6 +350,19 @@ export async function createSupplierAccount(return error(userToCompany.error, "Failed to add user to company");}+ if (claimsUpdate.error) {+ await deleteAuthAccount(userId);+ return error(claimsUpdate.error, "Failed to create user");+ }++ if (permissionsUpdate.error) {+ await deleteAuthAccount(userId);+ return error(+ permissionsUpdate.error,+ "Failed to create user permissions"+ );+ }+return success("Supplier account created");}}@@ -504,7 +543,7 @@ async function insertUser(return client.from("user").insert([user]).select("*");}-function makeClaimsFromEmployeeType({+function makePermissionsFromEmployeeType({data,}: {data: {@@ -515,7 +554,7 @@ function makeClaimsFromEmployeeType({module: string;}[];}) {- const claims: Record<string, number[]> = {};+ const permissions: Record<string, number[]> = {};data.forEach((permission) => {if (!permission.module) {@@ -526,13 +565,13 @@ function makeClaimsFromEmployeeType({const module = permission.module.toLowerCase();- claims[`${module}_view`] = permission.view;- claims[`${module}_create`] = permission.create;- claims[`${module}_update`] = permission.update;- claims[`${module}_delete`] = permission.delete;+ permissions[`${module}_view`] = permission.view;+ permissions[`${module}_create`] = permission.create;+ permissions[`${module}_update`] = permission.update;+ permissions[`${module}_delete`] = permission.delete;});- return claims;+ return permissions;}function isClaimPermission(key: string, value: unknown) {@@ -544,16 +583,16 @@ function isClaimPermission(key: string, value: unknown) {);}-function makeCustomerClaims(companyId: number) {+function makeCustomerPermissions(companyId: number) {// TODO: this should be more dynamic- const claims: Record<string, number[]> = {+ const permissions: Record<string, number[]> = {documents_view: [companyId],jobs_view: [companyId],sales_view: [companyId],parts_view: [companyId],};- return claims;+ return permissions;}export function makeEmptyPermissionsFromModules(data: Module[]) {@@ -710,15 +749,15 @@ export function makeCompanyPermissionsFromEmployeeType(return result;}-function makeSupplierClaims(companyId: number) {+function makeSupplierPermissions(companyId: number) {// TODO: this should be more dynamic- const claims: Record<string, number[]> = {+ const permissions: Record<string, number[]> = {documents_view: [companyId],purchasing_view: [companyId],parts_view: [companyId],};- return claims;+ return permissions;}export async function resendInvite(@@ -745,33 +784,51 @@ export async function resetPassword(userId: string, password: string) {}async function setUserClaims(+ client: SupabaseClient<Database>,userId: string,- claims: Record<string, number[] | string>+ claims: Record<string, string>) {- const client = getSupabaseServiceRole();const user = await client.auth.admin.getUserById(userId);- if (user.error) throw new Error(user.error.message);+ if (user.error) return user;const currentClaims = user.data?.user.app_metadata ?? {};- const newClaims = { ...currentClaims };+ const newClaims = { ...currentClaims, ...claims };- Object.entries(claims).forEach(([key, value]) => {- if (key === "role") {- newClaims["role"] = value;- }+ return client.auth.admin.updateUserById(userId, {+ app_metadata: newClaims,+ });+}- if (isClaimPermission(key, value)) {- if (key in newClaims) {- newClaims[key] = [...newClaims[key], ...value];- } else {- newClaims[key] = value;- }+async function setUserPermissions(+ client: SupabaseClient<Database>,+ userId: string,+ permissions: Record<string, number[]>+) {+ const user = await client+ .from("user")+ .select("permissions")+ .eq("id", userId)+ .single();+ if (user.error) return user;++ const currentPermissions = (user.data?.permissions ?? {}) as Record<+ string,+ number[]+ >;+ const newPermissions = { ...currentPermissions };++ Object.entries(permissions).forEach(([key, value]) => {+ if (key in newPermissions) {+ newPermissions[key] = [...newPermissions[key], ...value];+ } else {+ newPermissions[key] = value;}});- return client.auth.admin.updateUserById(userId, {- app_metadata: newClaims,- });+ return client+ .from("user")+ .update({ permissions: newPermissions })+ .eq("id", userId);}export async function updateEmployee(@@ -817,7 +874,7 @@ export async function updatePermissions(if (claims.error) return error(claims.error, "Failed to get claims");- const updatedClaims = (+ const updatedPermissions = (typeof claims.data !== "object" ||Array.isArray(claims.data) ||claims.data === null@@ -827,17 +884,17 @@ export async function updatePermissions(// add any missing claims to the current claimsObject.keys(permissions).forEach((name) => {- if (!(`${name}_view` in updatedClaims)) {- updatedClaims[`${name}_view`] = [];+ if (!(`${name}_view` in updatedPermissions)) {+ updatedPermissions[`${name}_view`] = [];}- if (!(`${name}_create` in updatedClaims)) {- updatedClaims[`${name}_create`] = [];+ if (!(`${name}_create` in updatedPermissions)) {+ updatedPermissions[`${name}_create`] = [];}- if (!(`${name}_update` in updatedClaims)) {- updatedClaims[`${name}_update`] = [];+ if (!(`${name}_update` in updatedPermissions)) {+ updatedPermissions[`${name}_update`] = [];}- if (!(`${name}_delete` in updatedClaims)) {- updatedClaims[`${name}_delete`] = [];+ if (!(`${name}_delete` in updatedPermissions)) {+ updatedPermissions[`${name}_delete`] = [];}});@@ -846,92 +903,91 @@ export async function updatePermissions(const module = name.toLowerCase();if (permission.view &&- !updatedClaims[`${module}_view`]?.includes(companyId)+ !updatedPermissions[`${module}_view`]?.includes(companyId)) {- updatedClaims[`${module}_view`].push(companyId);+ updatedPermissions[`${module}_view`].push(companyId);}if (permission.create &&- !updatedClaims[`${module}_create`]?.includes(companyId)+ !updatedPermissions[`${module}_create`]?.includes(companyId)) {- updatedClaims[`${module}_create`].push(companyId);+ updatedPermissions[`${module}_create`].push(companyId);}if (permission.update &&- !updatedClaims[`${module}_update`]?.includes(companyId)+ !updatedPermissions[`${module}_update`]?.includes(companyId)) {- updatedClaims[`${module}_update`].push(companyId);+ updatedPermissions[`${module}_update`].push(companyId);}if (permission.delete &&- !updatedClaims[`${module}_delete`]?.includes(companyId)+ !updatedPermissions[`${module}_delete`]?.includes(companyId)) {- updatedClaims[`${module}_delete`].push(companyId);+ updatedPermissions[`${module}_delete`].push(companyId);}});} else {Object.entries(permissions).forEach(([name, permission]) => {const module = name.toLowerCase();if (permission.view) {- if (!updatedClaims[`${module}_view`]?.includes(companyId)) {- updatedClaims[`${module}_view`] = [- ...updatedClaims[`${module}_view`],+ if (!updatedPermissions[`${module}_view`]?.includes(companyId)) {+ updatedPermissions[`${module}_view`] = [+ ...updatedPermissions[`${module}_view`],companyId,];}} else {- updatedClaims[`${module}_view`] = (- updatedClaims[`${module}_view`] as number[]+ updatedPermissions[`${module}_view`] = (+ updatedPermissions[`${module}_view`] as number[]).filter((c: number) => c !== companyId);}if (permission.create) {- if (!updatedClaims[`${module}_create`]?.includes(companyId)) {- updatedClaims[`${module}_create`] = [- ...updatedClaims[`${module}_create`],+ if (!updatedPermissions[`${module}_create`]?.includes(companyId)) {+ updatedPermissions[`${module}_create`] = [+ ...updatedPermissions[`${module}_create`],companyId,];}} else {- updatedClaims[`${module}_create`] = (- updatedClaims[`${module}_create`] as number[]+ updatedPermissions[`${module}_create`] = (+ updatedPermissions[`${module}_create`] as number[]).filter((c: number) => c !== companyId);}if (permission.update) {- if (!updatedClaims[`${module}_update`]?.includes(companyId)) {- updatedClaims[`${module}_update`] = [- ...updatedClaims[`${module}_update`],+ if (!updatedPermissions[`${module}_update`]?.includes(companyId)) {+ updatedPermissions[`${module}_update`] = [+ ...updatedPermissions[`${module}_update`],companyId,];}} else {- updatedClaims[`${module}_update`] = (- updatedClaims[`${module}_update`] as number[]+ updatedPermissions[`${module}_update`] = (+ updatedPermissions[`${module}_update`] as number[]).filter((c: number) => c !== companyId);}if (permission.delete) {- if (!updatedClaims[`${module}_delete`]?.includes(companyId)) {- updatedClaims[`${module}_delete`] = [- ...updatedClaims[`${module}_delete`],+ if (!updatedPermissions[`${module}_delete`]?.includes(companyId)) {+ updatedPermissions[`${module}_delete`] = [+ ...updatedPermissions[`${module}_delete`],companyId,];}} else {- updatedClaims[`${module}_delete`] = (- updatedClaims[`${module}_delete`] as number[]+ updatedPermissions[`${module}_delete`] = (+ updatedPermissions[`${module}_delete`] as number[]).filter((c: number) => c !== companyId);}});}- const claimsUpdate =- await getSupabaseServiceRole().auth.admin.updateUserById(id, {- app_metadata: updatedClaims,- });- if (claimsUpdate.error)- return error(claimsUpdate.error, "Failed to update claims");+ const permissionsUpdate = await getSupabaseServiceRole()+ .from("user")+ .update({ permissions: updatedPermissions });+ if (permissionsUpdate.error)+ return error(permissionsUpdate.error, "Failed to update claims");await redis.del(getPermissionCacheKey(id));diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.tsindex 716e8a8080..3c47b22cca 100644--- a/packages/database/src/seed.ts+++ b/packages/database/src/seed.ts@@ -1,3 +1,4 @@+import type { User } from "@supabase/supabase-js";import { createClient } from "@supabase/supabase-js";import * as dotenv from "dotenv";import { admin, claims, permissions } from "./seed/index";@@ -20,7 +21,8 @@ const getUserId = async (): Promise<string> => {const existingUserId = await supabaseAdmin.auth.admin.listUsers().then(- ({ data }) => data.users.find((user) => user.email === admin.email)?.id+ ({ data }) =>+ data.users.find((user: User) => user?.email! === admin.email)?.id);if (existingUserId) return existingUserId;diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex 9de3ea7903..ec25d9035c 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -232,41 +232,49 @@ serve(async (req: Request) => {.values(customFields.map((cf) => ({ ...cf, companyId }))).execute();- const user = await supabaseClient.auth.admin.getUserById(userId);+ const user = await supabaseClient+ .from("user")+ .select("permissions")+ .eq("id", userId)+ .single();if (user.error) throw new Error(user.error.message);- const currentClaims = user.data?.user.app_metadata ?? {};- const newClaims = { ...currentClaims };+ const currentPermissions = (user.data?.permissions ?? {}) as Record<+ string,+ number[]+ >;+ const newPermissions = { ...currentPermissions };modules.forEach(({ name }) => {const module = name?.toLowerCase();- if (`${module}_view` in newClaims) {- newClaims[`${module}_view`].push(companyId);+ if (`${module}_view` in newPermissions) {+ newPermissions[`${module}_view`].push(companyId);} else {- newClaims[`${module}_view`] = [companyId];+ newPermissions[`${module}_view`] = [companyId];}- if (`${module}_create` in newClaims) {- newClaims[`${module}_create`].push(companyId);+ if (`${module}_create` in newPermissions) {+ newPermissions[`${module}_create`].push(companyId);} else {- newClaims[`${module}_create`] = [companyId];+ newPermissions[`${module}_create`] = [companyId];}- if (`${module}_update` in newClaims) {- newClaims[`${module}_update`].push(companyId);+ if (`${module}_update` in newPermissions) {+ newPermissions[`${module}_update`].push(companyId);} else {- newClaims[`${module}_update`] = [companyId];+ newPermissions[`${module}_update`] = [companyId];}- if (`${module}_delete` in newClaims) {- newClaims[`${module}_delete`].push(companyId);+ if (`${module}_delete` in newPermissions) {+ newPermissions[`${module}_delete`].push(companyId);} else {- newClaims[`${module}_delete`] = [companyId];+ newPermissions[`${module}_delete`] = [companyId];}});- const { error } = await supabaseClient.auth.admin.updateUserById(userId, {- app_metadata: newClaims,- });+ const { error } = await supabaseClient+ .from("user")+ .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 17ec966e99..bd652eb73d 100644--- a/packages/database/supabase/migrations/20230123004206_claims.sql+++ b/packages/database/supabase/migrations/20230123004206_claims.sql@@ -15,11 +15,7 @@ CREATE OR REPLACE FUNCTION is_claims_admin() RETURNS "bool"return false; -- jwt expiredEND IF;- IF EXISTS (- SELECT 1- FROM get_permission_companies_as_text('users_update') AS company- WHERE company::int = 0- ) THEN+ IF has_company_permission('update_users', 0) THENreturn true; -- user has user_update set to trueELSEreturn false; -- user does NOT have user_update set to truediff --git a/packages/database/supabase/migrations/20230123004317_companies.sql b/packages/database/supabase/migrations/20230123004317_companies.sqlindex 4ed08fb959..bcf4706400 100644--- a/packages/database/supabase/migrations/20230123004317_companies.sql+++ b/packages/database/supabase/migrations/20230123004317_companies.sql@@ -48,4 +48,30 @@ CREATE POLICY "Employees with settings_delete can delete company" ON "company"CREATE TABLE "userToCompany" ("userId" TEXT NOT NULL REFERENCES "user" ("id") ON UPDATE CASCADE ON DELETE CASCADE,"companyId" INTEGER NOT NULL REFERENCES "company" ("id") ON UPDATE CASCADE ON DELETE CASCADE-);\ No newline at end of file+);++ALTER TABLE "userToCompany" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view userToCompany" ON "userToCompany"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );++CREATE POLICY "Employees with users_create can create userToCompany" ON "userToCompany"+ FOR INSERT+ WITH CHECK (+ has_company_permission('users_create', "companyId")+ );++CREATE POLICY "Employees with users_update can update userToCompany" ON "userToCompany"+ FOR UPDATE+ USING (+ has_company_permission('users_update', "companyId")+ );++CREATE POLICY "Employees with users_delete can delete userToCompany" ON "userToCompany"+ FOR DELETE+ USING (+ has_company_permission('users_delete', "companyId")+ );diff --git a/packages/database/supabase/migrations/20230123004436_employee.sql b/packages/database/supabase/migrations/20230123004436_employee.sqlindex 95e58edd6c..bfd18b038d 100644--- a/packages/database/supabase/migrations/20230123004436_employee.sql+++ b/packages/database/supabase/migrations/20230123004436_employee.sql@@ -1,6 +1,6 @@CREATE TABLE "employee" ("id" TEXT NOT NULL,- "companyId" INTEGER,+ "companyId" INTEGER NULL,"employeeTypeId" TEXT NOT NULL,CONSTRAINT "employee_pkey" PRIMARY KEY ("id", "companyId"),CONSTRAINT "employee_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,@@ -13,7 +13,6 @@ ALTER TABLE "employee" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees can view employees from their company" ON "employee" FOR SELECT USING (- is_claims_admin() OR"companyId" IN (SELECT "companyId" FROM "userToCompany" WHERE "userId" = auth.uid()::text)@@ -31,7 +30,7 @@ CREATE POLICY "Employees with users_update can delete employees" ON "employee" Fhas_company_permission('users_delete', "companyId"));-CREATE OR REPLACE VIEW "companies" WITH(SECURITY_INVOKER=true) AS+CREATE OR REPLACE VIEW "companies" ASSELECT DISTINCTc.*,uc.*,@@ -42,4 +41,4 @@ CREATE OR REPLACE VIEW "companies" WITH(SECURITY_INVOKER=true) ASINNER JOIN "employee" eON e.id = uc."userId" AND e."companyId" = uc."companyId"INNER JOIN "employeeType" et- ON et.id = e."employeeTypeId"\ No newline at end of file+ ON et.id = e."employeeTypeId";\ No newline at end of file