generated from plutack/nextjsauth-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
68 lines (62 loc) · 1.74 KB
/
auth.ts
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
import NextAuth from "next-auth";
import "next-auth/jwt";
import authConfig from "@/auth.config";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { db } from "@/lib/db";
import "next-auth";
import { userRole } from "@prisma/client";
import { encode } from "next-auth/jwt";
declare module "next-auth" {
interface User {
id?: string;
role?: userRole;
accessToken?: string;
totalClicks?: number;
uniqueCountryCount?: number;
totalLinksCount?: number;
}
interface Session {
user: User;
}
}
declare module "next-auth/jwt" {
interface JWT {
id: string;
role?: userRole;
totalClicks?: number;
uniqueCountryCount?: number;
totalLinksCount?: number;
}
}
export const { auth, handlers, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(db),
session: { strategy: "jwt" },
...authConfig,
callbacks: {
async jwt({ token, user }) {
if (user) {
const userWithLinks = await db.user.findUnique({
where: { id: user.id },
include: { links: true },
});
token.role = user.role;
token.totalClicks = user.totalClicks;
token.uniqueCountryCount = user.uniqueCountryCount;
token.totalLinksCount = userWithLinks?.links.length || 0;
}
return token;
},
async session({ session, token, user }) {
if (token.sub) {
session.user.id = token.sub;
session.user.role = token.role;
session.user.totalClicks = token.totalClicks;
session.user.uniqueCountryCount = token.uniqueCountryCount;
session.user.totalLinksCount = token.totalLinksCount;
}
const { id, ...restOfUser } = session.user;
session.user = { id, ...restOfUser };
return session;
},
},
});