-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path[...nextauth].ts
More file actions
163 lines (147 loc) · 4.6 KB
/
Copy path[...nextauth].ts
File metadata and controls
163 lines (147 loc) · 4.6 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import CredentialsProvider from "next-auth/providers/credentials";
import FacebookProvider from "next-auth/providers/facebook";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import GoogleProvider from "next-auth/providers/google";
import { NextApiRequest, NextApiResponse } from "next";
import { getCookie, setCookie } from "cookies-next";
import NextAuth, { AuthOptions } from "next-auth";
import { decode, encode } from "next-auth/jwt";
import { Prisma, prisma } from "database";
import { loginSchema } from "validation";
import { randomUUID } from "crypto";
import bcrypt from "bcrypt";
export function authOptionsWrapper(req: NextApiRequest, res: NextApiResponse) {
const isCredentialsCallback =
req.query?.nextauth?.includes("callback") &&
req.query.nextauth?.includes("credentials") &&
req?.method === "POST";
return [
req,
res,
{
adapter: PrismaAdapter(prisma),
providers: [
FacebookProvider({
clientId: process.env.FACEBOOK_ID!,
clientSecret: process.env.FACEBOOK_SECRET!,
}),
GoogleProvider({
clientId: process.env.GOOGLE_ID!,
clientSecret: process.env.GOOGLE_SECRET!,
}),
CredentialsProvider({
credentials: {
email: { label: "email", type: "text" },
password: { label: "Password", type: "password" },
},
authorize: async (credentials) => {
try {
const result = await loginSchema.safeParseAsync(credentials);
if (!result.success) {
throw new Error(result.error.errors[0].message);
}
const { email, password } = result.data;
const user = await prisma.user.findUnique({
where: {
email,
},
});
if (!user) {
throw new Error("User account does not exist");
}
const passwordsMatch = await bcrypt.compare(
password,
user?.password!
);
if (!passwordsMatch) {
throw new Error("Password is not correct");
}
return {
id: user.id,
email: user.email,
image: user.image,
name: user.name,
};
} catch (error) {
if (
error instanceof Prisma.PrismaClientInitializationError ||
error instanceof Prisma.PrismaClientKnownRequestError
) {
throw new Error("System error. Please contact support");
}
throw error;
}
},
}),
],
callbacks: {
async redirect({ url }) {
return url;
},
async signIn({ user }) {
if (isCredentialsCallback) {
if (user) {
const sessionToken = randomUUID();
const sessionExpiry = new Date(
Date.now() + 60 * 60 * 24 * 30 * 1000
);
await prisma.session.create({
data: {
sessionToken,
userId: user.id,
expires: sessionExpiry,
},
});
setCookie("next-auth.session-token", sessionToken, {
req,
res,
expires: sessionExpiry,
});
}
}
return true;
},
},
secret: process.env.NEXTAUTH_SECRET,
jwt: {
maxAge: 60 * 60 * 24 * 30,
async encode(params) {
if (isCredentialsCallback) {
const cookie = getCookie("next-auth.session-token", { req, res });
console.log(cookie);
if (cookie) return cookie;
return "";
}
return encode(params);
},
async decode(params) {
if (isCredentialsCallback) {
return null;
}
return decode(params);
},
},
debug: process.env.NODE_ENV === "development",
events: {
async signOut({ session }) {
const { sessionToken = "" } = session as unknown as {
sessionToken?: string;
};
if (sessionToken) {
await prisma.session.deleteMany({
where: {
sessionToken,
},
});
}
},
},
} as AuthOptions,
] as const;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
return NextAuth(...authOptionsWrapper(req, res));
}