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.

🔐 add permissions to loaders/actions/components

Brad Barbin151e9d98ed82
diff --git a/apps/carbon/app/components/Navigation/Sidebar/useSidebar.tsx b/apps/carbon/app/components/Navigation/Sidebar/useSidebar.tsx
index 341a4c6302..dbdbfbee7f 100644
--- a/apps/carbon/app/components/Navigation/Sidebar/useSidebar.tsx
+++ b/apps/carbon/app/components/Navigation/Sidebar/useSidebar.tsx
@@ -11,7 +11,7 @@ import { CgProfile } from "react-icons/cg";
import { GoSettings } from "react-icons/go";
import { HiOutlineCube, HiOutlineDocumentDuplicate } from "react-icons/hi";
import { SiHandshake } from "react-icons/si";
-import { usePermissions } from "~/hooks/usePermissions";
+import { usePermissions } from "~/hooks";
const sidebarItems: Authenticated<NavItem>[] = [
{
@@ -97,9 +97,7 @@ export function useSidebar() {
const permissions = usePermissions();
return sidebarItems.filter((item) => {
if (item.permission) {
- return (
- item.permission in permissions && permissions[item.permission].view
- );
+ return permissions.can("view", item.permission);
} else {
return true;
}
diff --git a/apps/carbon/app/hooks/index.ts b/apps/carbon/app/hooks/index.ts
index ee7b24704b..a46831c5a0 100644
--- a/apps/carbon/app/hooks/index.ts
+++ b/apps/carbon/app/hooks/index.ts
@@ -1,5 +1,6 @@
+import { usePermissions } from "./usePermissions";
import { useRouteData } from "./useRouteData";
import { useUser } from "./useUser";
import { useUrlParams } from "./useUrlParams";
-export { useRouteData, useUser, useUrlParams };
+export { usePermissions, useRouteData, useUser, useUrlParams };
diff --git a/apps/carbon/app/hooks/usePermissions.tsx b/apps/carbon/app/hooks/usePermissions.tsx
index 3a514e8547..955b352936 100644
--- a/apps/carbon/app/hooks/usePermissions.tsx
+++ b/apps/carbon/app/hooks/usePermissions.tsx
@@ -1,15 +1,31 @@
+import { useCallback } from "react";
import type { Permission } from "~/modules/Users/types";
import { useRouteData } from "./useRouteData";
export function usePermissions() {
const data = useRouteData<{ permissions: unknown }>("/app");
- if (data?.permissions && isPermissions(data.permissions)) {
- return data.permissions;
+
+ if (!isPermissions(data?.permissions)) {
+ // TODO: force logout -- the likely cause is development changes
+ throw new Error(
+ "usePermissions must be used within an authenticated route. If you are seeing this error, you are likely in development and have changed the session variables. Try deleting the cookies."
+ );
}
- // TODO: force logout -- the likely cause is development changes
- throw new Error(
- "usePermissions must be used within an authenticated route. If you are seeing this error, you are likely in development and have changed the session variables. Try deleting the cookies."
+
+ const can = useCallback(
+ (action: "view" | "create" | "update" | "delete", feature: string) => {
+ return (
+ // not sure why we have to type cast here
+ (data?.permissions as Record<string, Permission>)[feature]?.[action] ??
+ false
+ );
+ },
+ [data?.permissions]
);
+
+ return {
+ can,
+ };
}
function isPermissions(value: any): value is Record<string, Permission> {
diff --git a/apps/carbon/app/modules/Users/EmployeeTypesTable/EmployeeTypesTable.tsx b/apps/carbon/app/modules/Users/EmployeeTypesTable/EmployeeTypesTable.tsx
index c17ab386b6..c26533599e 100644
--- a/apps/carbon/app/modules/Users/EmployeeTypesTable/EmployeeTypesTable.tsx
+++ b/apps/carbon/app/modules/Users/EmployeeTypesTable/EmployeeTypesTable.tsx
@@ -4,6 +4,7 @@ import { useNavigate } from "@remix-run/react";
import { memo } from "react";
import { BsPencilSquare } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
+import { usePermissions } from "~/hooks";
import type { EmployeeType } from "~/modules/Users/types";
type EmployeeTypesTableProps = {
@@ -12,6 +13,8 @@ type EmployeeTypesTableProps = {
const EmployeeTypesTable = memo(({ data }: EmployeeTypesTableProps) => {
const navigate = useNavigate();
+ const permissions = usePermissions();
+
const rows = data.map((row) => ({
id: row.id,
protected: row.protected,
@@ -27,20 +30,28 @@ const EmployeeTypesTable = memo(({ data }: EmployeeTypesTableProps) => {
),
actions: (
<Flex justifyContent="end">
- {!row.protected && (
- <ActionMenu>
- <MenuItem icon={<BsPencilSquare />}>Edit Employee Type</MenuItem>
- <MenuItem
- icon={<IoMdTrash />}
- onClick={(e) => {
- e.stopPropagation();
- navigate(`/app/users/employee-types/delete/${row.id}`);
- }}
- >
- Delete Employee Type
- </MenuItem>
- </ActionMenu>
- )}
+ {!row.protected &&
+ (permissions.can("update", "users") ||
+ permissions.can("delete", "users")) && (
+ <ActionMenu>
+ {permissions.can("update", "users") && (
+ <MenuItem icon={<BsPencilSquare />}>
+ Edit Employee Type
+ </MenuItem>
+ )}
+ {permissions.can("delete", "users") && (
+ <MenuItem
+ icon={<IoMdTrash />}
+ onClick={(e) => {
+ e.stopPropagation();
+ navigate(`/app/users/employee-types/delete/${row.id}`);
+ }}
+ >
+ Delete Employee Type
+ </MenuItem>
+ )}
+ </ActionMenu>
+ )}
</Flex>
),
}));
diff --git a/apps/carbon/app/modules/Users/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/modules/Users/EmployeesTable/EmployeesTable.tsx
index 5b7f9db5c7..b7debdae83 100644
--- a/apps/carbon/app/modules/Users/EmployeesTable/EmployeesTable.tsx
+++ b/apps/carbon/app/modules/Users/EmployeesTable/EmployeesTable.tsx
@@ -4,6 +4,7 @@ import { useNavigate } from "@remix-run/react";
import { memo } from "react";
import { BsPencilSquare } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
+import { usePermissions } from "~/hooks";
import type { Employee } from "../types";
type EmployeesTableProps = {
@@ -12,6 +13,8 @@ type EmployeesTableProps = {
const EmployeesTable = memo(({ data }: EmployeesTableProps) => {
const navigate = useNavigate();
+ const permissions = usePermissions();
+
const rows = data.map(({ User, EmployeeType }) => {
if (
User === null ||
@@ -28,18 +31,21 @@ const EmployeesTable = memo(({ data }: EmployeesTableProps) => {
employeeType: EmployeeType.name,
actions: (
<Flex justifyContent="end">
- <ActionMenu>
- <MenuItem icon={<BsPencilSquare />}>Edit Permissions</MenuItem>
- <MenuItem
- icon={<IoMdTrash />}
- onClick={(e) => {
- e.stopPropagation();
- navigate(`/app/users/employeess/deactivate/${User.id}`);
- }}
- >
- Deactivate Employee
- </MenuItem>
- </ActionMenu>
+ {(permissions.can("update", "users") ||
+ permissions.can("delete", "users")) && (
+ <ActionMenu>
+ <MenuItem icon={<BsPencilSquare />}>Edit Permissions</MenuItem>
+ <MenuItem
+ icon={<IoMdTrash />}
+ onClick={(e) => {
+ e.stopPropagation();
+ navigate(`/app/users/employeess/deactivate/${User.id}`);
+ }}
+ >
+ Deactivate Employee
+ </MenuItem>
+ </ActionMenu>
+ )}
</Flex>
),
};
diff --git a/apps/carbon/app/routes/app.parts.tsx b/apps/carbon/app/routes/app.parts.tsx
index 085feb41df..c62786eef2 100644
--- a/apps/carbon/app/routes/app.parts.tsx
+++ b/apps/carbon/app/routes/app.parts.tsx
@@ -12,7 +12,7 @@ import ReactFlow, {
useEdgesState,
} from "reactflow";
import reactFlowStyles from "reactflow/dist/style.css";
-import { requireAuthSession } from "~/services/session";
+import { requirePermissions } from "~/services/auth";
export const meta: MetaFunction = () => ({
title: "Carbon | Parts",
@@ -23,7 +23,10 @@ export function links() {
}
export async function loader({ request }: LoaderArgs) {
- await requireAuthSession(request);
+ await requirePermissions(request, {
+ view: "parts",
+ });
+
const nodes: Node[] = [
{
id: "1",
diff --git a/apps/carbon/app/routes/app.tsx b/apps/carbon/app/routes/app.tsx
index d2316ff3bb..1c694d1a18 100644
--- a/apps/carbon/app/routes/app.tsx
+++ b/apps/carbon/app/routes/app.tsx
@@ -29,11 +29,11 @@ export async function loader({ request }: LoaderArgs) {
getUserByClient(client),
]);
- if (user.error) {
+ if (user?.error) {
await destroyAuthSession(request);
}
- if (claims.error || user.error || claims.data === null) {
+ if (claims?.error || user?.error || claims?.data === null) {
await destroyAuthSession(request);
}
diff --git a/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx b/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx
index 4c7678508d..50c91cc581 100644
--- a/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.$employeeTypeId.tsx
@@ -3,8 +3,8 @@ import { redirect } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import { getSupabase } from "~/lib/supabase";
import { EmployeeTypeForm } from "~/modules/Users";
+import { requirePermissions } from "~/services/auth";
import {
employeeTypeValidator,
getEmployeeType,
@@ -13,17 +13,17 @@ import {
upsertEmployeeType,
upsertEmployeeTypePermissions,
} from "~/services/users";
-import { requireAuthSession, setSessionFlash } from "~/services/session";
+import { setSessionFlash } from "~/services/session";
import { assertIsPost } from "~/utils/http";
export async function loader({ request, params }: LoaderArgs) {
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
const { employeeTypeId } = params;
if (!employeeTypeId) return redirect("/app/users/employee-types");
- const client = getSupabase(accessToken);
-
const [employeeType, employeeTypePermissions] = await Promise.all([
getEmployeeType(client, employeeTypeId),
getPermissionsByEmployeeType(client, employeeTypeId),
@@ -43,7 +43,10 @@ export async function loader({ request, params }: LoaderArgs) {
export async function action({ request }: ActionArgs) {
assertIsPost(request);
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ update: "users",
+ });
+
const validation = await employeeTypeValidator.validate(
await request.formData()
);
@@ -53,9 +56,9 @@ export async function action({ request }: ActionArgs) {
}
const { id, name, color, data } = validation.data;
+ // TODO: parse with io-ts
const permissions = JSON.parse(data);
- const client = getSupabase(accessToken);
const updateEmployeeType = await upsertEmployeeType(client, {
id,
name,
diff --git a/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx b/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx
index c41bb6a1c3..ff3db3861b 100644
--- a/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.delete.$employeeTypeId.tsx
@@ -11,20 +11,23 @@ import {
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useLoaderData, useNavigate, useParams } from "@remix-run/react";
-import { getSupabase } from "~/lib/supabase";
+import { requirePermissions } from "~/services/auth";
import { deleteEmployeeType, getEmployeeType } from "~/services/users";
-import { requireAuthSession, setSessionFlash } from "~/services/session";
+import { setSessionFlash } from "~/services/session";
export async function loader({ request, params }: LoaderArgs) {
- const { accessToken } = await requireAuthSession(request);
- const client = getSupabase(accessToken);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
const { employeeTypeId } = params;
return json(await getEmployeeType(client, employeeTypeId!));
}
export async function action({ request, params }: ActionArgs) {
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ delete: "users",
+ });
const { employeeTypeId } = params;
if (!employeeTypeId) {
@@ -37,7 +40,6 @@ export async function action({ request, params }: ActionArgs) {
);
}
- const client = getSupabase(accessToken);
const deleteType = await deleteEmployeeType(client, employeeTypeId);
if (deleteType.error) {
return redirect(
diff --git a/apps/carbon/app/routes/app.users.employee-types.new.tsx b/apps/carbon/app/routes/app.users.employee-types.new.tsx
index 22c4ae67ec..7d954438d6 100644
--- a/apps/carbon/app/routes/app.users.employee-types.new.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.new.tsx
@@ -5,6 +5,7 @@ import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import { getSupabase } from "~/lib/supabase";
import { EmployeeTypeForm } from "~/modules/Users";
+import { requirePermissions } from "~/services/auth";
import {
employeeTypeValidator,
getFeatures,
@@ -37,7 +38,10 @@ export async function loader({ request }: LoaderArgs) {
export async function action({ request }: ActionArgs) {
assertIsPost(request);
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ create: "users",
+ });
+
const validation = await employeeTypeValidator.validate(
await request.formData()
);
@@ -47,9 +51,9 @@ export async function action({ request }: ActionArgs) {
}
const { name, color, data } = validation.data;
+ // TODO: parse with io-ts
const permissions = JSON.parse(data);
- const client = getSupabase(accessToken);
const insertEmployeeType = await upsertEmployeeType(client, {
name,
color: color || null,
diff --git a/apps/carbon/app/routes/app.users.employee-types.tsx b/apps/carbon/app/routes/app.users.employee-types.tsx
index 73c7cc20b2..bd35d752d6 100644
--- a/apps/carbon/app/routes/app.users.employee-types.tsx
+++ b/apps/carbon/app/routes/app.users.employee-types.tsx
@@ -10,20 +10,22 @@ import type { LoaderArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Link, Outlet, useLoaderData } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
-import { getSupabase } from "~/lib/supabase";
+import { usePermissions } from "~/hooks";
import { EmployeeTypesTable } from "~/modules/Users";
+import { requirePermissions } from "~/services/auth";
import { getEmployeeTypes } from "~/services/users";
-import { requireAuthSession } from "~/services/session";
export async function loader({ request }: LoaderArgs) {
- const { accessToken } = await requireAuthSession(request);
- const client = getSupabase(accessToken);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
return json(await getEmployeeTypes(client));
}
export default function EmployeeTypesRoute() {
const { data } = useLoaderData<typeof loader>();
+ const permissions = usePermissions();
const borderColor = useColorModeValue("gray.200", "gray.800");
return (
@@ -44,14 +46,16 @@ export default function EmployeeTypesRoute() {
</Select>
</HStack>
<HStack spacing={2}>
- <Button
- as={Link}
- to="new"
- colorScheme="brand"
- leftIcon={<IoMdAdd />}
- >
- New Employee Type
- </Button>
+ {permissions.can("create", "users") && (
+ <Button
+ as={Link}
+ to="new"
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Employee Type
+ </Button>
+ )}
</HStack>
</HStack>
<EmployeeTypesTable data={data ?? []} />
diff --git a/apps/carbon/app/routes/app.users.employees.$employeeId.tsx b/apps/carbon/app/routes/app.users.employees.$employeeId.tsx
index 4497b22b88..5d62c12260 100644
--- a/apps/carbon/app/routes/app.users.employees.$employeeId.tsx
+++ b/apps/carbon/app/routes/app.users.employees.$employeeId.tsx
@@ -3,9 +3,9 @@ import { json } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import { getSupabase } from "~/lib/supabase";
import { EmployeePermissionsForm } from "~/modules/Users";
-import { requireAuthSession, setSessionFlash } from "~/services/session";
+import { requirePermissions } from "~/services/auth";
+import { setSessionFlash } from "~/services/session";
import {
employeeValidator,
getClaimsById,
@@ -16,12 +16,13 @@ import {
import { assertIsPost } from "~/utils/http";
export async function loader({ request, params }: LoaderArgs) {
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
const { employeeId } = params;
if (!employeeId) return redirect("/app/users/employees");
- const client = getSupabase(accessToken);
const [claims, employee] = await Promise.all([
getClaimsById(client, employeeId),
getUserById(client, employeeId),
@@ -56,7 +57,10 @@ export async function loader({ request, params }: LoaderArgs) {
export async function action({ request }: ActionArgs) {
assertIsPost(request);
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ update: "users",
+ });
+
const validation = await employeeValidator.validate(await request.formData());
if (validation.error) {
@@ -64,11 +68,9 @@ export async function action({ request }: ActionArgs) {
}
const { id, data } = validation.data;
- const permissions = JSON.parse(data);
-
// TODO: io-ts validation on permissions
+ const permissions = JSON.parse(data);
- const client = getSupabase(accessToken);
const result = await updatePermissions(client, {
id,
permissions,
diff --git a/apps/carbon/app/routes/app.users.employees.new.tsx b/apps/carbon/app/routes/app.users.employees.new.tsx
index 1ce2bf6af1..e2ffe1ab89 100644
--- a/apps/carbon/app/routes/app.users.employees.new.tsx
+++ b/apps/carbon/app/routes/app.users.employees.new.tsx
@@ -1,18 +1,20 @@
import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import { requireAuthSession, setSessionFlash } from "~/services/session";
+import { requirePermissions } from "~/services/auth";
+import { setSessionFlash } from "~/services/session";
import {
createEmployeeAccount,
createEmployeeValidator,
} from "~/services/users";
import { assertIsPost } from "~/utils/http";
-import { getSupabase } from "~/lib/supabase";
import { CreateEmployeeModal } from "~/modules/Users";
export async function action({ request }: ActionArgs) {
assertIsPost(request);
- const { accessToken } = await requireAuthSession(request);
+ const { client } = await requirePermissions(request, {
+ create: "users",
+ });
const validation = await createEmployeeValidator.validate(
await request.formData()
@@ -22,7 +24,6 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const client = getSupabase(accessToken);
const { email, firstName, lastName, employeeType } = validation.data;
const result = await createEmployeeAccount(client, {
email,
diff --git a/apps/carbon/app/routes/app.users.employees.tsx b/apps/carbon/app/routes/app.users.employees.tsx
index ef058b3476..0a5ebf7ae2 100644
--- a/apps/carbon/app/routes/app.users.employees.tsx
+++ b/apps/carbon/app/routes/app.users.employees.tsx
@@ -5,16 +5,16 @@ import { json } from "@remix-run/node";
import { Outlet, useLoaderData, useNavigate } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
-import { useUrlParams } from "~/hooks";
-import { getSupabase } from "~/lib/supabase";
+import { usePermissions, useUrlParams } from "~/hooks";
import { EmployeesTable } from "~/modules/Users";
+import { requirePermissions } from "~/services/auth";
import { getEmployees, getEmployeeTypes } from "~/services/users";
-import { requireAuthSession } from "~/services/session";
import { mapRowsToOptions } from "~/utils/form";
export async function loader({ request }: LoaderArgs) {
- const { accessToken } = await requireAuthSession(request);
- const client = getSupabase(accessToken);
+ const { client } = await requirePermissions(request, {
+ view: "users",
+ });
const url = new URL(request.url);
const search = new URLSearchParams(url.search);
@@ -33,6 +33,7 @@ export default function UsersEmployeesRoute() {
const { employees, employeeTypes } = useLoaderData<typeof loader>();
const [params, setParams] = useUrlParams();
const navigate = useNavigate();
+ const permissions = usePermissions();
const borderColor = useColorModeValue("gray.200", "gray.800");
@@ -76,15 +77,17 @@ export default function UsersEmployeesRoute() {
/>
</HStack>
<HStack spacing={2}>
- <Button
- colorScheme="brand"
- onClick={() => {
- navigate("new");
- }}
- leftIcon={<IoMdAdd />}
- >
- New Employee
- </Button>
+ {permissions.can("create", "users") && (
+ <Button
+ colorScheme="brand"
+ onClick={() => {
+ navigate("new");
+ }}
+ leftIcon={<IoMdAdd />}
+ >
+ New Employee
+ </Button>
+ )}
</HStack>
</HStack>
<EmployeesTable data={employees.data ?? []} />
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index f00145a2d4..f1b02d358c 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -1,4 +1,5 @@
import type { Database } from "@carbon/database";
+import { redirect } from "@remix-run/node";
import type {
AuthSession as SupabaseAuthSession,
SupabaseClient,
@@ -6,6 +7,8 @@ import type {
import { SERVER_URL } from "~/config/env";
import { REFRESH_ACCESS_TOKEN_THRESHOLD } from "~/config/env";
import { getSupabase, getSupabaseAdmin } from "~/lib/supabase";
+import { requireAuthSession, setSessionFlash } from "../session";
+import { makePermissionsFromClaims } from "../users";
import type { AuthSession } from "./types";
export async function getUserByClient(client: SupabaseClient<Database>) {
@@ -104,6 +107,76 @@ export async function refreshAccessToken(
return makeAuthSession(data.session);
}
+export async function requirePermissions(
+ request: Request,
+ requiredPermissions: {
+ view?: string | string[];
+ create?: string | string[];
+ update?: string | string[];
+ delete?: string | string[];
+ }
+) {
+ const { accessToken } = await requireAuthSession(request);
+ const client = getSupabase(accessToken);
+ // early exit if no requiredPermissions are required
+ if (Object.keys(requiredPermissions).length === 0) return { client };
+
+ // TODO: use redis to cache permissions
+ const getMyClaims = await client.rpc("get_my_claims");
+
+ if (getMyClaims.error || getMyClaims.data === null) {
+ throw redirect(
+ "/app",
+ await setSessionFlash(request, {
+ success: false,
+ message: "Failed to parse claims",
+ })
+ );
+ }
+
+ const myPermissions = makePermissionsFromClaims(getMyClaims.data);
+
+ if (!myPermissions) {
+ throw redirect(
+ "/app",
+ await setSessionFlash(request, {
+ success: false,
+ message: "Failed to parse claims",
+ })
+ );
+ }
+
+ const hasRequiredPermissions = Object.entries(requiredPermissions).every(
+ ([action, permission]) => {
+ if (typeof permission === "string") {
+ return myPermissions![permission][
+ action as "view" | "create" | "update" | "delete"
+ ];
+ } else if (Array.isArray(permission)) {
+ return permission.every((p) => {
+ return !myPermissions![p][
+ action as "view" | "create" | "update" | "delete"
+ ];
+ });
+ } else {
+ return false;
+ }
+ }
+ );
+
+ if (!hasRequiredPermissions) {
+ throw redirect(
+ "/app",
+ await setSessionFlash(request, {
+ success: false,
+ message: "Access Denied",
+ })
+ );
+ }
+
+ return { client };
+}
+
export async function resetPassword(accessToken: string, password: string) {
const { error } = await getSupabase(accessToken).auth.updateUser({
password,
diff --git a/apps/carbon/app/services/session/session.server.ts b/apps/carbon/app/services/session/session.server.ts
index 59b5c1eead..ede6b1cc99 100644
--- a/apps/carbon/app/services/session/session.server.ts
+++ b/apps/carbon/app/services/session/session.server.ts
@@ -20,10 +20,6 @@ import { refreshAccessToken, verifyAuthSession } from "../auth/auth.server";
import type { AuthSession } from "../auth/types";
import type { Result } from "~/types";
-/**
- * Session storage CRUD
- */
-
const sessionStorage = createCookieSessionStorage({
cookie: {
name: "__authSession",
@@ -153,19 +149,19 @@ export async function requireAuthSession(
{
onFailRedirectTo,
verify,
- }: { onFailRedirectTo?: string; verify: boolean } = { verify: false }
+ }: {
+ onFailRedirectTo?: string;
+ verify: boolean;
+ } = { verify: false }
): Promise<AuthSession> {
- // hello there
const authSession = await assertAuthSession(request, {
onFailRedirectTo,
});
- // ok, let's challenge its access token.
- // by default, we don't verify the access token from supabase auth api to save some time
+ // by default we don't verify the session to save time
const isValidSession = verify ? await verifyAuthSession(authSession) : true;
- // damn, access token is not valid or expires soon
- // let's try to refresh, in case of 🧐
+ // if not valid, we try to refresh the session
if (!isValidSession || isExpiringSoon(authSession.expiresAt)) {
return refreshAuthSession(request);
}
diff --git a/apps/carbon/remix.config.js b/apps/carbon/remix.config.js
index 63c7b48d81..af0a3cf81f 100644
--- a/apps/carbon/remix.config.js
+++ b/apps/carbon/remix.config.js
@@ -18,6 +18,12 @@ module.exports = {
ignoredRouteFiles: [], // same as remix config
});
},
+ serverDependenciesToBundle: [
+ "@carbon/database",
+ "@carbon/logger",
+ "@carbon/react",
+ "@carbon/utils",
+ ],
watchPaths: async () => {
return [
"../../packages/carbon-react/src/**/*",
diff --git a/turbo.json b/turbo.json
index 732a570ca3..5d0edcdcf8 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,6 +1,5 @@
{
"$schema": "https://turborepo.org/schema.json",
- "globalDependencies": [".env"],
"pipeline": {
"build": {
"outputs": [