-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.config.ts
79 lines (72 loc) · 1.91 KB
/
auth.config.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
73
74
75
76
77
78
79
import type { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import prisma from "@/lib/prisma";
import { AuthError } from "next-auth";
import { comparePassword } from "./lib/auth/authpw";
// 将错误信息抽取为常量
const AUTH_ERROR_MESSAGES = {
USER_NOT_FOUND: "呜呜~ 这个用户好像不存在哦,快检查一下吧!",
INVALID_PASSWORD: "啊呀~ 密码错啦~ 试试看能不能记起来?",
} as const;
export class CustomAuthError extends AuthError {
constructor(msg: string) {
super();
this.message = msg;
this.stack = undefined;
}
}
// 将验证逻辑抽取为独立函数
const validateCredentials = async (
credentials: Record<"email" | "password", string>
) => {
const user = await prisma.users.findUnique({
where: { email: credentials.email },
});
if (!user) {
throw new CustomAuthError(AUTH_ERROR_MESSAGES.USER_NOT_FOUND);
}
const passwordMatch = await comparePassword(
credentials.password,
user.password
);
if (!passwordMatch) {
throw new CustomAuthError(AUTH_ERROR_MESSAGES.INVALID_PASSWORD);
}
return user;
};
export default {
providers: [
Credentials({
credentials: {
email: {},
password: {},
},
authorize: validateCredentials,
}),
],
pages: {
signIn: "/AuthPanel",
},
callbacks: {
jwt({ token, user }) {
if (user) {
// User is available during sign-in
token.identity = user.identity;
}
return token;
},
session({ session, token }) {
session.user.identity = token.identity;
return session;
},
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnDashboard = nextUrl.pathname.startsWith("/dashboard");
if (isOnDashboard) {
return isLoggedIn;
}
return true;
},
},
debug: false,
} satisfies NextAuthConfig;