fix: reliable fs_users upsert on sign-in
ON CONFLICT expression matching was silently failing due to a mismatch between the query expression and the index definition (::text cast). Replaced with an explicit SELECT-then-INSERT-or-UPDATE pattern. Made-with: Cursor
This commit is contained in:
@@ -28,15 +28,31 @@ export const authOptions: NextAuthOptions = {
|
|||||||
async signIn({ user }) {
|
async signIn({ user }) {
|
||||||
if (!user?.email) return true;
|
if (!user?.email) return true;
|
||||||
try {
|
try {
|
||||||
const workspace = user.email.split("@")[0].toLowerCase().replace(/[^a-z0-9]+/g, "-") + "-account";
|
const workspace =
|
||||||
await query(`
|
user.email.split("@")[0].toLowerCase().replace(/[^a-z0-9]+/g, "-") + "-account";
|
||||||
INSERT INTO fs_users (id, user_id, data)
|
const data = JSON.stringify({
|
||||||
VALUES (gen_random_uuid()::text, $1, $2::jsonb)
|
email: user.email,
|
||||||
ON CONFLICT ((data->>'email')) DO UPDATE
|
name: user.name,
|
||||||
SET user_id = EXCLUDED.user_id,
|
image: user.image,
|
||||||
data = fs_users.data || EXCLUDED.data,
|
workspace,
|
||||||
updated_at = NOW()
|
});
|
||||||
`, [user.id, JSON.stringify({ email: user.email, name: user.name, image: user.image, workspace })]);
|
|
||||||
|
// Two-step upsert avoids relying on ON CONFLICT expression matching
|
||||||
|
const existing = await query<{ id: string }>(
|
||||||
|
`SELECT id FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
|
||||||
|
[user.email]
|
||||||
|
);
|
||||||
|
if (existing.length === 0) {
|
||||||
|
await query(
|
||||||
|
`INSERT INTO fs_users (id, user_id, data) VALUES (gen_random_uuid()::text, $1, $2::jsonb)`,
|
||||||
|
[user.id, data]
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await query(
|
||||||
|
`UPDATE fs_users SET user_id = $1, data = data || $2::jsonb, updated_at = NOW() WHERE id = $3`,
|
||||||
|
[user.id, data, existing[0].id]
|
||||||
|
);
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("[signIn] Failed to upsert fs_user:", e);
|
console.error("[signIn] Failed to upsert fs_user:", e);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user