-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
87 lines (78 loc) · 2.45 KB
/
Copy pathauth.ts
File metadata and controls
87 lines (78 loc) · 2.45 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
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import prisma from "./lib/prisma";
import authConfig from "./lib/auth.config";
export const { auth, handlers, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(prisma),
pages: {
signIn: "/login",
},
events: {
async linkAccount({ user }) {
await prisma.user.update({
where: { id: user.id },
data: {
emailVerified: new Date(),
},
});
},
},
callbacks: {
async signIn({ account }) {
// console.log("🔐 signIn callback triggered", { provider: account?.provider });
if (account?.provider !== "credentials") {
return true;
}
return false;
},
async jwt({ token, trigger, user, session }) {
// Detect if we're running in Edge Runtime
const isEdgeRuntime =
typeof process === "undefined" || process.env.NEXT_RUNTIME === "edge";
// ✅ Only run Prisma queries outside of Edge Runtime (not in middleware)
if (token?.email && !isEdgeRuntime) {
const emailToQuery = user?.email || token.email;
// console.log("📧 Email to query:", emailToQuery);
try {
// console.log("🔍 Fetching user from database...");
const dbUser = await prisma.user.findUnique({
where: { email: emailToQuery as string },
include: {
userRoles: true,
},
});
if (dbUser) {
token.id = dbUser.id;
token.name = dbUser.name;
token.email = dbUser.email;
token.libraryRoles = dbUser.userRoles.map((u) => ({
libid: u.libraryId,
role: u.role,
}));
// console.log("✅ Token updated with library roles:", token.libraryRoles);
}
} catch (error) {
console.error("❌ Error fetching user data:", error);
// Keep existing token data if database query fails
}
}
return token;
},
async session({ session, token }) {
// const isEdgeRuntime = typeof process === 'undefined' || process.env.NEXT_RUNTIME === 'edge';
return {
...session,
user: {
...session.user,
id: token.id,
name: token.name,
email: token.email,
libdetails: token.libraryRoles,
},
};
},
},
session: { strategy: "jwt" },
secret: process.env.AUTH_SECRET,
...authConfig,
});