|
1 | 1 | import { betterAuth } from "better-auth"; |
2 | 2 | import { drizzleAdapter } from "better-auth/adapters/drizzle"; |
3 | 3 | import { anonymous, genericOAuth } from "better-auth/plugins"; |
| 4 | +import { eq } from "drizzle-orm"; |
4 | 5 | import { db } from "./db"; |
5 | 6 | import { |
6 | 7 | accounts, |
| 8 | + integrations, |
7 | 9 | sessions, |
8 | 10 | users, |
9 | 11 | verifications, |
@@ -51,7 +53,47 @@ function getBaseURL() { |
51 | 53 |
|
52 | 54 | // Build plugins array conditionally |
53 | 55 | const plugins = [ |
54 | | - anonymous(), |
| 56 | + anonymous({ |
| 57 | + async onLinkAccount(data) { |
| 58 | + // When an anonymous user links to a real account, migrate their data |
| 59 | + const fromUserId = data.anonymousUser.user.id; |
| 60 | + const toUserId = data.newUser.user.id; |
| 61 | + |
| 62 | + console.log( |
| 63 | + `[Anonymous Migration] Migrating from user ${fromUserId} to ${toUserId}` |
| 64 | + ); |
| 65 | + |
| 66 | + try { |
| 67 | + // Migrate workflows |
| 68 | + await db |
| 69 | + .update(workflows) |
| 70 | + .set({ userId: toUserId }) |
| 71 | + .where(eq(workflows.userId, fromUserId)); |
| 72 | + |
| 73 | + // Migrate workflow executions |
| 74 | + await db |
| 75 | + .update(workflowExecutions) |
| 76 | + .set({ userId: toUserId }) |
| 77 | + .where(eq(workflowExecutions.userId, fromUserId)); |
| 78 | + |
| 79 | + // Migrate integrations |
| 80 | + await db |
| 81 | + .update(integrations) |
| 82 | + .set({ userId: toUserId }) |
| 83 | + .where(eq(integrations.userId, fromUserId)); |
| 84 | + |
| 85 | + console.log( |
| 86 | + `[Anonymous Migration] Successfully migrated data from ${fromUserId} to ${toUserId}` |
| 87 | + ); |
| 88 | + } catch (error) { |
| 89 | + console.error( |
| 90 | + "[Anonymous Migration] Error migrating user data:", |
| 91 | + error |
| 92 | + ); |
| 93 | + throw error; |
| 94 | + } |
| 95 | + }, |
| 96 | + }), |
55 | 97 | ...(process.env.VERCEL_CLIENT_ID |
56 | 98 | ? [ |
57 | 99 | genericOAuth({ |
|
0 commit comments