-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
78 lines (72 loc) · 2.07 KB
/
Copy pathauth.ts
File metadata and controls
78 lines (72 loc) · 2.07 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
import GitHub from "next-auth/providers/github";
import { AUTHOR_BY_GITHUB_ID_QUERY } from "@/sanity/lib/queries";
import { client } from "@/sanity/lib/client";
import { writeClient } from "@/sanity/lib/write-client";
import NextAuth from "next-auth";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [GitHub],
callbacks: {
async signIn({ user, profile }) {
if (!user || !profile) return false;
const { name, email, image } = user;
const { id, login, bio } = profile;
try {
const existingUser = await client
.withConfig({ useCdn: false })
.fetch(AUTHOR_BY_GITHUB_ID_QUERY, {
id: Number(id),
});
if (!existingUser) {
await writeClient.create({
_type: "author",
id: Number(id),
name,
username: login,
email,
image,
bio: (bio as string) || "",
});
} else {
// Sync profile data from GitHub if the user already exists
await writeClient
.patch(existingUser._id)
.set({
name,
username: login,
email,
image,
bio: (bio as string) || existingUser.bio || "",
})
.commit();
}
return true;
} catch (error) {
console.error("Error during sign in:", error);
return false;
}
},
async jwt({ token, account, profile }) {
if (account && profile) {
try {
const user = await client
.withConfig({ useCdn: false })
.fetch(AUTHOR_BY_GITHUB_ID_QUERY, {
id: Number(profile.id),
});
if (user) {
token.id = user._id;
}
} catch (error) {
console.error("Error in JWT callback:", error);
}
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
}
return session;
},
},
});