-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
80 lines (74 loc) · 1.88 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
69
70
71
72
73
74
75
76
77
78
79
80
import { PrismaAdapter } from "@auth/prisma-adapter";
import prisma from "./lib/prisma";
import GoogleProvider from "next-auth/providers/google";
import NextAuth, { getServerSession, type NextAuthOptions } from "next-auth";
import {
GetServerSidePropsContext,
NextApiRequest,
NextApiResponse,
} from "next";
export const config = {
pages: {
signIn: "/login",
},
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
session: {
strategy: "jwt",
},
callbacks: {
async session({ session, token }) {
if (token) {
session.user.id = token.id;
session.user.name = token.name;
session.user.email = token.email;
session.user.image = token.picture;
session.user.username = token.username;
}
return session;
},
async jwt({ token, user }) {
const prismaUser = await prisma.user.findFirst({
where: {
email: token.email,
},
});
if (!prismaUser) {
token.id = user.id;
return token;
}
if (!prismaUser.username) {
await prisma.user.update({
where: {
id: prismaUser.id,
},
data: {
username: prismaUser.name?.split(" ").join("").toLowerCase(),
},
});
}
return {
id: prismaUser.id,
name: prismaUser.name,
email: prismaUser.email,
username: prismaUser.username,
picture: prismaUser.image,
};
},
},
} satisfies NextAuthOptions;
export default NextAuth(config);
// Use it in server contexts
export function auth(
...args:
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
| [NextApiRequest, NextApiResponse]
| []
) {
return getServerSession(...args, config);
}