fix: 强制 username 登录也需要邮箱验证

- 添加 sendOnSignIn: true 配置
- 在 hook 中拦截 /sign-in/username 请求
- 检查用户邮箱是否已验证,未验证返回 403
This commit is contained in:
2026-03-10 19:41:30 +08:00
parent 6f4b123a84
commit db0b0ff348

View File

@@ -30,6 +30,7 @@ export const auth = betterAuth({
}, },
emailVerification: { emailVerification: {
sendOnSignUp: true, sendOnSignUp: true,
sendOnSignIn: true,
sendVerificationEmail: async ({ user, url }) => { sendVerificationEmail: async ({ user, url }) => {
const result = await sendEmail({ const result = await sendEmail({
to: user.email, to: user.email,
@@ -50,14 +51,35 @@ export const auth = betterAuth({
plugins: [nextCookies(), username()], plugins: [nextCookies(), username()],
hooks: { hooks: {
before: createAuthMiddleware(async (ctx) => { before: createAuthMiddleware(async (ctx) => {
if (ctx.path !== "/sign-up/email" && ctx.path !== "/update-user") return; if (ctx.path === "/sign-up/email" || ctx.path === "/update-user") {
const body = ctx.body as { username?: string }; const body = ctx.body as { username?: string };
if (!body.username || body.username.trim() === "") { if (!body.username || body.username.trim() === "") {
throw new APIError("BAD_REQUEST", { throw new APIError("BAD_REQUEST", {
message: "Username is required", message: "Username is required",
}); });
} }
}
if (ctx.path === "/sign-in/username") {
const body = ctx.body as { username?: string };
if (body.username) {
const user = await prisma.user.findFirst({
where: {
OR: [
{ username: body.username },
{ email: body.username },
],
},
select: { emailVerified: true },
});
if (user && !user.emailVerified) {
throw new APIError("FORBIDDEN", {
message: "Please verify your email address before signing in",
});
}
}
}
}), }),
}, },
}); });