-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
53 lines (50 loc) · 1.75 KB
/
auth.ts
File metadata and controls
53 lines (50 loc) · 1.75 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
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
import { client } from "./sanity/lib/client"
import { AUTHOR_BY_GITHUB_ID_QUERY } from "./sanity/lib/queries"
import { writeClient } from "./sanity/lib/write-client"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [GitHub],
// By default, the `id` property does not exist on `token` or `session`. See the [TypeScript](https://authjs.dev/getting-started/typescript) on how to add it.
callbacks: {
async signIn({ user: { name, email, image }, profile }) {
if (!profile) {
console.warn("Profile is undefined, skipping user creation");
return true; // 允许登录继续
}
const { id, login, bio } = profile as { id: string; login: string; bio?: string };
const existingUser = await client
.withConfig({ useCdn: false })
.fetch(AUTHOR_BY_GITHUB_ID_QUERY, { id });
if (!existingUser) {
await writeClient.create({
_type: "author",
id,
name,
username: login,
email,
image,
bio: bio || "",
});
}
return true;
},
async jwt({ token, account,profile }) {
if (account && profile) {
const user = await client
.withConfig({useCdn: false})
.fetch(AUTHOR_BY_GITHUB_ID_QUERY, {
id: profile?.id,
});
token.id = user?._id;
// console.log("JWT Callback:", { token, profile, user });
}
return token;
},
async session({ session, token }) {
Object.assign(session, {id: token.id,});
// console.log("Session Callback:", { session, token }); // Debug
return session;
},
},
})