Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathauth.ts
More file actions
Latest commit
150 lines (143 loc) · 5.23 KB
/
Copy pathauth.ts
File metadata and controls
150 lines (143 loc) · 5.23 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
importNextAuthfrom"next-auth";
importGitHubfrom"next-auth/providers/github";
importGitLabfrom"next-auth/providers/gitlab";
importNodemailerfrom"next-auth/providers/nodemailer";
import{DrizzleAdapter}from"@auth/drizzle-adapter";
import{db}from"@/server/db";
import{user}from"@/server/db/schema";
import{createWelcomeEmailTemplate}from"@/utils/createEmailTemplate";
import{createPasswordLessEmailTemplate}from"@/utils/createPasswordLessEmailTemplate";
import{manageNewsletterSubscription}from"@/server/lib/newsletter";
importsendEmail,{nodemailerSesTransporter}from"@/utils/sendEmail";
import{isAdminEmail}from"@/server/lib/adminConfig";
import{eq}from"drizzle-orm";
import*asSentryfrom"@sentry/nextjs";
// Passwordless email sign-in is gated: enabled in dev, or explicitly via env.
constemailAuthEnabled=
process.env.EMAIL_AUTH_ENABLED==="true"||
process.env.NODE_ENV!=="production";
exportconst{ handlers, auth, signIn, signOut }=NextAuth({
adapter: DrizzleAdapter(db,{
// @ts-expect-error - Custom user table
usersTable: user,
}),
providers: [
GitHub({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
GitLab({
clientId: process.env.GITLAB_ID!,
clientSecret: process.env.GITLAB_SECRET!,
}),
...(emailAuthEnabled
? [
Nodemailer({
// next-auth v5 registers this provider as "nodemailer" by default,
// but the sign-in UI calls signIn("email") — pin the id so the
// magic-link flow actually resolves a provider.
id: "email",
name: "Email",
server: {
// Using custom sendVerificationRequest, so this is not used
host: "",
port: 0,
auth: {user: "",pass: ""},
},
from: process.env.ADMIN_EMAIL,
asyncsendVerificationRequest({ identifier, url }){
try{
if(!process.env.ADMIN_EMAIL){
thrownewError("ADMIN_EMAIL not set");
}
awaitnodemailerSesTransporter.sendMail({
to: identifier,
from: process.env.ADMIN_EMAIL,
subject: `Your link to get back to building on Codú`,
text: `Your link to get back to building on Codú\n\nClick to sign in: ${url}\n\nThis link expires soon. If you didn't request it, you can ignore this email.\n\n`,
html: createPasswordLessEmailTemplate(url),
});
}catch(error){
Sentry.captureException(error);
thrownewError(`Sign in email could not be sent`);
}
},
}),
]
: []),
],
pages: {
signIn: "/get-started",
newUser: "/welcome",
verifyRequest: "/auth",
error: "/auth/error",
},
callbacks: {
session({ session, user }){
if(session.user){
session.user.id=user.id;
session.user.role=user.role;
session.user.newsletter=user.newsletter;
// The Session type promises this and server code builds member URLs
// from it (e.g. IndexNow pings) — without this line it's undefined.
session.user.username=user.username??"";
}
returnsession;
},
asyncsignIn({ user }){
try{
constuserIsBanned=awaitdb.query.banned_users.findFirst({
where: (banned_users,{ eq })=>eq(banned_users.userId,user.id),
});
return!userIsBanned;
}catch(error){
console.error("Error checking banned users:",error);
Sentry.captureException(error);
// Fail closed: reject sign-in on error to maintain security
returnfalse;
}
},
},
events: {
asynccreateUser({user: newUser}){
const{ email, id }=newUser;
if(!email){
console.error("Missing email so cannot send welcome email");
Sentry.captureMessage("Missing 'email' so cannot send welcome email");
return;
}
// Grant admin role if email is in ADMIN_EMAILS environment variable
if(isAdminEmail(email)){
try{
awaitdb.update(user).set({role: "ADMIN"}).where(eq(user.id,id));
console.log(`Granted ADMIN role to ${email}`);
}catch(error){
console.error("Failed to grant admin role:",error);
Sentry.captureException(error);
}
}
consthtmlMessage=createWelcomeEmailTemplate(
newUser?.name||undefined,
);
// Subscribe to newsletter (separate try/catch so it doesn't block welcome email)
try{
awaitmanageNewsletterSubscription(email,"subscribe");
}catch(error){
console.error("Failed to subscribe user to newsletter:",error);
Sentry.captureException(error);
}
// Send welcome email
try{
awaitsendEmail({
recipient: email,
htmlMessage,
subject:
"Thanks for Joining Codú 🎉 + Your Exclusive Community Invite.",
});
}catch(error){
console.error("Failed to send welcome email:",error);
Sentry.captureException(error);
}
},
},
});