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.

feat: add the ability to accept invites

Brad Barbin2dc8bf816b2c
diff --git a/apps/carbon/app/components/EmployeeAvatar.tsx b/apps/carbon/app/components/EmployeeAvatar.tsx
index a529865337..6089e17d54 100644
--- a/apps/carbon/app/components/EmployeeAvatar.tsx
+++ b/apps/carbon/app/components/EmployeeAvatar.tsx
@@ -34,9 +34,6 @@ const EmployeeAvatar = ({
return (
<HStack className="no-underline">
<Avatar size={"xs"} {...props} />
- {withName && (
- <span className="text-muted-foreground">Deactivated user</span>
- )}
</HStack>
);
}
diff --git a/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx
index f8ee520ba7..91fd3e15ff 100644
--- a/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx
+++ b/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx
@@ -2,7 +2,6 @@ import {
Checkbox,
DropdownMenuContent,
DropdownMenuItem,
- HStack,
MenuIcon,
MenuItem,
useDisclosure,
@@ -71,8 +70,8 @@ const EmployeesTable = memo(
return [
{
header: "User",
- cell: ({ row }) => (
- <HStack>
+ cell: ({ row }) => {
+ return row.original.active === true ? (
<Hyperlink
to={`${path.to.employeeAccount(
row.original.id!
@@ -80,8 +79,12 @@ const EmployeesTable = memo(
>
<EmployeeAvatar size="sm" employeeId={row.original.id} />
</Hyperlink>
- </HStack>
- ),
+ ) : (
+ <div className="opacity-70">
+ <EmployeeAvatar size="sm" employeeId={row.original.id} />
+ </div>
+ );
+ },
meta: {
icon: <LuUser />,
},
@@ -171,16 +174,6 @@ const EmployeesTable = memo(
<LuShield className="mr-2 h-4 w-4" />
<span>Edit Permissions</span>
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => {
- setSelectedUserIds(selectedRows.map((row) => row.id!));
- resendInviteModal.onOpen();
- }}
- disabled={!permissions.can("create", "users")}
- >
- <LuMailCheck className="mr-2 h-4 w-4" />
- <span>Resend Account Invite</span>
- </DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setSelectedUserIds(selectedRows.map((row) => row.id!));
@@ -194,32 +187,35 @@ const EmployeesTable = memo(
</DropdownMenuContent>
);
},
- [permissions, bulkEditDrawer, resendInviteModal, deactivateEmployeeModal]
+ [permissions, bulkEditDrawer, deactivateEmployeeModal]
);
const renderContextMenu = useCallback(
(row: (typeof data)[number]) => {
return (
<>
- <MenuItem
- onClick={() =>
- navigate(
- `${path.to.employeeAccount(row.id!)}?${params.toString()}`
- )
- }
- >
- <MenuIcon icon={<LuPencil />} />
- Edit Permissions
- </MenuItem>
- <MenuItem
- onClick={() => {
- setSelectedUserIds([row.id!]);
- resendInviteModal.onOpen();
- }}
- >
- <MenuIcon icon={<LuMailCheck />} />
- Resend Account Invite
- </MenuItem>
+ {row.active === true ? (
+ <MenuItem
+ onClick={() =>
+ navigate(
+ `${path.to.employeeAccount(row.id!)}?${params.toString()}`
+ )
+ }
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Permissions
+ </MenuItem>
+ ) : (
+ <MenuItem
+ onClick={() => {
+ setSelectedUserIds([row.id!]);
+ resendInviteModal.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuMailCheck />} />
+ Resend Account Invite
+ </MenuItem>
+ )}
{row.active === true && (
<MenuItem
onClick={(e) => {
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index ed92cb5565..63f052932d 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -138,8 +138,11 @@ export async function createCustomerAccount(
}
}
-export async function acceptInvite(code: string) {
- const serviceRole = getCarbonServiceRole();
+export async function acceptInvite(
+ serviceRole: SupabaseClient<Database>,
+ code: string,
+ email?: string
+) {
const invite = await serviceRole
.from("invite")
.select("*")
@@ -149,8 +152,14 @@ export async function acceptInvite(code: string) {
if (invite.error) return invite;
+ if (email && invite.data.email !== email) {
+ throw new Error(
+ "Invite code does not match email. Please logout and try again."
+ );
+ }
+
const user = await getUserByEmail(invite.data.email);
- if (user.error || !user.data) return user;
+ if (user.error) return user;
const [activate, addUser, setPermissions] = await Promise.all([
activateEmployee(serviceRole, {
@@ -196,10 +205,12 @@ export async function acceptInvite(code: string) {
return setPermissions;
}
- return await serviceRole
+ return serviceRole
.from("invite")
.update({ acceptedAt: new Date().toISOString() })
- .eq("code", code);
+ .eq("code", code)
+ .select("*")
+ .single();
}
async function activateEmployee(
@@ -652,8 +663,8 @@ export async function getUserByEmail(email: string) {
return getCarbonServiceRole()
.from("user")
.select("*")
- .eq("email", email)
- .maybeSingle();
+ .eq("email", email.toLowerCase())
+ .single();
}
export async function getUserClaims(userId: string, companyId: string) {
diff --git a/apps/carbon/app/routes/_public+/_layout.tsx b/apps/carbon/app/routes/_public+/_layout.tsx
index 3a68364870..171dd639b1 100644
--- a/apps/carbon/app/routes/_public+/_layout.tsx
+++ b/apps/carbon/app/routes/_public+/_layout.tsx
@@ -7,7 +7,7 @@ export default function PublicRoute() {
<div className="flex min-h-screen min-w-screen">
<VStack
spacing={8}
- className="items-center justify-start pt-[20dvh] mx-auto max-w-lg z-[3]"
+ className="items-center justify-start pt-[16dvh] mx-auto max-w-lg z-[3]"
>
<Outlet />
</VStack>
diff --git a/apps/carbon/app/routes/_public+/confirm-invite.tsx b/apps/carbon/app/routes/_public+/confirm-invite.tsx
deleted file mode 100644
index 7feed42ba3..0000000000
--- a/apps/carbon/app/routes/_public+/confirm-invite.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { SUPABASE_API_URL } from "@carbon/auth";
-import { Button as _Button, Heading as _Heading, VStack } from "@carbon/react";
-import { useNavigate, useSearchParams } from "@remix-run/react";
-import { AnimatePresence, motion } from "framer-motion";
-
-const Heading = motion(_Heading);
-const Button = motion(_Button);
-
-const fade = {
- initial: { opacity: 0 },
- animate: { opacity: 1 },
-};
-
-export default function ConfirmInvite() {
- const [params] = useSearchParams();
- const navigate = useNavigate();
-
- const token = params.get("token");
- if (!token) {
- navigate("/");
- return null;
- }
-
- const getConfirmationURL = (token: string) => {
- return `${SUPABASE_API_URL}/auth/v1/verify?token=${token}&type=invite&redirect_to=${window?.location.origin}/callback`;
- };
-
- return (
- <AnimatePresence>
- <VStack
- spacing={4}
- className="max-w-lg pt-[20dvh] items-center text-center"
- >
- <motion.img
- initial={{ opacity: 0, scale: 0.4 }}
- animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 2, ease: "easeInOut" }}
- src="/carbon-logo-dark.png"
- alt="Carbon Logo"
- className="block dark:hidden max-w-[60px] mb-3"
- />
- <motion.img
- initial={{ opacity: 0, scale: 0.4 }}
- animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 2, ease: "easeInOut" }}
- src="/carbon-logo-light.png"
- alt="Carbon Logo"
- className="hidden dark:block max-w-[60px] mb-3"
- />
- <Heading
- {...fade}
- transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}
- size="h1"
- className="m-0"
- >
- Welcome to CarbonOS
- </Heading>
- <motion.p
- {...fade}
- transition={{ duration: 1.4, ease: "easeInOut", delay: 1.9 }}
- className="text-muted-foreground text-sm pb-4"
- >
- CarbonOS is the operating system for manufacturing
- </motion.p>
-
- <Button
- {...fade}
- transition={{ duration: 1, delay: 2.4 }}
- size="lg"
- onClick={() => {
- window.location.href = getConfirmationURL(token);
- }}
- >
- Accept Invite
- </Button>
- </VStack>
- </AnimatePresence>
- );
-}
diff --git a/apps/carbon/app/routes/_public+/forgot-password.tsx b/apps/carbon/app/routes/_public+/forgot-password.tsx
index e1a1d72123..52c950caff 100644
--- a/apps/carbon/app/routes/_public+/forgot-password.tsx
+++ b/apps/carbon/app/routes/_public+/forgot-password.tsx
@@ -56,16 +56,17 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
const { email } = validation.data;
const user = await getUserByEmail(email);
-
+ console.log({ user });
if (user.data && user.data.active) {
const companies = await getCompaniesForUser(
getCarbonServiceRole(),
user.data.id
);
+
if (companies.length > 0) {
- const authSession = await sendMagicLink(email);
- if (!authSession) {
- return json(error(authSession, "Failed to send magic link"), {
+ const magicLink = await sendMagicLink(email);
+ if (!magicLink) {
+ return json(error(magicLink, "Failed to send magic link"), {
status: 500,
});
}
@@ -74,7 +75,7 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
console.error(`No user found for email: ${email}`);
}
- return json(success("Success"));
+ return json(success());
}
export default function ForgotPasswordRoute() {
diff --git a/apps/carbon/app/routes/_public+/invite.$code.tsx b/apps/carbon/app/routes/_public+/invite.$code.tsx
new file mode 100644
index 0000000000..09035a67a4
--- /dev/null
+++ b/apps/carbon/app/routes/_public+/invite.$code.tsx
@@ -0,0 +1,169 @@
+import {
+ error,
+ getAppUrl,
+ getCarbonServiceRole,
+ getPermissionCacheKey,
+} from "@carbon/auth";
+import { flash, getAuthSession } from "@carbon/auth/session.server";
+import { redis } from "@carbon/kv";
+import { Button as _Button, Heading as _Heading, VStack } from "@carbon/react";
+import { Form, Link, redirect, useLoaderData } from "@remix-run/react";
+import type {
+ ActionFunctionArgs,
+ LoaderFunctionArgs,
+ MetaFunction,
+} from "@vercel/remix";
+import { AnimatePresence, motion } from "framer-motion";
+import { acceptInvite } from "~/modules/users/users.server";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Accept Invite | CarbonOS" }];
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { code } = params;
+ if (!code) throw new Error("No code provided");
+
+ const serviceRole = getCarbonServiceRole();
+ const invite = await serviceRole
+ .from("invite")
+ .select("*, company(name)")
+ .eq("code", code)
+ .single();
+
+ if (!invite.data || invite.data.acceptedAt) {
+ return { success: false, company: null };
+ }
+
+ return { success: true, company: invite.data.company };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { code } = params;
+ if (!code) throw new Error("No code provided");
+ const authSession = await getAuthSession(request);
+
+ const serviceRole = getCarbonServiceRole();
+
+ const accept = await acceptInvite(serviceRole, code, authSession?.email);
+ if (accept.error) {
+ throw redirect(
+ path.to.root,
+ await flash(
+ request,
+ error(accept.error, accept.error.message ?? "Failed to accept invite")
+ )
+ );
+ }
+
+ if (authSession) {
+ await redis.del(getPermissionCacheKey(authSession.userId));
+ throw redirect(path.to.authenticatedRoot);
+ } else {
+ const magicLink = await serviceRole.auth.admin.generateLink({
+ type: "magiclink",
+ email: accept.data.email,
+ options: {
+ redirectTo: `${getAppUrl()}/callback`,
+ },
+ });
+ throw redirect(magicLink.data?.properties?.action_link ?? path.to.root);
+ }
+}
+
+const fade = {
+ initial: { opacity: 0 },
+ animate: { opacity: 1 },
+};
+
+const Heading = motion(_Heading);
+const Button = motion(_Button);
+
+export default function Invite() {
+ const { success, company } = useLoaderData<typeof loader>();
+
+ if (!success) {
+ return (
+ <VStack
+ spacing={4}
+ className="max-w-lg pt-[16dvh] items-center text-center"
+ >
+ <div>
+ <img
+ src="/carbon-logo-dark.png"
+ alt="Carbon Logo"
+ className="block dark:hidden max-w-[100px] mb-3"
+ />
+ <img
+ src="/carbon-logo-light.png"
+ alt="Carbon Logo"
+ className="hidden dark:block max-w-[100px] mb-3"
+ />
+ </div>
+ <VStack spacing={2} className="text-center w-full">
+ <Heading className="w-full text-center">Invalid Invite</Heading>
+ <p>
+ Your invitation is invalid or has already been accepted. Please
+ contact support if you believe this is an error.
+ </p>
+ </VStack>
+ <Button asChild>
+ <Link to="/">Return Home</Link>
+ </Button>
+ </VStack>
+ );
+ }
+
+ return (
+ <AnimatePresence>
+ <VStack
+ spacing={4}
+ className="max-w-lg pt-[16dvh] items-center text-center"
+ >
+ <motion.img
+ initial={{ opacity: 0, scale: 0.4 }}
+ animate={{ opacity: 1, scale: 1 }}
+ transition={{ duration: 1, ease: "easeInOut" }}
+ src="/carbon-logo-dark.png"
+ alt="Carbon Logo"
+ className="block dark:hidden max-w-[60px] mb-3"
+ />
+ <motion.img
+ initial={{ opacity: 0, scale: 0.4 }}
+ animate={{ opacity: 1, scale: 1 }}
+ transition={{ duration: 1, ease: "easeInOut" }}
+ src="/carbon-logo-light.png"
+ alt="Carbon Logo"
+ className="hidden dark:block max-w-[60px] mb-3"
+ />
+ <Heading
+ {...fade}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 0.5 }}
+ size="h1"
+ className="m-0"
+ >
+ Welcome to CarbonOS
+ </Heading>
+ <motion.p
+ {...fade}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 0.9 }}
+ className="text-muted-foreground text-sm pb-4"
+ >
+ CarbonOS is the operating system for manufacturing
+ </motion.p>
+
+ <Form method="post">
+ <Button
+ {...fade}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 1.4 }}
+ size="lg"
+ type="submit"
+ >
+ {`Join ${company?.name ?? "Company"}`}
+ </Button>
+ </Form>
+ </VStack>
+ </AnimatePresence>
+ );
+}
diff --git a/apps/carbon/app/routes/_public+/confirm-magic-link.tsx b/apps/carbon/app/routes/_public+/magic-link.tsx
similarity index 83%
rename from apps/carbon/app/routes/_public+/confirm-magic-link.tsx
rename to apps/carbon/app/routes/_public+/magic-link.tsx
index 154aa94cd4..94a09dc932 100644
--- a/apps/carbon/app/routes/_public+/confirm-magic-link.tsx
+++ b/apps/carbon/app/routes/_public+/magic-link.tsx
@@ -29,12 +29,12 @@ export default function ConfirmMagicLink() {
<AnimatePresence>
<VStack
spacing={4}
- className="max-w-lg pt-[20dvh] items-center text-center"
+ className="max-w-lg pt-[16dvh] items-center text-center"
>
<motion.img
initial={{ opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 2, ease: "easeInOut" }}
+ transition={{ duration: 1, ease: "easeInOut" }}
src="/carbon-logo-dark.png"
alt="Carbon Logo"
className="block dark:hidden max-w-[60px] mb-3"
@@ -42,14 +42,14 @@ export default function ConfirmMagicLink() {
<motion.img
initial={{ opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 2, ease: "easeInOut" }}
+ transition={{ duration: 1, ease: "easeInOut" }}
src="/carbon-logo-light.png"
alt="Carbon Logo"
className="hidden dark:block max-w-[60px] mb-3"
/>
<Heading
{...fade}
- transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 0.5 }}
size="h1"
className="m-0"
>
@@ -57,7 +57,7 @@ export default function ConfirmMagicLink() {
</Heading>
<motion.p
{...fade}
- transition={{ duration: 1.4, ease: "easeInOut", delay: 1.9 }}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 0.9 }}
className="text-muted-foreground text-sm pb-4"
>
CarbonOS is the operating system for manufacturing
@@ -65,7 +65,7 @@ export default function ConfirmMagicLink() {
<Button
{...fade}
- transition={{ duration: 1, delay: 2.4 }}
+ transition={{ duration: 0.8, ease: "easeInOut", delay: 1.4 }}
size="lg"
onClick={() => {
window.location.href = getConfirmationURL(token);
diff --git a/apps/carbon/app/routes/x+/api+/_layout.tsx b/apps/carbon/app/routes/x+/api+/_layout.tsx
index b5e98c4b3d..82b513a6da 100644
--- a/apps/carbon/app/routes/x+/api+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/api+/_layout.tsx
@@ -88,6 +88,7 @@ export default function ApiDocsRoute() {
const tableBlacklist = new Set([
"apiKey",
"documentTransaction",
+ "invite",
"oauthClient",
"oauthCode",
"oauthToken",
diff --git a/apps/carbon/app/routes/x+/users+/employees.new.tsx b/apps/carbon/app/routes/x+/users+/employees.new.tsx
index aba9f6ebcf..2c6dbc399d 100644
--- a/apps/carbon/app/routes/x+/users+/employees.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/employees.new.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost, error, success } from "@carbon/auth";
+import { assertIsPost, error, getAppUrl, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { InviteEmail } from "@carbon/documents/email";
@@ -94,7 +94,7 @@ export async function action({ request }: ActionFunctionArgs) {
invitedByName: user.data.fullName ?? "",
email,
companyName: company.data.name,
- inviteCode: result.code,
+ inviteLink: `${getAppUrl()}/invite/${result.code}`,
ip,
location,
})
diff --git a/apps/carbon/app/trigger/user-admin.ts b/apps/carbon/app/trigger/user-admin.ts
index ba6a6647da..2e07ab9759 100644
--- a/apps/carbon/app/trigger/user-admin.ts
+++ b/apps/carbon/app/trigger/user-admin.ts
@@ -2,13 +2,13 @@ import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
import { getCarbonServiceRole } from "@carbon/auth";
-import { deactivateUser, resendInvite } from "~/modules/users/users.server";
+import { deactivateUser } from "~/modules/users/users.server";
import type { Result } from "~/types";
const serviceRole = getCarbonServiceRole();
export const userAdminSchema = z.object({
id: z.string(),
- type: z.enum(["resend", "deactivate"]),
+ type: z.enum(["deactivate"]),
companyId: z.string(),
});
@@ -20,10 +20,6 @@ export const userAdminTask = task({
let result: Result;
switch (payload.type) {
- case "resend":
- console.log(`📫 Resending invite for ${payload.id}`);
- result = await resendInvite(serviceRole, payload.id);
- break;
case "deactivate":
console.log(`🚭 Deactivating ${payload.id}`);
result = await deactivateUser(
diff --git a/apps/developers/app/routes/_public+/forgot-password.tsx b/apps/developers/app/routes/_public+/forgot-password.tsx
index bfa7d4abc5..3efe5e6b50 100644
--- a/apps/developers/app/routes/_public+/forgot-password.tsx
+++ b/apps/developers/app/routes/_public+/forgot-password.tsx
@@ -1,35 +1,5 @@
-import type { Result } from "@carbon/auth";
-import {
- assertIsPost,
- error,
- forgotPasswordValidator,
- success,
-} from "@carbon/auth";
-import { sendMagicLink } from "@carbon/auth/auth.server";
-import { getAuthSession } from "@carbon/auth/session.server";
-import { getUserByEmail } from "@carbon/auth/users.server";
-import {
- Input,
- Submit,
- ValidatedForm,
- validationError,
- validator,
-} from "@carbon/form";
-import {
- Alert,
- AlertDescription,
- AlertTitle,
- Button,
- VStack,
-} from "@carbon/react";
-import { Link, useActionData } from "@remix-run/react";
-import type {
- ActionFunctionArgs,
- LoaderFunctionArgs,
- MetaFunction,
-} from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
-import { LuAlertCircle, LuCheckCircle } from "react-icons/lu";
+import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
import { path } from "~/utils/path";
@@ -42,94 +12,5 @@ export const meta: MetaFunction = () => {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const authSession = await getAuthSession(request);
- if (authSession) throw redirect(path.to.authenticatedRoot);
- return null;
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const validation = await validator(forgotPasswordValidator).validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { email } = validation.data;
- const user = await getUserByEmail(email);
-
- if (user.data && user.data.active) {
- const authSession = await sendMagicLink(email);
-
- if (!authSession) {
- return json(error(authSession, "Failed to send magic link"), {
- status: 500,
- });
- }
- }
-
- return json(success("Success"));
-}
-
-export default function ForgotPasswordRoute() {
- const actionData = useActionData<Result>();
-
- return (
- <>
- <div className="flex flex-col items-center justify-center">
- <img
- src="/carbon-logo-dark.png"
- alt="Carbon Logo"
- className="block dark:hidden max-w-[100px] mb-3"
- />
- <img
- src="/carbon-logo-light.png"
- alt="Carbon Logo"
- className="hidden dark:block max-w-[100px] mb-3"
- />
- <h3 className="font-mono font-bold leading-loose uppercase text-xl">
- Developers
- </h3>
- </div>
- {actionData?.success ? (
- <Alert
- variant="success"
- className="h-[240px] [&>svg]:left-8 [&>svg]:top-8 p-8"
- >
- <LuCheckCircle className="w-4 h-4" />
- <AlertTitle>Success</AlertTitle>
- <AlertDescription>
- If you have an account, you should receive an email shortly with a
- link to log in.
- </AlertDescription>
- </Alert>
- ) : (
- <div className="rounded-lg bg-card border border-border shadow-lg p-8 w-[380px]">
- <ValidatedForm validator={forgotPasswordValidator} method="post">
- <VStack spacing={4}>
- <p className="w-full px-8 text-center text-sm text-muted-foreground">
- {" "}
- Please enter your email address to search for your account.{" "}
- </p>
- {actionData?.success === false && (
- <Alert variant="destructive">
- <LuAlertCircle className="w-4 h-4" />
- <AlertTitle>{actionData?.message}</AlertTitle>
- </Alert>
- )}
- <Input name="email" label="Email" />
- <Submit size="lg" className="w-full" withBlocker={false}>
- Reset Password
- </Submit>
- <Button variant="link" asChild className="w-full">
- <Link to={path.to.login}>Back to login</Link>
- </Button>
- </VStack>
- </ValidatedForm>
- </div>
- )}
- </>
- );
+ throw redirect(path.to.forgotPassword);
}
diff --git a/apps/developers/app/utils/path.ts b/apps/developers/app/utils/path.ts
index 8b37f13655..dc5206b0f7 100644
--- a/apps/developers/app/utils/path.ts
+++ b/apps/developers/app/utils/path.ts
@@ -13,7 +13,7 @@ export const path = {
companySwitch: (companyId: string) =>
generatePath(`${x}/company/switch/${companyId}`),
dashboard: `${ERP_URL}/x`,
- forgotPassword: "/forgot-password",
+ forgotPassword: `${ERP_URL}/forgot-password`,
healthcheck: "/healthcheck",
login: "/login",
logout: "/logout",
diff --git a/apps/mes/app/routes/_public+/forgot-password.tsx b/apps/mes/app/routes/_public+/forgot-password.tsx
index 2f8748b9c0..f40912251f 100644
--- a/apps/mes/app/routes/_public+/forgot-password.tsx
+++ b/apps/mes/app/routes/_public+/forgot-password.tsx
@@ -1,35 +1,5 @@
-import type { Result } from "@carbon/auth";
-import {
- assertIsPost,
- error,
- forgotPasswordValidator,
- success,
-} from "@carbon/auth";
-import { sendMagicLink } from "@carbon/auth/auth.server";
-import { getAuthSession } from "@carbon/auth/session.server";
-import { getUserByEmail } from "@carbon/auth/users.server";
-import {
- Input,
- Submit,
- ValidatedForm,
- validationError,
- validator,
-} from "@carbon/form";
-import {
- Alert,
- AlertDescription,
- AlertTitle,
- Button,
- VStack,
-} from "@carbon/react";
-import { Link, useActionData } from "@remix-run/react";
-import type {
- ActionFunctionArgs,
- LoaderFunctionArgs,
- MetaFunction,
-} from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
-import { LuAlertCircle, LuCheckCircle } from "react-icons/lu";
+import type { LoaderFunctionArgs, MetaFunction } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
import { path } from "~/utils/path";
@@ -42,86 +12,5 @@ export const meta: MetaFunction = () => {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const authSession = await getAuthSession(request);
- if (authSession) throw redirect(path.to.authenticatedRoot);
- return null;
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const validation = await validator(forgotPasswordValidator).validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { email } = validation.data;
- const user = await getUserByEmail(email);
-
- if (user.data && user.data.active) {
- const authSession = await sendMagicLink(email);
-
- if (!authSession) {
- return json(error(authSession, "Failed to send magic link"), {
- status: 500,
- });
- }
- }
-
- return json(success("Success"));
-}
-
-export default function ForgotPasswordRoute() {
- const actionData = useActionData<Result>();
-
- return (
- <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
- <div className="flex space-y-2 justify-center">
- <img
- src="/carbon-logo-dark.png"
- alt="Carbon Logo"
- className="block dark:hidden max-w-[100px] mb-3"
- />
- <img
- src="/carbon-logo-light.png"
- alt="Carbon Logo"
- className="hidden dark:block max-w-[100px] mb-3"
- />
- </div>
-
- {actionData?.success ? (
- <Alert variant="success" className="[&>svg]:left-8 [&>svg]:top-8 p-8">
- <LuCheckCircle className="w-4 h-4" />
- <AlertTitle>Success</AlertTitle>
- <AlertDescription>
- If you have an account, you should receive an email shortly with a
- link to log in.
- </AlertDescription>
- </Alert>
- ) : (
- <ValidatedForm validator={forgotPasswordValidator} method="post">
- <VStack spacing={4}>
- <p className="w-full px-8 text-center text-sm text-muted-foreground">
- Please enter your email address to search for your account.
- </p>
- {actionData?.success === false && (
- <Alert variant="destructive">
- <LuAlertCircle className="w-4 h-4" />
- <AlertTitle>{actionData?.message}</AlertTitle>
- </Alert>
- )}
- <Input name="email" label="Email" />
- <Submit size="lg" className="w-full" withBlocker={false}>
- Reset Password
- </Submit>
- <Button variant="link" asChild className="w-full">
- <Link to={path.to.login}>Back to login</Link>
- </Button>
- </VStack>
- </ValidatedForm>
- )}
- </div>
- );
+ throw redirect(path.to.forgotPassword);
}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index dbd91af46b..563c579f73 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -25,7 +25,7 @@ export const path = {
endShift: `${x}/end-shift`,
feedback: `${x}/feedback`,
finish: `${x}/finish`,
- forgotPassword: "/forgot-password",
+ forgotPassword: `${ERP_URL}/forgot-password`,
healthcheck: "/healthcheck",
issue: `${x}/issue`,
operation: (id: string) => generatePath(`${x}/operation/${id}`),
diff --git a/packages/auth/src/services/users.server.ts b/packages/auth/src/services/users.server.ts
index 8ac8f8adeb..5851fbce6b 100644
--- a/packages/auth/src/services/users.server.ts
+++ b/packages/auth/src/services/users.server.ts
@@ -13,7 +13,7 @@ export async function getUserByEmail(email: string) {
.from("user")
.select("*")
.eq("email", email.toLowerCase())
- .maybeSingle();
+ .single();
}
export async function getUserClaims(userId: string, companyId: string) {
diff --git a/packages/database/supabase/migrations/20241208004151_invites.sql b/packages/database/supabase/migrations/20241208004151_invites.sql
index 75c4b62199..2a59f8cd13 100644
--- a/packages/database/supabase/migrations/20241208004151_invites.sql
+++ b/packages/database/supabase/migrations/20241208004151_invites.sql
@@ -12,7 +12,8 @@ CREATE TABLE "invite" (
CONSTRAINT "invite_pkey" PRIMARY KEY ("id"),
CONSTRAINT "invite_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id"),
- CONSTRAINT "invite_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+ CONSTRAINT "invite_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "invite_email_companyId_key" UNIQUE ("email", "companyId")
);
CREATE INDEX "invite_unaccepted_code_idx" ON "invite" ("code") WHERE "acceptedAt" IS NULL;
diff --git a/packages/database/supabase/templates/magic-link.html b/packages/database/supabase/templates/magic-link.html
index d0526547ad..c0adbd69c7 100644
--- a/packages/database/supabase/templates/magic-link.html
+++ b/packages/database/supabase/templates/magic-link.html
@@ -3,5 +3,5 @@
<p>Follow this link to login:</p>
<p>
- <a href="{{ .SiteURL }}/confirm-magic-link?token={{ .TokenHash }}">Log In</a>
+ <a href="{{ .SiteURL }}/magic-link?token={{ .TokenHash }}">Log In</a>
</p>
diff --git a/packages/documents/src/email/InviteEmail.tsx b/packages/documents/src/email/InviteEmail.tsx
index b961a5329b..3fd69a1c37 100644
--- a/packages/documents/src/email/InviteEmail.tsx
+++ b/packages/documents/src/email/InviteEmail.tsx
@@ -1,4 +1,3 @@
-import { getAppUrl } from "@carbon/auth";
import {
Body,
Button,
@@ -19,24 +18,20 @@ interface Props {
invitedByEmail?: string;
invitedByName?: string;
companyName?: string;
- inviteCode?: string;
+ inviteLink?: string;
ip?: string;
location?: string;
}
-const baseAppUrl = getAppUrl();
-
export const InviteEmail = ({
invitedByEmail = "[email protected]",
invitedByName = "Tom Sawyer",
email = "[email protected]",
companyName = "Tombstone",
- inviteCode = "1234567890",
+ inviteLink = "https://carbonos.dev/invite/1234567890",
ip = "38.38.38.38",
location = "Tombstone, AZ",
}: Props) => {
- const inviteLink = `${baseAppUrl}/invite/${inviteCode}`;
-
return (
<Html>
<Tailwind>