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: password login

Brad Barbind2e094c02c70
diff --git a/.env.example b/.env.example
index 89c25568a5..fd789c5480 100644
--- a/.env.example
+++ b/.env.example
@@ -1,4 +1,4 @@
-AUTH_PROVIDERS="email,google,azure"
+AUTH_PROVIDERS="email,google" # "email" | "google" | "azure" | "password"
CARBON_EDITION="community" # "community" | "cloud" | "enterprise"
CLOUDFLARE_TURNSTILE_SITE_KEY="1x00000000000000000000AA"
diff --git a/apps/academy/app/root.tsx b/apps/academy/app/root.tsx
index 72d9bfaaf9..d40765e972 100644
--- a/apps/academy/app/root.tsx
+++ b/apps/academy/app/root.tsx
@@ -195,7 +195,7 @@ export default function App() {
const env = loaderData?.env ?? {};
const result = loaderData?.result;
const prefs = loaderData?.preferences;
- const theme = "blue";
+ const theme = "zinc";
const challengeAttempts = loaderData?.challengeAttempts ?? [];
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 8999aa6efb..e4ec3d3198 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -127,7 +127,7 @@ export function Document({
children,
title = "Carbon",
mode = "light",
- theme = "blue"
+ theme = "zinc"
}: {
children: React.ReactNode;
title?: string;
@@ -191,7 +191,7 @@ export default function App() {
const loaderData = useLoaderData<typeof loader>();
const env = loaderData?.env ?? {};
const result = loaderData?.result;
- const theme = loaderData?.theme ?? "blue";
+ const theme = loaderData?.theme ?? "zinc";
const prefs = loaderData?.preferences;
const mode = useMode();
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index 92e0570a75..d25c943e81 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -8,13 +8,30 @@ import {
carbonClient,
error,
magicLinkValidator,
+ passwordLoginValidator,
RATE_LIMIT
} from "@carbon/auth";
-import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
-import { flash, getAuthSession } from "@carbon/auth/session.server";
+import {
+ sendMagicLink,
+ signInWithEmail,
+ verifyAuthSession
+} from "@carbon/auth/auth.server";
+import { setCompanyId } from "@carbon/auth/company.server";
+import {
+ flash,
+ getAuthSession,
+ setAuthSession
+} from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { sendVerificationCode } from "@carbon/auth/verification.server";
-import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
+import {
+ Hidden,
+ Input,
+ Password,
+ Submit,
+ ValidatedForm,
+ validator
+} from "@carbon/form";
import { redis } from "@carbon/kv";
import {
Alert,
@@ -81,6 +98,72 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ const providers = AUTH_PROVIDERS.split(",");
+ const isPasswordAuth = providers.includes("password");
+
+ if (isPasswordAuth) {
+ const validation = await validator(passwordLoginValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return error(validation.error, "Invalid login");
+ }
+
+ const { email, password, turnstileToken } = validation.data;
+
+ if (
+ CarbonEdition === Edition.Cloud &&
+ CLOUDFLARE_TURNSTILE_SITE_KEY !== "1x00000000000000000000AA"
+ ) {
+ const verifyResponse = await fetch(
+ "https://challenges.cloudflare.com/turnstile/v0/siteverify",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ body: new URLSearchParams({
+ secret: CLOUDFLARE_TURNSTILE_SECRET_KEY ?? "",
+ response: turnstileToken ?? "",
+ remoteip: ip
+ })
+ }
+ );
+
+ const verifyData = await verifyResponse.json();
+ if (!verifyData.success) {
+ return data(
+ error(null, "Bot verification failed. Please try again."),
+ await flash(
+ request,
+ error(null, "Bot verification failed. Please try again.")
+ )
+ );
+ }
+ }
+
+ const authSession = await signInWithEmail(email, password);
+
+ if (!authSession) {
+ return data(
+ { success: false, message: "Invalid email/password combination" },
+ await flash(request, error(null, "Invalid email/password combination"))
+ );
+ }
+
+ const redirectTo = validation.data.redirectTo;
+ const sessionCookie = await setAuthSession(request, { authSession });
+ const companyIdCookie = setCompanyId(authSession.companyId);
+
+ return redirect(redirectTo || path.to.authenticatedRoot, {
+ headers: [
+ ["Set-Cookie", sessionCookie],
+ ["Set-Cookie", companyIdCookie]
+ ]
+ });
+ }
+
const validation = await validator(magicLinkValidator).validate(
await request.formData()
);
@@ -158,6 +241,7 @@ export default function LoginRoute() {
const { providers } = useLoaderData<typeof loader>();
const hasOutlookAuth = providers.includes("azure");
const hasGoogleAuth = providers.includes("google");
+ const hasPasswordAuth = providers.includes("password");
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get("redirectTo") ?? undefined;
@@ -227,7 +311,9 @@ export default function LoginRoute() {
/>
</div>
<div className="rounded-lg md:bg-card md:border md:border-border md:shadow-lg p-8 w-[380px]">
- {fetcher.data?.success === true && fetcher.data?.mode === "login" ? (
+ {!hasPasswordAuth &&
+ fetcher.data?.success === true &&
+ fetcher.data?.mode === "login" ? (
<>
<VStack spacing={4} className="items-center justify-center">
<Heading size="h3">Check your email</Heading>
@@ -236,7 +322,7 @@ export default function LoginRoute() {
</p>
</VStack>
</>
- ) : mode === "verify" ? (
+ ) : !hasPasswordAuth && mode === "verify" ? (
<VStack spacing={4} className="items-center">
<Heading size="h3">Verify your email</Heading>
<p className="text-muted-foreground tracking-tight text-sm text-center">
@@ -259,6 +345,82 @@ export default function LoginRoute() {
Use a different email
</Button>
</VStack>
+ ) : hasPasswordAuth ? (
+ <ValidatedForm
+ fetcher={fetcher}
+ validator={passwordLoginValidator}
+ defaultValues={{ redirectTo }}
+ method="post"
+ action="/login"
+ >
+ <Hidden name="redirectTo" value={redirectTo} type="hidden" />
+ <Hidden name="turnstileToken" value={turnstileToken} />
+ <VStack spacing={2}>
+ {fetcher.data?.success === false && fetcher.data?.message && (
+ <Alert variant="destructive">
+ <LuCircleAlert className="w-4 h-4" />
+ <AlertTitle>Authentication Error</AlertTitle>
+ <AlertDescription>{fetcher.data?.message}</AlertDescription>
+ </Alert>
+ )}
+
+ <Input name="email" label="" placeholder="Email Address" />
+ <Password name="password" label="" placeholder="Password" />
+
+ <Submit
+ isDisabled={
+ fetcher.state !== "idle" ||
+ (!!CLOUDFLARE_TURNSTILE_SITE_KEY && !turnstileToken)
+ }
+ isLoading={fetcher.state === "submitting"}
+ size="lg"
+ className="w-full"
+ withBlocker={false}
+ >
+ Sign In
+ </Submit>
+ {!!CLOUDFLARE_TURNSTILE_SITE_KEY && (
+ <div className="w-full flex justify-center">
+ <Turnstile
+ siteKey={CLOUDFLARE_TURNSTILE_SITE_KEY}
+ onSuccess={(token) => setTurnstileToken(token)}
+ onError={() => setTurnstileToken("")}
+ onExpire={() => setTurnstileToken("")}
+ options={{
+ theme: theme === "dark" ? "dark" : "light"
+ }}
+ />
+ </div>
+ )}
+
+ {hasGoogleAuth && (
+ <Button
+ type="button"
+ size="lg"
+ className="w-full"
+ onClick={onSignInWithGoogle}
+ isDisabled={fetcher.state !== "idle"}
+ variant="secondary"
+ leftIcon={<GoogleIcon />}
+ >
+ Sign in with Google
+ </Button>
+ )}
+ {hasOutlookAuth && (
+ <Button
+ type="button"
+ size="lg"
+ className="w-full"
+ onClick={onSignInWithAzure}
+ isDisabled={fetcher.state !== "idle"}
+ variant="secondary"
+ leftIcon={<OutlookIcon className="size-6" />}
+ >
+ Sign in with Outlook
+ </Button>
+ )}
+ </VStack>
+ </ValidatedForm>
) : (
<ValidatedForm
fetcher={fetcher}
@@ -338,7 +500,8 @@ export default function LoginRoute() {
</div>
<div className="flex flex-col gap-4 text-sm text-center text-balance text-muted-foreground w-[380px]">
- {mode !== "verify" &&
+ {!hasPasswordAuth &&
+ mode !== "verify" &&
fetcher.data?.success !== true &&
CarbonEdition !== Edition.Enterprise && (
<p>Login or create a new account</p>
diff --git a/apps/erp/app/services/theme.server.ts b/apps/erp/app/services/theme.server.ts
index a7d281c038..ea662d4c73 100644
--- a/apps/erp/app/services/theme.server.ts
+++ b/apps/erp/app/services/theme.server.ts
@@ -16,9 +16,9 @@ type Theme = (typeof themes)[number];
export function getTheme(request: Request): Theme {
const cookieHeader = request.headers.get("cookie");
- const parsed = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : "blue";
+ const parsed = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : "zinc";
if (themes.includes(parsed as Theme)) return parsed as Theme;
- return "blue";
+ return "zinc";
}
export function setTheme(theme: string) {
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index e847337490..d8ec7822b3 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -113,7 +113,7 @@ function Document({
children,
title = "Carbon",
mode = "light",
- theme = "blue"
+ theme = "zinc"
}: {
children: React.ReactNode;
title?: string;
@@ -180,7 +180,7 @@ export default function App() {
const loaderData = useLoaderData<typeof loader>();
const env = loaderData?.env ?? {};
const result = loaderData?.result;
- const theme = loaderData?.theme ?? "blue";
+ const theme = loaderData?.theme ?? "zinc";
const prefs = loaderData?.preferences;
/* Toast Messages */
diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsx
index 4d32404d8c..5e9b7af84f 100644
--- a/apps/mes/app/routes/_public+/login.tsx
+++ b/apps/mes/app/routes/_public+/login.tsx
@@ -6,12 +6,29 @@ import {
carbonClient,
error,
magicLinkValidator,
+ passwordLoginValidator,
RATE_LIMIT
} from "@carbon/auth";
-import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
-import { flash, getAuthSession } from "@carbon/auth/session.server";
+import {
+ sendMagicLink,
+ signInWithEmail,
+ verifyAuthSession
+} from "@carbon/auth/auth.server";
+import { setCompanyId } from "@carbon/auth/company.server";
+import {
+ flash,
+ getAuthSession,
+ setAuthSession
+} from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
-import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
+import {
+ Hidden,
+ Input,
+ Password,
+ Submit,
+ ValidatedForm,
+ validator
+} from "@carbon/form";
import { redis } from "@carbon/kv";
import {
Alert,
@@ -76,6 +93,40 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ const providers = AUTH_PROVIDERS.split(",");
+ const isPasswordAuth = providers.includes("password");
+
+ if (isPasswordAuth) {
+ const validation = await validator(passwordLoginValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return error(validation.error, "Invalid login");
+ }
+
+ const { email, password } = validation.data;
+ const authSession = await signInWithEmail(email, password);
+
+ if (!authSession) {
+ return data(
+ { success: false, message: "Invalid email/password combination" },
+ await flash(request, error(null, "Invalid email/password combination"))
+ );
+ }
+
+ const redirectTo = validation.data.redirectTo;
+ const sessionCookie = await setAuthSession(request, { authSession });
+ const companyIdCookie = setCompanyId(authSession.companyId);
+
+ return redirect(redirectTo || path.to.authenticatedRoot, {
+ headers: [
+ ["Set-Cookie", sessionCookie],
+ ["Set-Cookie", companyIdCookie]
+ ]
+ });
+ }
+
const validation = await validator(magicLinkValidator).validate(
await request.formData()
);
@@ -110,6 +161,7 @@ export default function LoginRoute() {
const { providers } = useLoaderData<typeof loader>();
const hasOutlookAuth = providers.includes("azure");
const hasGoogleAuth = providers.includes("google");
+ const hasPasswordAuth = providers.includes("password");
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get("redirectTo") ?? undefined;
@@ -159,7 +211,7 @@ export default function LoginRoute() {
/>
</div>
<div className="rounded-lg md:bg-card md:border md:border-border md:shadow-lg p-8 w-[380px]">
- {fetcher.data?.success === true ? (
+ {!hasPasswordAuth && fetcher.data?.success === true ? (
<>
<VStack spacing={4} className="items-center justify-center">
<Heading size="h3">Check your email</Heading>
@@ -168,6 +220,64 @@ export default function LoginRoute() {
</p>
</VStack>
</>
+ ) : hasPasswordAuth ? (
+ <ValidatedForm
+ fetcher={fetcher}
+ validator={passwordLoginValidator}
+ defaultValues={{ redirectTo }}
+ method="post"
+ >
+ <Hidden name="redirectTo" value={redirectTo} type="hidden" />
+ <VStack spacing={2}>
+ {fetcher.data?.success === false && fetcher.data?.message && (
+ <Alert variant="destructive">
+ <LuCircleAlert className="w-4 h-4" />
+ <AlertTitle>Authentication Error</AlertTitle>
+ <AlertDescription>{fetcher.data?.message}</AlertDescription>
+ </Alert>
+ )}
+
+ <Input name="email" label="" placeholder="Email Address" />
+ <Password name="password" label="" placeholder="Password" />
+
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state === "submitting"}
+ size="lg"
+ className="w-full"
+ withBlocker={false}
+ >
+ Sign In
+ </Submit>
+
+ {hasGoogleAuth && (
+ <Button
+ type="button"
+ size="lg"
+ className="w-full"
+ onClick={onSignInWithGoogle}
+ isDisabled={fetcher.state !== "idle"}
+ variant="secondary"
+ leftIcon={<GoogleIcon />}
+ >
+ Sign in with Google
+ </Button>
+ )}
+ {hasOutlookAuth && (
+ <Button
+ type="button"
+ size="lg"
+ className="w-full"
+ onClick={onSignInWithAzure}
+ isDisabled={fetcher.state !== "idle"}
+ variant="secondary"
+ leftIcon={<OutlookIcon className="size-6" />}
+ >
+ Sign in with Outlook
+ </Button>
+ )}
+ </VStack>
+ </ValidatedForm>
) : (
<ValidatedForm
fetcher={fetcher}
diff --git a/apps/mes/app/services/theme.server.ts b/apps/mes/app/services/theme.server.ts
index 96b33d84db..28887f48bb 100644
--- a/apps/mes/app/services/theme.server.ts
+++ b/apps/mes/app/services/theme.server.ts
@@ -15,9 +15,9 @@ type Theme = (typeof themes)[number];
export function getTheme(request: Request): Theme {
const cookieHeader = request.headers.get("cookie");
- const parsed = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : "blue";
+ const parsed = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : "zinc";
if (themes.includes(parsed as Theme)) return parsed as Theme;
- return "blue";
+ return "zinc";
}
export function setTheme(theme: string) {
diff --git a/apps/starter/app/root.tsx b/apps/starter/app/root.tsx
index 9bdf918eef..bc0e4dd718 100644
--- a/apps/starter/app/root.tsx
+++ b/apps/starter/app/root.tsx
@@ -99,7 +99,7 @@ function Document({
children,
title = "Carbon",
mode = "light",
- theme = "blue"
+ theme = "zinc"
}: {
children: React.ReactNode;
title?: string;
diff --git a/apps/starter/app/services/theme.server.ts b/apps/starter/app/services/theme.server.ts
index 96b33d84db..28887f48bb 100644
--- a/apps/starter/app/services/theme.server.ts
+++ b/apps/starter/app/services/theme.server.ts
@@ -15,9 +15,9 @@ type Theme = (typeof themes)[number];
export function getTheme(request: Request): Theme {
const cookieHeader = request.headers.get("cookie");
- const parsed = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : "blue";
+ const parsed = cookieHeader ? cookie.parse(cookieHeader)[cookieName] : "zinc";
if (themes.includes(parsed as Theme)) return parsed as Theme;
- return "blue";
+ return "zinc";
}
export function setTheme(theme: string) {
diff --git a/packages/auth/src/validators.ts b/packages/auth/src/validators.ts
index 3d8a1f8525..ccc181cec8 100644
--- a/packages/auth/src/validators.ts
+++ b/packages/auth/src/validators.ts
@@ -33,6 +33,16 @@ export const magicLinkValidator = z.object({
turnstileToken: zfd.text(z.string().optional())
});
+export const passwordLoginValidator = z.object({
+ email: z
+ .string()
+ .min(1, { message: "Email is required" })
+ .email("Must be a valid email"),
+ password: z.string().min(6, { message: "Password is too short" }),
+ redirectTo: zfd.text(z.string().optional()),
+ turnstileToken: zfd.text(z.string().optional())
+});
+
export const resetPasswordValidator = z.object({
password: z.string().min(6, { message: "Password is too short" })
});