-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
107 lines (105 loc) · 2.62 KB
/
auth.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
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
import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
import Credentials from "next-auth/providers/credentials";
import { prisma } from "@/lib/prisma";
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
Credentials({
credentials: {
email: {},
password: {},
},
async authorize(credentials) {
if (!credentials.email || !credentials.password) {
return null;
}
const user = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});
if (!user) {
return null;
}
//If user exists return it with all properties
return {
id: user.id + "",
email: user.email,
name: user.name,
image: user.image,
};
},
}),
],
session: {
strategy: "jwt",
},
pages: {
signIn: "/auth",
},
callbacks: {
//Providers sign in callback
signIn: async (user, account, profile) => {
//Find user in database
const u = await prisma.user.findUnique({
where: {
email: user.user.email,
},
});
if (!u) {
await prisma.user.create({
data: {
email: user.user.email,
name: user.user.name,
image: user.user.image,
password: "test",
provider: user.account.provider,
},
});
}
return true;
},
session: async ({ token, session }) => {
// console.log("Session Callback:", { token, session });
const u = await prisma.user.findUnique({
where: {
email: session.user.email,
},
cacheStrategy: { ttl: 60 },
});
// console.log("Session Callback user in db:", u);
return {
...session,
user: {
...session.user,
id: u.id,
image: token.image,
},
};
},
jwt: ({ token, user, trigger, session }) => {
if (user) {
const u = user;
return {
...token,
id: u.id,
image: u.image,
};
}
//When session update is triggered in action refresh session
if (trigger === "update") {
return { ...token, ...session.user };
}
return token;
},
},
});