-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathauth-options.ts
More file actions
200 lines (185 loc) · 5.72 KB
/
Copy pathauth-options.ts
File metadata and controls
200 lines (185 loc) · 5.72 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
import crypto from "node:crypto";
import { serverEnv } from "@cap/env";
import { eq } from "drizzle-orm";
import type { NextAuthOptions } from "next-auth";
import { getServerSession as _getServerSession } from "next-auth";
import type { Adapter } from "next-auth/adapters";
import EmailProvider from "next-auth/providers/email";
import GoogleProvider from "next-auth/providers/google";
import type { Provider } from "next-auth/providers/index";
import WorkOSProvider from "next-auth/providers/workos";
import { sendEmail } from "../emails/config.ts";
import { db } from "../index.ts";
import { users } from "../schema.ts";
import { isEmailAllowedForSignup } from "./domain-utils.ts";
import { DrizzleAdapter } from "./drizzle-adapter.ts";
export const maxDuration = 120;
export const authOptions = (): NextAuthOptions => {
let _adapter: Adapter | undefined;
let _providers: Provider[] | undefined;
return {
get adapter() {
if (_adapter) return _adapter;
_adapter = DrizzleAdapter(db());
return _adapter;
},
debug: process.env.NODE_ENV !== "production",
session: {
strategy: "jwt",
},
get secret() {
return serverEnv().NEXTAUTH_SECRET;
},
pages: {
signIn: "/login",
},
get providers() {
if (_providers) return _providers;
_providers = [
GoogleProvider({
clientId: serverEnv().GOOGLE_CLIENT_ID!,
clientSecret: serverEnv().GOOGLE_CLIENT_SECRET!,
authorization: {
params: {
scope: [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
].join(" "),
prompt: "select_account",
},
},
}),
WorkOSProvider({
clientId: serverEnv().WORKOS_CLIENT_ID as string,
clientSecret: serverEnv().WORKOS_API_KEY as string,
profile(profile) {
return {
id: profile.id,
name: profile.first_name
? `${profile.first_name} ${profile.last_name || ""}`
: profile.email?.split("@")[0] || profile.id,
email: profile.email,
image: profile.profile_picture_url,
};
},
}),
EmailProvider({
async generateVerificationToken() {
return crypto.randomInt(100000, 1000000).toString();
},
async sendVerificationRequest({ identifier, token }) {
console.log("sendVerificationRequest");
if (!serverEnv().RESEND_API_KEY) {
console.log("\n");
console.log(
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
);
console.log("🔐 VERIFICATION CODE (Development Mode)");
console.log(
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
);
console.log(`📧 Email: ${identifier}`);
console.log(`🔢 Code: ${token}`);
console.log(`⏱ Expires in: 10 minutes`);
console.log(
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
);
console.log("\n");
} else {
console.log({ identifier, token });
const { OTPEmail } = await import("../emails/otp-email");
const email = OTPEmail({ code: token, email: identifier });
console.log({ email });
await sendEmail({
email: identifier,
subject: `Your Cap Verification Code`,
react: email,
});
}
},
}),
];
return _providers;
},
cookies: {
sessionToken: {
name: `next-auth.session-token`,
options: {
httpOnly: true,
sameSite: "none",
path: "/",
secure: true,
},
},
},
callbacks: {
async signIn({ user, email, credentials }) {
const allowedDomains = serverEnv().CAP_ALLOWED_SIGNUP_DOMAINS;
if (!allowedDomains) return true;
const rawEmail =
user?.email ||
(typeof email === "string"
? email
: typeof credentials?.email === "string"
? credentials.email
: null);
if (!rawEmail || typeof rawEmail !== "string") return true;
const userEmail = rawEmail.toLowerCase();
const [existingUser] = await db()
.select()
.from(users)
.where(eq(users.email, userEmail))
.limit(1);
// Only apply domain restrictions for new users, existing ones can always sign in
if (
!existingUser &&
!isEmailAllowedForSignup(userEmail, allowedDomains)
) {
console.warn(`Signup blocked for email domain: ${userEmail}`);
return false;
}
return true;
},
async session({ token, session }) {
if (!session.user) return session;
if (token?.id && typeof token.id === "string") {
(session.user as { id: string }).id = token.id;
session.user.name = token.name ?? null;
session.user.email = token.email ?? null;
session.user.image = token.picture ?? null;
}
return session;
},
async jwt({ token, user }) {
if (user || !token.id) {
const [dbUser] = await db()
.select({
id: users.id,
name: users.name,
lastName: users.lastName,
email: users.email,
image: users.image,
})
.from(users)
.where(eq(users.email, (token.email || "").toLowerCase()))
.limit(1);
if (!dbUser) {
if (user) {
token.id = user?.id;
}
return token;
}
return {
id: dbUser.id,
name: dbUser.name,
lastName: dbUser.lastName,
email: dbUser.email,
picture: dbUser.image,
};
}
return token;
},
},
};
};
export const getServerSession = () => _getServerSession(authOptions());