-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
77 lines (71 loc) · 2.36 KB
/
Copy pathauth.ts
File metadata and controls
77 lines (71 loc) · 2.36 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
import NextAuth from "next-auth";
import authConfig from "@/auth.config";
import db from "./lib/db";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { getUserById } from "./data/user";
import { UserRole } from "@prisma/client";
/**
* NextAuth configuration with custom callbacks and Prisma adapter.
*
* - Callbacks:
* - `signIn`: Validates user sign-in, ensuring email is verified for credentials provider.
* - `session`: Adds user ID and role to the session object.
* - `jwt`: Adds user role to the JWT token.
* - Events:
* - `linkAccount`: Marks email as verified when a new account is linked.
* - Adapter: Uses Prisma adapter for database interactions.
* - Session strategy: Uses JWT for sessions.
* - Additional configurations from `authConfig`.
* - handlers is called in app/api/auth/[...nextauth]/route.ts
*/
export const { auth, handlers, signIn, signOut } = NextAuth({
callbacks: {
async signIn({ user, account }) {
if (account?.provider !== "credentials") return true;
if (!user.id) return false;
const existingUser = await getUserById(user.id);
if (!existingUser || existingUser.emailVerified === null) {
return false;
}
return true;
},
async session({ token, session }) {
if (token.sub && session.user) {
session.user.id = token.sub;
session.user.role = token.role as UserRole;
// add more fields to the session object if needed
// to add additional fields also update the next-auth.d.ts file like UserRole
// for more info check next-auth.d.ts
}
return session;
},
async jwt({ token }) {
if (!token.sub) return token;
const existingUser = await getUserById(token.sub);
if (existingUser) {
token.role = existingUser.role;
}
return token;
},
async redirect({ url, baseUrl }) {
// If redirecting to a callback URL, allow it
if (url.startsWith("/")) return `${baseUrl}${url}`;
// If redirecting to the same domain, allow it
if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
},
events: {
async linkAccount({ user }) {
await db.user.update({
where: { id: user.id },
data: { emailVerified: new Date() },
});
},
},
adapter: PrismaAdapter(db),
session: {
strategy: "jwt",
},
...authConfig,
});