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.

2.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { useRouteData } from "@carbon/react";
import { path } from "~/utils/path";

type PersonalData = {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  avatarUrl: string | null;
};

type Company = {
  id: string;
  name: string;
  logoDarkIcon: string | null;
  logoLightIcon: string | null;
  logoDark: string | null;
  logoLight: string | null;
};

type User = PersonalData & {
  company: Company;
};

export function useUser(): User {
  const data = useRouteData<{
    company: unknown;
    user: unknown;
    effectiveUserId?: string;
  }>(path.to.authenticatedRoot);

  if (
    data?.company &&
    isCompany(data.company) &&
    data?.user &&
    isUser(data.user)
  ) {
    return {
      ...data.user,
      id: data.effectiveUserId ?? data.user.id,
      company: data.company
    };
  }

  // TODO: force logout -- the likely cause is development changes
  throw new Error(
    "useUser 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."
  );
}

function isCompany(value: any): value is Company {
  return (
    typeof value.id === "string" &&
    typeof value.name === "string" &&
    (typeof value.logoDarkIcon === "string" || value.logoDarkIcon === null) &&
    (typeof value.logoLightIcon === "string" || value.logoLightIcon === null) &&
    (typeof value.logoDark === "string" || value.logoDark === null) &&
    (typeof value.logoLight === "string" || value.logoLight === null)
  );
}

function isUser(value: any): value is User {
  return (
    typeof value.id === "string" &&
    typeof value.email === "string" &&
    typeof value.firstName === "string" &&
    typeof value.lastName === "string" &&
    "avatarUrl" in value
  );
}