-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathauth.ts
More file actions
160 lines (148 loc) · 4.6 KB
/
auth.ts
File metadata and controls
160 lines (148 loc) · 4.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { anonymous, genericOAuth } from "better-auth/plugins";
import { eq } from "drizzle-orm";
import { db } from "./db";
import {
accounts,
integrations,
sessions,
users,
verifications,
workflowExecutionLogs,
workflowExecutions,
workflowExecutionsRelations,
workflows,
} from "./db/schema";
// Construct schema object for drizzle adapter
const schema = {
user: users,
session: sessions,
account: accounts,
verification: verifications,
workflows,
workflowExecutions,
workflowExecutionLogs,
workflowExecutionsRelations,
};
// Determine the base URL for authentication
// This supports Vercel Preview deployments with dynamic URLs
function getBaseURL() {
// Priority 1: Explicit BETTER_AUTH_URL (set manually for production/dev)
if (process.env.BETTER_AUTH_URL) {
return process.env.BETTER_AUTH_URL;
}
// Priority 2: NEXT_PUBLIC_APP_URL
if (process.env.NEXT_PUBLIC_APP_URL) {
return process.env.NEXT_PUBLIC_APP_URL;
}
// Priority 3: Check if we're on Vercel (for preview deployments)
if (process.env.VERCEL_URL) {
// VERCEL_URL doesn't include protocol, so add it
// Use https for Vercel deployments (both production and preview)
return `https://${process.env.VERCEL_URL}`;
}
// Fallback: Local development
return "http://localhost:3000";
}
// Build plugins array conditionally
const plugins = [
anonymous({
async onLinkAccount(data) {
// When an anonymous user links to a real account, migrate their data
const fromUserId = data.anonymousUser.user.id;
const toUserId = data.newUser.user.id;
console.log(
`[Anonymous Migration] Migrating from user ${fromUserId} to ${toUserId}`
);
try {
// Migrate workflows
await db
.update(workflows)
.set({ userId: toUserId })
.where(eq(workflows.userId, fromUserId));
// Migrate workflow executions
await db
.update(workflowExecutions)
.set({ userId: toUserId })
.where(eq(workflowExecutions.userId, fromUserId));
// Migrate integrations
await db
.update(integrations)
.set({ userId: toUserId })
.where(eq(integrations.userId, fromUserId));
console.log(
`[Anonymous Migration] Successfully migrated data from ${fromUserId} to ${toUserId}`
);
} catch (error) {
console.error(
"[Anonymous Migration] Error migrating user data:",
error
);
throw error;
}
},
}),
...(process.env.VERCEL_CLIENT_ID
? [
genericOAuth({
config: [
{
providerId: "vercel",
clientId: process.env.VERCEL_CLIENT_ID,
clientSecret: process.env.VERCEL_CLIENT_SECRET || "",
authorizationUrl: "https://vercel.com/oauth/authorize",
tokenUrl: "https://api.vercel.com/login/oauth/token",
userInfoUrl: "https://api.vercel.com/login/oauth/userinfo",
scopes: ["openid", "email", "profile"],
discoveryUrl: undefined,
pkce: true,
getUserInfo: async (tokens) => {
const response = await fetch(
"https://api.vercel.com/login/oauth/userinfo",
{
headers: {
Authorization: `Bearer ${tokens.accessToken}`,
},
}
);
const profile = await response.json();
console.log("[Vercel OAuth] userinfo response:", profile);
return {
id: profile.sub,
email: profile.email,
name: profile.name ?? profile.preferred_username,
emailVerified: profile.email_verified ?? true,
image: profile.picture,
};
},
},
],
}),
]
: []),
];
export const auth = betterAuth({
baseURL: getBaseURL(),
database: drizzleAdapter(db, {
provider: "pg",
schema,
}),
emailAndPassword: {
enabled: true,
requireEmailVerification: false,
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID || "",
clientSecret: process.env.GITHUB_CLIENT_SECRET || "",
enabled: !!process.env.GITHUB_CLIENT_ID,
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID || "",
clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
enabled: !!process.env.GOOGLE_CLIENT_ID,
},
},
plugins,
});