forked from HiveNexus/HiveChat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
72 lines (70 loc) · 2.06 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import NextAuth from "next-auth";
import { ZodError } from "zod";
import Credentials from "next-auth/providers/credentials";
import { signInSchema } from "@/app/lib/zod";
import { verifyPassword } from "@/app/utils/password";
import { db } from '@/app/db';
import { users } from '@/app/db/schema';
import { eq } from 'drizzle-orm';
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
try {
const { email, password } = await signInSchema.parseAsync(credentials);
const user = await db.query.users
.findFirst({
where: eq(users.email, email)
})
if (!user || !user.password) {
return null;
}
const passwordMatch = await verifyPassword(password, user.password);
if (passwordMatch) {
return {
id: user.id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin || false,
};
} else {
return null;
}
} catch (error) {
if (error instanceof ZodError) {
// 如果验证失败,返回 null 表示凭据无效
return null;
}
// 处理其他错误
throw error;
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.isAdmin = user.isAdmin;
}
return token;
},
async session({ session, token }) {
if (token) {
// session.user.isAdmin = token.isAdmin || false;
session.user = {
...session.user, // 保留已有的属性
id: String(token.id),
isAdmin: Boolean(token.isAdmin), // 添加 isAdmin
};
}
return session;
},
},
})