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.

fix: recover from orphaned auth user on re-creation after partial delete (#1345)

Anshul sharmaafd756745413
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index 56c217eccd..2344ae9c1a 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -268,19 +268,21 @@ export async function createCustomerAccount(
if (user.data) {
userId = user.data.id;
+ if (!(await authIdentityExists(userId))) {
+ return {
+ success: false,
+ message:
+ "This user's auth account no longer exists. Contact support before re-adding."
+ };
+ }
} else {
isNewUser = true;
- const createSupabaseUser = await serviceRole.auth.admin.createUser({
- email: email.toLowerCase(),
- password: crypto.randomUUID(),
- email_confirm: true
- });
-
- if (createSupabaseUser.error) {
- return { success: false, message: createSupabaseUser.error.message };
+ const resolvedId = await resolveAuthUserId(email);
+ if (!resolvedId) {
+ return { success: false, message: "Failed to create auth account" };
}
+ userId = resolvedId;
- userId = createSupabaseUser.data.user.id;
const createCarbonUser = await createUser(serviceRole, {
id: userId,
email: email.toLowerCase(),
@@ -383,6 +385,13 @@ export async function createEmployeeAccount(
if (user.data) {
userId = user.data.id;
+ if (!(await authIdentityExists(userId))) {
+ return {
+ success: false,
+ message:
+ "This user's auth account no longer exists. Contact support before re-adding."
+ };
+ }
const existingEmployee = await client
.from("employee")
@@ -399,17 +408,12 @@ export async function createEmployeeAccount(
}
} else {
isNewUser = true;
- const createSupabaseUser = await serviceRole.auth.admin.createUser({
- email: email.toLowerCase(),
- password: crypto.randomUUID(),
- email_confirm: true
- });
-
- if (createSupabaseUser.error) {
- return { success: false, message: createSupabaseUser.error.message };
+ const resolvedId = await resolveAuthUserId(email);
+ if (!resolvedId) {
+ return { success: false, message: "Failed to create auth account" };
}
+ userId = resolvedId;
- userId = createSupabaseUser.data.user.id;
const createCarbonUser = await createUser(serviceRole, {
id: userId,
email: email.toLowerCase(),
@@ -512,19 +516,21 @@ export async function createSupplierAccount(
if (user.data) {
userId = user.data.id;
+ if (!(await authIdentityExists(userId))) {
+ return {
+ success: false,
+ message:
+ "This user's auth account no longer exists. Contact support before re-adding."
+ };
+ }
} else {
isNewUser = true;
- const createSupabaseUser = await serviceRole.auth.admin.createUser({
- email: email.toLowerCase(),
- password: crypto.randomUUID(),
- email_confirm: true
- });
-
- if (createSupabaseUser.error) {
- return { success: false, message: createSupabaseUser.error.message };
+ const resolvedId = await resolveAuthUserId(email);
+ if (!resolvedId) {
+ return { success: false, message: "Failed to create auth account" };
}
+ userId = resolvedId;
- userId = createSupabaseUser.data.user.id;
const createCarbonUser = await createUser(serviceRole, {
id: userId,
email: email.toLowerCase(),
@@ -647,6 +653,43 @@ export async function getUserByEmail(email: string) {
.single();
}
+// Returns false if the auth identity for this userId has been deleted, leaving only an app-side row.
+async function authIdentityExists(userId: string): Promise<boolean> {
+ const { error } = await getCarbonServiceRole().auth.admin.getUserById(userId);
+ return !error;
+}
+
+// Creates the auth user for email, or recovers the existing ID if a prior deletion left one behind.
+async function resolveAuthUserId(email: string): Promise<string | null> {
+ const serviceRole = getCarbonServiceRole();
+ const result = await serviceRole.auth.admin.createUser({
+ email: email.toLowerCase(),
+ password: crypto.randomUUID(),
+ email_confirm: true
+ });
+
+ if (!result.error) return result.data.user.id;
+
+ // Only recover for "already registered"; other errors (network, rate limit) surface as-is.
+ if (result.error.code !== "user_already_exists") return null;
+
+ // auth record exists but app user row doesn't; find the orphaned ID.
+ const target = email.toLowerCase();
+ let page = 1;
+ const perPage = 1000;
+ while (true) {
+ const { data, error } = await serviceRole.auth.admin.listUsers({
+ page,
+ perPage
+ });
+ if (error || !data?.users?.length) return null;
+ const match = data.users.find((u) => u.email?.toLowerCase() === target);
+ if (match) return match.id;
+ if (data.users.length < perPage) return null;
+ page++;
+ }
+}
+
export async function getUserGroups(
client: SupabaseClient<Database>,
userId: string
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index d9f843efdd..c94cd7c411 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -64,12 +64,22 @@ export async function deleteAuthAccount(
client: SupabaseClient<Database>,
userId: string
) {
- const [supabaseDelete, carbonDelete] = await Promise.all([
- client.auth.admin.deleteUser(userId),
- client.from("user").delete().eq("id", userId)
- ]);
-
- if (supabaseDelete.error || carbonDelete.error) return null;
+ // Sequential: a failed auth delete leaves both records intact and retryable.
+ const supabaseDelete = await client.auth.admin.deleteUser(userId);
+ if (supabaseDelete.error) return null;
+
+ const carbonDelete = await client.from("user").delete().eq("id", userId);
+ if (carbonDelete.error) {
+ // Auth user is gone but the app row remains; log so it can be found and cleaned up.
+ log.error(
+ "deleteAuthAccount: user table cleanup failed after auth delete",
+ {
+ userId,
+ error: carbonDelete.error
+ }
+ );
+ return null;
+ }
return true;
}