forked from Surendrakumarpatel/snapchat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
57 lines (56 loc) · 1.99 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
import NextAuth from "next-auth"
import connectDB from "./lib/db"
import github from "next-auth/providers/github";
import { User } from "./models/user.model";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
github({
clientId: process.env.AUTH_GITHUB_CLIENT_ID,
clientSecret: process.env.AUTH_GITHUB_CLIENT_SECRET
})
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({session}:{session:any}) {
try {
await connectDB();
if (session.user) {
const user = await User.findOne({ email: session.user.email });
if (user) {
session.user._id = user._id;
return session;
} else {
console.log("User not found.");
}
} else {
console.log("Invalid session");
}
} catch (error) {
console.log(error);
throw error;
}
},
async signIn({ account, profile }) {
if (account?.provider === 'github') {
await connectDB();
try {
const user = await User.findOne({email:profile?.email!});
if (!user) {
const newUser = await User.create({
username: profile?.login,
fullname: profile?.name,
email: profile?.email,
profilePhoto: profile?.avatar_url
});
await newUser.save();
}
return true;
} catch (error) {
console.log(error);
return false;
}
}
return false;
}
}
})