-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
66 lines (64 loc) · 1.82 KB
/
auth.ts
File metadata and controls
66 lines (64 loc) · 1.82 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
import NextAuth, { type NextAuthConfig } from "next-auth";
import Google from "next-auth/providers/google";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { db } from "@/db";
import { accounts, sessions, users, verificationTokens } from "@/db/schema";
import { eq } from "drizzle-orm";
const config: NextAuthConfig = {
adapter: DrizzleAdapter(db, {
usersTable: users,
accountsTable: accounts,
sessionsTable: sessions,
verificationTokensTable: verificationTokens,
}),
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
pages: {
signIn: "/",
},
session: {
strategy: "database",
},
callbacks: {
async signIn({ user }) {
const adminEmails = (process.env.ADMIN_EMAILS ?? "")
.split(",")
.map((v) => v.trim().toLowerCase())
.filter(Boolean);
const email = user.email?.toLowerCase();
if (email && adminEmails.includes(email)) {
try {
await db.update(users).set({ admin: true }).where(eq(users.email, email));
} catch {
// best-effort; ignore errors to not block sign-in
}
}
return true;
},
async session({ session, user }: { session: any; user: any }) {
if (session.user) {
session.user.id = user.id;
session.user.admin = Boolean(user.admin);
}
return session;
},
async redirect({ url, baseUrl }) {
const dashboardUrl = `${baseUrl}/dashboard`;
if (url === baseUrl || url === `${baseUrl}/`) return dashboardUrl;
if (url.startsWith("/")) return `${baseUrl}${url}`;
if (new URL(url).origin === baseUrl) return url;
return dashboardUrl;
},
},
trustHost: true,
};
export const {
handlers,
auth,
signIn,
signOut,
} = NextAuth(config);