-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.js
51 lines (42 loc) · 1.2 KB
/
route.js
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
import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
import User from "@models/user";
import { connectToDB } from "@utils/database";
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
callbacks: {
async session({ session }) {
// store the user id from MongoDB to session
const sessionUser = await User.findOne({
email: session.user.email,
});
session.user.id = sessionUser._id.toString();
return session;
},
async signIn({ profile }) {
try {
await connectToDB();
// check if a user already exist
const userExists = await User.findOne({ email: profile.email });
// if not, create user
if (!userExists) {
await User.create({
email: profile.email,
username: profile.name.replace(" ", "").toLowerCase(),
image: profile.picture,
});
}
return true;
} catch (error) {
console.log(error);
return false;
}
},
},
});
export { handler as GET, handler as POST };