From db0b0ff348aacd2594ea9e49554f71d03432e70c Mon Sep 17 00:00:00 2001 From: goddonebianu Date: Tue, 10 Mar 2026 19:41:30 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=BC=BA=E5=88=B6=20username=20?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E4=B9=9F=E9=9C=80=E8=A6=81=E9=82=AE=E7=AE=B1?= =?UTF-8?q?=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 sendOnSignIn: true 配置 - 在 hook 中拦截 /sign-in/username 请求 - 检查用户邮箱是否已验证,未验证返回 403 --- src/auth.ts | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/auth.ts b/src/auth.ts index 258666f..c7d0efc 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -30,6 +30,7 @@ export const auth = betterAuth({ }, emailVerification: { sendOnSignUp: true, + sendOnSignIn: true, sendVerificationEmail: async ({ user, url }) => { const result = await sendEmail({ to: user.email, @@ -50,13 +51,34 @@ export const auth = betterAuth({ plugins: [nextCookies(), username()], hooks: { before: createAuthMiddleware(async (ctx) => { - if (ctx.path !== "/sign-up/email" && ctx.path !== "/update-user") return; - - const body = ctx.body as { username?: string }; - if (!body.username || body.username.trim() === "") { - throw new APIError("BAD_REQUEST", { - message: "Username is required", - }); + if (ctx.path === "/sign-up/email" || ctx.path === "/update-user") { + const body = ctx.body as { username?: string }; + if (!body.username || body.username.trim() === "") { + throw new APIError("BAD_REQUEST", { + 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", + }); + } + } } }), },