-
-
Notifications
You must be signed in to change notification settings - Fork 722
Expand file tree
/
Copy pathauth.ts
More file actions
298 lines (296 loc) · 9.39 KB
/
auth.ts
File metadata and controls
298 lines (296 loc) · 9.39 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import { checkout, polar, portal, webhooks } from "@polar-sh/better-auth";
import { Polar } from "@polar-sh/sdk";
import * as Sentry from "@sentry/nextjs";
import { betterAuth } from "better-auth";
import {
captcha,
createAuthMiddleware,
customSession,
magicLink,
} from "better-auth/plugins";
import { github } from "better-auth/social-providers";
import Database from "better-sqlite3";
import { Pool } from "pg";
import { PRODUCTS } from "./product-list";
import { sendEmail } from "./send-mail";
export const polarClient = new Polar({
accessToken: process.env.POLAR_ACCESS_TOKEN,
// Use 'sandbox' if you're using the Polar Sandbox environment
// Remember that access tokens, products, etc. are completely separated between environments.
// Access tokens obtained in Production are for instance not usable in the Sandbox environment.
server: process.env.NODE_ENV === "production" ? "production" : "sandbox",
});
export const auth = betterAuth({
user: {
additionalFields: {
planType: {
type: "string",
required: false,
input: false, // don't allow user to set plan type
},
ghSponsorInfo: {
type: "string",
required: false,
input: false, // don't allow user to set role
},
},
},
emailVerification: {
sendOnSignUp: true,
autoSignInAfterVerification: true,
async sendVerificationEmail({ user, url }) {
await sendEmail({
to: user.email,
template: "verifyEmail",
props: { url, name: user.name },
});
},
},
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
autoSignIn: true,
},
socialProviders: {
github: {
clientId: process.env.AUTH_GITHUB_ID as string,
clientSecret: process.env.AUTH_GITHUB_SECRET as string,
async getUserInfo(token) {
// This is a workaround to still re-use the default github provider getUserInfo
// and still be able to fetch the sponsor info with the token
return (await github({
clientId: process.env.AUTH_GITHUB_ID as string,
clientSecret: process.env.AUTH_GITHUB_SECRET as string,
async mapProfileToUser() {
const resSponsor = await fetch(`https://api.github.com/graphql`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token.accessToken}`,
},
// organization(login:"TypeCellOS") {
// user(login:"YousefED") {
body: JSON.stringify({
query: `{
user(login:"YousefED") {
sponsorshipForViewerAsSponsor(activeOnly:false) {
isActive,
tier {
name
monthlyPriceInDollars
}
}
}
}`,
}),
});
if (resSponsor.ok) {
// Mock data. TODO: disable and test actial data
// profile.sponsorInfo = {
// isActive: true,
// tier: {
// name: "test",
// monthlyPriceInDollars: 100,
// },
// };
// use API data:
const data = await resSponsor.json();
//// eslint-disable-next-line no-console
console.log("sponsor data", data);
// {
// "data": {
// "user": {
// "sponsorshipForViewerAsSponsor": {
// "isActive": true,
// "tier": {
// "name": "$90 a month",
// "monthlyPriceInDollars": 90
// }
// }
// }
// }
// }
const sponsorInfo: null | {
isActive: boolean;
tier: {
monthlyPriceInDollars: number;
};
} = data.data.user.sponsorshipForViewerAsSponsor;
if (!sponsorInfo?.isActive) {
return {};
}
return {
ghSponsorInfo: JSON.stringify(sponsorInfo),
};
}
return {};
},
}).getUserInfo(token))!;
},
},
},
// Use SQLite for local development
database:
process.env.NODE_ENV === "production" || process.env.POSTGRES_URL
? new Pool({
connectionString: process.env.POSTGRES_URL,
})
: new Database("./sqlite.db"),
plugins: [
captcha({
provider: "cloudflare-turnstile",
secretKey: process.env.TURNSTILE_SECRET_KEY!,
endpoints: ["/sign-up/email"],
}),
customSession(
async ({ user, session }) => {
// If they are a GitHub sponsor, use that plan type
if (user.ghSponsorInfo) {
const sponsorInfo = JSON.parse(user.ghSponsorInfo);
return {
planType:
sponsorInfo.tier.monthlyPriceInDollars > 100
? "business"
: "starter",
user,
session,
};
}
// If not, see if they are subscribed to a Polar product
// If not, use the free plan
return {
planType: user.planType ?? PRODUCTS.free.slug,
user,
session,
};
},
{
// This is really only for type inference
user: {
additionalFields: {
ghSponsorInfo: {
type: "string",
required: false,
input: false, // don't allow user to set role
},
planType: {
type: "string",
required: false,
input: false, // don't allow user to set plan type
},
},
},
},
),
magicLink({
sendMagicLink: async ({ email, url }) => {
await sendEmail({
to: email,
template: "magicLink",
props: { url },
});
},
}),
// Just temporary for testing
// Serves on http://localhost:3000/api/auth/reference
// openAPI(),
polar({
client: polarClient,
// Enable automatic Polar Customer creation on signup
createCustomerOnSignUp: true,
use: [
checkout({
products: [
{
productId: PRODUCTS.business.id, // ID of Product from Polar Dashboard
slug: PRODUCTS.business.slug, // Custom slug for easy reference in Checkout URL, e.g. /checkout/pro
},
{
productId: PRODUCTS["business-yearly"].id,
slug: PRODUCTS["business-yearly"].slug,
},
{
productId: PRODUCTS.starter.id,
slug: PRODUCTS.starter.slug,
},
],
successUrl: "/thanks",
authenticatedUsersOnly: true,
}),
portal(),
webhooks({
secret: process.env.POLAR_WEBHOOK_SECRET as string,
async onPayload(payload) {
switch (payload.type) {
case "subscription.active":
case "subscription.canceled":
case "subscription.updated":
case "subscription.revoked":
case "subscription.created":
case "subscription.uncanceled": {
const authContext = await auth.$context;
const userId = payload.data.customer.externalId;
if (!userId) {
return;
}
if (payload.data.status === "active") {
const productId = payload.data.product.id;
const planType = Object.values(PRODUCTS).find(
(p) => p.id === productId,
)?.slug;
await authContext.internalAdapter.updateUser(userId, {
planType,
});
} else {
// No active subscription, so we need to remove the plan type
await authContext.internalAdapter.updateUser(userId, {
planType: null,
});
}
}
}
},
}),
],
}),
],
onAPIError: {
onError: (error) => {
Sentry.captureException(error, {
tags: { source: "better-auth" },
level: "fatal",
});
},
},
hooks: {
after: createAuthMiddleware(async (ctx) => {
if (
ctx.path === "/magic-link/verify" ||
ctx.path === "/verify-email" ||
ctx.path === "/sign-in/social"
) {
// After verifying email, send them a welcome email
const newSession = ctx.context.newSession;
if (newSession) {
const oneMinuteAgo = new Date(Date.now() - 60 * 1000);
if (
ctx.path === "/magic-link/verify" &&
newSession.user.createdAt < oneMinuteAgo
) {
// magic link is for an account that was created more than a minute ago, so just a normal sign in
// no need to send welcome email
return false;
}
// await sendEmail({
// to: newSession.user.email,
// template: "welcome",
// props: {
// name: newSession.user.name,
// },
// });
return;
}
}
}),
},
});