-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
54 lines (49 loc) · 1.2 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
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import { AUTHOR_BY_GOOGLE_ID_QUERY } from "./sanity/lib/queries";
import { client } from "./sanity/lib/client";
import { writeClient } from "./sanity/lib/write-client";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [Google],
callbacks: {
async signIn({
user: { name, email, image },
profile: { sub: id, given_name },
}) {
// console.log("user", user);
// console.log("profile", profile);
const existingUser = await client
.withConfig({ useCdn: false })
.fetch(AUTHOR_BY_GOOGLE_ID_QUERY, {
id,
});
if (!existingUser) {
await writeClient.create({
_type: "author",
id,
name,
username: given_name,
email,
image,
bio: "",
});
}
return true;
},
async jwt({ token, account, profile }) {
if (account && profile) {
const user = await client
.withConfig({ useCdn: false })
.fetch(AUTHOR_BY_GOOGLE_ID_QUERY, {
id: profile?.sub,
});
token.id = user?._id;
}
return token;
},
async session({ session, token }) {
Object.assign(session, { id: token.id });
return session;
},
},
});