Skip to content

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.

refactor: company form to support mult-tenant

Brad Barbind862d20e6847
diff --git a/apps/carbon/app/config/env.ts b/apps/carbon/app/config/env.ts
index 13918301ef..0ef2c548fd 100644
--- a/apps/carbon/app/config/env.ts
+++ b/apps/carbon/app/config/env.ts
@@ -54,7 +54,8 @@ function getEnv(
*/
export const SUPABASE_SERVICE_ROLE = getEnv("SUPABASE_SERVICE_ROLE");
export const SESSION_SECRET = getEnv("SESSION_SECRET");
-export const SESSION_KEY = "authenticated";
+export const SESSION_KEY = "auth";
+export const SESSION_COMPANY_KEY = "company";
export const SESSION_ERROR_KEY = "error";
export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days;
export const REFRESH_ACCESS_TOKEN_THRESHOLD = 60 * 10; // 10 minutes left before token expires
diff --git a/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx b/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
index 74cb1536a8..89799de9bc 100644
--- a/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
+++ b/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
@@ -29,6 +29,7 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {
});
if (imageUpload.error) {
+ console.error(imageUpload.error);
toast.error("Failed to upload image");
}
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index ab5b198da8..a5429a1cd5 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -8,8 +8,15 @@ import { interpolateSequenceDate } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import type { companyValidator, sequenceValidator } from "./settings.models";
-export async function getCompany(client: SupabaseClient<Database>) {
- const company = await client.from("company").select("*").single();
+export async function getCompany(
+ client: SupabaseClient<Database>,
+ companyId: number
+) {
+ const company = await client
+ .from("company")
+ .select("*")
+ .eq("id", companyId)
+ .single();
if (company.error) {
return company;
}
@@ -195,11 +202,12 @@ export async function rollbackNextSequence(
export async function updateCompany(
client: SupabaseClient<Database>,
+ companyId: number,
company: Partial<z.infer<typeof companyValidator>> & {
updatedBy: string;
}
) {
- return client.from("company").update(sanitize(company)).eq("id", true);
+ return client.from("company").update(sanitize(company)).eq("id", companyId);
}
export async function updateIntegration(
@@ -217,6 +225,7 @@ export async function updateIntegration(
export async function updateLogo(
client: SupabaseClient<Database>,
+ companyId: number,
logo: string | null
) {
return client
@@ -226,7 +235,7 @@ export async function updateLogo(
logo,
})
)
- .eq("id", true);
+ .eq("id", companyId);
}
export async function updateSequence(
diff --git a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
index d50b16ebf7..5aa6229672 100644
--- a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
@@ -24,7 +24,7 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
const imageUpload = await supabase.storage
.from("public")
- .upload(`logo.${fileExtension}`, logo, {
+ .upload(`${company.id}/logo.${fileExtension}`, logo, {
cacheControl: "0",
upsert: true,
});
diff --git a/apps/carbon/app/modules/users/users.service.ts b/apps/carbon/app/modules/users/users.service.ts
index 1ef50c0802..822dbcfa9d 100644
--- a/apps/carbon/app/modules/users/users.service.ts
+++ b/apps/carbon/app/modules/users/users.service.ts
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
+import logger from "~/lib/logger";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import type { Permission } from "./types";
@@ -18,6 +19,23 @@ export async function deleteGroup(
return client.from("group").delete().eq("id", groupId);
}
+export async function getCompaniesForUser(
+ client: SupabaseClient<Database>,
+ userId: string
+) {
+ const { data, error } = await client
+ .from("userToCompany")
+ .select("companyId")
+ .eq("userId", userId);
+
+ if (error) {
+ logger.error(error, `Failed to get companies for user ${userId}`);
+ return [];
+ }
+
+ return data?.map((row) => row.companyId) ?? [];
+}
+
export async function getCustomers(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
diff --git a/apps/carbon/app/routes/_public+/callback.tsx b/apps/carbon/app/routes/_public+/callback.tsx
index 666802de80..332a8c7e0c 100644
--- a/apps/carbon/app/routes/_public+/callback.tsx
+++ b/apps/carbon/app/routes/_public+/callback.tsx
@@ -50,7 +50,7 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
const user = await getUserByEmail(authSession.email);
if (user?.data) {
- throw redirect(path.to.resetPassord, {
+ throw redirect(path.to.resetPassword, {
headers: {
"Set-Cookie": await commitAuthSession(request, {
authSession,
diff --git a/apps/carbon/app/routes/_public+/reset-password.tsx b/apps/carbon/app/routes/_public+/reset-password.tsx
index 7ea088836e..30213cc8e7 100644
--- a/apps/carbon/app/routes/_public+/reset-password.tsx
+++ b/apps/carbon/app/routes/_public+/reset-password.tsx
@@ -70,7 +70,7 @@ export default function ResetPasswordRoute() {
<div className="rounded-lg bg-background shadow-lg p-8 w-[380px]">
<ValidatedForm
method="post"
- action={path.to.resetPassord}
+ action={path.to.resetPassword}
validator={resetPasswordValidator}
>
<VStack spacing={4}>
diff --git a/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx b/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
index 193e65427a..f6bd7823a7 100644
--- a/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
@@ -11,7 +11,7 @@ import { getCompany } from "~/modules/settings";
import { requirePermissions } from "~/services/auth/auth.server";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "purchasing",
});
@@ -20,7 +20,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const [company, purchaseOrder, purchaseOrderLines, purchaseOrderLocations] =
await Promise.all([
- getCompany(client),
+ getCompany(client, companyId),
getPurchaseOrder(client, orderId),
getPurchaseOrderLines(client, orderId),
getPurchaseOrderLocations(client, orderId),
diff --git a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
index 4a5548b3ea..ed36b021fd 100644
--- a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
@@ -11,7 +11,7 @@ import { getCompany } from "~/modules/settings";
import { requirePermissions } from "~/services/auth/auth.server";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "sales",
});
@@ -19,7 +19,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!id) throw new Error("Could not find id");
const [company, quote, quoteLines, quoteLocations] = await Promise.all([
- getCompany(client),
+ getCompany(client, companyId),
getQuote(client, id),
getQuoteLines(client, id),
getQuoteCustomerDetails(client, id),
diff --git a/apps/carbon/app/routes/onboarding+/_layout.tsx b/apps/carbon/app/routes/onboarding+/_layout.tsx
index f35a306d90..cf0a2cdfd8 100644
--- a/apps/carbon/app/routes/onboarding+/_layout.tsx
+++ b/apps/carbon/app/routes/onboarding+/_layout.tsx
@@ -11,12 +11,12 @@ import type { ShouldRevalidateFunction } from "@remix-run/react";
export const shouldRevalidate: ShouldRevalidateFunction = () => true;
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
create: "settings",
});
const [company, locations] = await Promise.all([
- getCompany(client),
+ getCompany(client, companyId),
getLocationsList(client),
]);
// we don't need to do onboarding if we have a company name or locations
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
index 99541452c6..d6c79e0cf9 100644
--- a/apps/carbon/app/routes/onboarding+/company.tsx
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -36,11 +36,11 @@ import { requirePermissions } from "~/services/auth/auth.server";
import { assertIsPost } from "~/utils/http";
export async function loader({ request }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
update: "settings",
});
- const company = await getCompany(client);
+ const company = await getCompany(client, companyId);
if (company.error || !company.data) {
return json({
company: null,
@@ -71,7 +71,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { next, ...data } = validation.data;
const [company, locations] = await Promise.all([
- getCompany(client),
+ getCompany(client, 1),
getLocationsList(client),
]);
@@ -79,7 +79,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (company.data && location) {
const [companyUpdate, locationUpdate] = await Promise.all([
- updateCompany(supabaseClient, { ...data, updatedBy: userId }),
+ updateCompany(supabaseClient, 1, { ...data, updatedBy: userId }),
upsertLocation(supabaseClient, {
...location,
...data,
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 99f7f7b11e..06d713f178 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -38,7 +38,7 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { accessToken, expiresAt, expiresIn, userId } =
+ const { accessToken, companyId, expiresAt, expiresIn, userId } =
await requireAuthSession(request, { verify: true });
// share a client between requests
@@ -47,7 +47,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
// parallelize the requests
const [company, customFields, integrations, user, claims, groups, defaults] =
await Promise.all([
- getCompany(client),
+ getCompany(client, companyId),
getCustomFieldsSchemas(client, {}),
getIntegrations(client),
getUser(client, userId),
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
index dc786a1d7a..184d14dea4 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
@@ -25,7 +25,7 @@ export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "purchasing",
role: "employee",
});
@@ -138,7 +138,7 @@ export async function action(args: ActionFunctionArgs) {
purchaseOrderLocations,
buyer,
] = await Promise.all([
- getCompany(client),
+ getCompany(client, companyId),
getSupplierContact(client, supplierContact),
getPurchaseOrder(client, orderId),
getPurchaseOrderLines(client, orderId),
diff --git a/apps/carbon/app/routes/x+/quote+/$id.release.tsx b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
index 5732a55d77..d9543799a5 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.release.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
@@ -25,7 +25,7 @@ export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "sales",
role: "employee",
});
@@ -126,7 +126,7 @@ export async function action(args: ActionFunctionArgs) {
const [company, customer, customerContact, quoteLines, user] =
await Promise.all([
- getCompany(client),
+ getCompany(client, companyId),
getCustomer(client, quote.data.customerId!),
getCustomerContact(client, customerContactId),
getQuoteLines(client, id),
diff --git a/apps/carbon/app/routes/x+/settings+/company.tsx b/apps/carbon/app/routes/x+/settings+/company.tsx
index e5b7526709..dc773f6d02 100644
--- a/apps/carbon/app/routes/x+/settings+/company.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.tsx
@@ -32,7 +32,7 @@ export const handle: Handle = {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "settings",
});
const formData = await request.formData();
@@ -44,7 +44,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const update = await updateCompany(client, {
+ const update = await updateCompany(client, companyId, {
...validation.data,
updatedBy: userId,
});
@@ -60,7 +60,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (formData.get("intent") === "logo") {
const logoPath = formData.get("path");
if (logoPath === null || typeof logoPath === "string") {
- const logoUpdate = await updateLogo(client, logoPath);
+ const logoUpdate = await updateLogo(client, companyId, logoPath);
if (logoUpdate.error) {
throw redirect(
path.to.company,
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index 56b4344034..4ac12d9977 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -6,6 +6,7 @@ import type {
} from "@supabase/supabase-js";
import { REFRESH_ACCESS_TOKEN_THRESHOLD, VERCEL_URL } from "~/config/env";
import { getSupabase, getSupabaseServiceRole } from "~/lib/supabase";
+import { getCompaniesForUser } from "~/modules/users";
import { getUserClaims } from "~/modules/users/users.server";
import { flash, requireAuthSession } from "~/services/session.server";
import { path } from "~/utils/path";
@@ -52,7 +53,8 @@ export async function getAuthAccountByAccessToken(accessToken: string) {
}
function makeAuthSession(
- supabaseSession: SupabaseAuthSession | null
+ supabaseSession: SupabaseAuthSession | null,
+ companyId: number
): AuthSession | null {
if (!supabaseSession) return null;
@@ -64,6 +66,7 @@ function makeAuthSession(
return {
accessToken: supabaseSession.access_token,
+ companyId,
refreshToken: supabaseSession.refresh_token,
userId: supabaseSession.user.id,
email: supabaseSession.user.email,
@@ -84,15 +87,18 @@ export async function requirePermissions(
}
): Promise<{
client: SupabaseClient<Database>;
+ companyId: number;
email: string;
userId: string;
}> {
- const { accessToken, email, userId } = await requireAuthSession(request);
+ const { accessToken, companyId, email, userId } = await requireAuthSession(
+ request
+ );
const client = getSupabase(accessToken);
// early exit if no requiredPermissions are required
if (Object.keys(requiredPermissions).length === 0)
- return { client, email, userId };
+ return { client, companyId, email, userId };
const myClaims = await getUserClaims(request);
@@ -132,7 +138,7 @@ export async function requirePermissions(
);
}
- return { client, email, userId };
+ return { client, companyId, email, userId };
}
export async function resetPassword(accessToken: string, password: string) {
@@ -165,29 +171,39 @@ export async function sendMagicLink(email: string) {
}
export async function signInWithEmail(email: string, password: string) {
- const { data, error } =
- await getSupabaseServiceRole().auth.signInWithPassword({
- email,
- password,
- });
+ const client = getSupabaseServiceRole();
+ const { data, error } = await client.auth.signInWithPassword({
+ email,
+ password,
+ });
if (!data.session || error) return null;
+ const companies = await getCompaniesForUser(client, data.user.id);
- return makeAuthSession(data.session);
+ return makeAuthSession(data.session, companies?.[0] ?? -1);
}
export async function refreshAccessToken(
- refreshToken?: string
+ refreshToken?: string,
+ companyId?: number | null
): Promise<AuthSession | null> {
if (!refreshToken) return null;
- const { data, error } = await getSupabaseServiceRole().auth.refreshSession({
+ const client = getSupabaseServiceRole();
+
+ const { data, error } = await client.auth.refreshSession({
refresh_token: refreshToken,
});
if (!data.session || error) return null;
- return makeAuthSession(data.session);
+ let company = companyId;
+ if (!companyId) {
+ const companies = await getCompaniesForUser(client, data.user?.id!);
+ company = companies?.[0] ?? -1;
+ }
+
+ return makeAuthSession(data.session, company!);
}
export async function verifyAuthSession(authSession: AuthSession) {
diff --git a/apps/carbon/app/services/auth/types.ts b/apps/carbon/app/services/auth/types.ts
index 6af12e8e04..8490fc4f79 100644
--- a/apps/carbon/app/services/auth/types.ts
+++ b/apps/carbon/app/services/auth/types.ts
@@ -2,6 +2,7 @@ export interface AuthSession {
accessToken: string;
refreshToken: string;
userId: string;
+ companyId: number;
email: string;
expiresIn: number;
expiresAt: number;
diff --git a/apps/carbon/app/services/session.server.ts b/apps/carbon/app/services/session.server.ts
index fc1f55651e..344eda65d7 100644
--- a/apps/carbon/app/services/session.server.ts
+++ b/apps/carbon/app/services/session.server.ts
@@ -5,7 +5,7 @@ import { getCurrentPath, isGet, makeRedirectToFromHere } from "~/utils/http";
import {
NODE_ENV,
REFRESH_ACCESS_TOKEN_THRESHOLD,
- SESSION_ERROR_KEY,
+ SESSION_COMPANY_KEY,
SESSION_KEY,
SESSION_MAX_AGE,
SESSION_SECRET,
@@ -46,10 +46,10 @@ export async function commitAuthSession(
request: Request,
{
authSession,
- flashErrorMessage,
+ company,
}: {
authSession?: AuthSession | null;
- flashErrorMessage?: string | null;
+ company?: number;
} = {}
) {
const session = await getSession(request);
@@ -60,7 +60,9 @@ export async function commitAuthSession(
session.set(SESSION_KEY, authSession);
}
- session.flash(SESSION_ERROR_KEY, flashErrorMessage);
+ if (company !== undefined) {
+ session.set(SESSION_COMPANY_KEY, company);
+ }
return sessionStorage.commitSession(session, { maxAge: SESSION_MAX_AGE });
}
@@ -87,6 +89,13 @@ export async function flash(request: Request, result: Result) {
};
}
+export async function getCompanySession(
+ request: Request
+): Promise<number | null> {
+ const session = await getSession(request);
+ return session.get(SESSION_COMPANY_KEY);
+}
+
export async function getAuthSession(
request: Request
): Promise<AuthSession | null> {
@@ -145,9 +154,11 @@ export async function refreshAuthSession(
request: Request
): Promise<AuthSession> {
const authSession = await getAuthSession(request);
+ const companyId = await getCompanySession(request);
const refreshedAuthSession = await refreshAccessToken(
- authSession?.refreshToken
+ authSession?.refreshToken,
+ companyId
);
if (!refreshedAuthSession) {
@@ -159,7 +170,6 @@ export async function refreshAuthSession(
headers: {
"Set-Cookie": await commitAuthSession(request, {
authSession: null,
- flashErrorMessage: "fail-refresh-auth-session",
}),
},
});
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 0110594581..34fe036f73 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -466,7 +466,7 @@ export const path = {
requestForQuoteFavorite: `${x}/purchasing/rfqs/favorite`,
requestForQuotes: `${x}/purchasing/rfqs`,
resendInvite: `${x}/users/resend-invite`,
- resetPassord: "/reset-password",
+ resetPassword: "/reset-password",
resources: `${x}/resources`,
root: "/",
routings: `${x}/parts/routing`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 73bca86690..adea112043 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -14871,6 +14871,7 @@ export type Database = {
id: string | null;
logo: string | null;
name: string | null;
+ orderCount: number | null;
status: string | null;
taxId: string | null;
type: string | null;
diff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sql
index 90b3aa866b..c6caa4e377 100644
--- a/packages/database/supabase/migrations/20230123004206_claims.sql
+++ b/packages/database/supabase/migrations/20230123004206_claims.sql
@@ -67,21 +67,18 @@ $$;
CREATE OR REPLACE FUNCTION has_company_permission(claim text, company integer) RETURNS "bool"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
+ DECLARE
+ claim_value JSONB;
BEGIN
- IF EXISTS (
- SELECT 1
- FROM jsonb_array_elements_text((current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->claim) AS j
- WHERE j::int = 0
- ) THEN
+ SELECT coalesce(raw_app_meta_data->claim, null) INTO claim_value FROM auth.users WHERE id = auth.uid();
+ IF claim_value IS NULL THEN
+ return false;
+ ELSIF claim_value::text ~ '^[0-9]+$' AND claim_value::text::integer = 0 THEN
return true;
- ELSIF EXISTS (
- SELECT 1
- FROM jsonb_array_elements_text((current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->claim) AS j
- WHERE j::int = company
- ) THEN
+ ELSIF claim_value::text ~ '^[0-9]+$' AND claim_value::text::integer = company THEN
return true;
ELSE
- return false;
+ return false;
END IF;
END;
$$;
@@ -108,6 +105,8 @@ CREATE OR REPLACE FUNCTION get_claim(uid uuid, claim text) RETURNS "jsonb"
END;
$$;
+
+
CREATE OR REPLACE FUNCTION set_claim(uid uuid, claim text, value jsonb) RETURNS "text"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
diff --git a/packages/database/supabase/migrations/20230123004514_buckets.sql b/packages/database/supabase/migrations/20230123004514_buckets.sql
index e45df5f21d..ef3b66889d 100644
--- a/packages/database/supabase/migrations/20230123004514_buckets.sql
+++ b/packages/database/supabase/migrations/20230123004514_buckets.sql
@@ -14,21 +14,42 @@ CREATE POLICY "Employees with settings_create can insert into the public bucket"
ON storage.objects FOR INSERT WITH CHECK (
bucket_id = 'public'
AND (auth.role() = 'authenticated')
- -- AND has_company_permission('settings_create', (storage.foldername(name))[1])
+ -- AND (
+ -- CAST((storage.foldername(name))[1] AS INTEGER) = ANY(
+ -- coalesce(
+ -- get_permission_companies('settings_create')::integer[],
+ -- array[]::integer[]
+ -- )
+ -- )
+ -- )
);
CREATE POLICY "Employees with settings_update can update the public bucket"
ON storage.objects FOR UPDATE USING (
bucket_id = 'public'
AND (auth.role() = 'authenticated')
- -- AND has_company_permission('settings_update', (storage.foldername(name))[1])
+ -- AND (
+ -- CAST((storage.foldername(name))[1] AS INTEGER) = ANY(
+ -- coalesce(
+ -- get_permission_companies('settings_update')::integer[],
+ -- array[]::integer[]
+ -- )
+ -- )
+ -- )
);
CREATE POLICY "Employees with settings_delete can delete from public bucket"
ON storage.objects FOR DELETE USING (
bucket_id = 'public'
AND (auth.role() = 'authenticated')
- -- AND has_company_permission('settings_delete', (storage.foldername(name))[1])
+ -- AND (
+ -- CAST((storage.foldername(name))[1] AS INTEGER) = ANY(
+ -- coalesce(
+ -- get_permission_companies('settings_delete')::integer[],
+ -- array[]::integer[]
+ -- )
+ -- )
+ -- )
);
CREATE POLICY "Anyone can view avatars"