fix: 强制 username 登录也需要邮箱验证
- 添加 sendOnSignIn: true 配置 - 在 hook 中拦截 /sign-in/username 请求 - 检查用户邮箱是否已验证,未验证返回 403
This commit is contained in:
26
src/auth.ts
26
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,14 +51,35 @@ export const auth = betterAuth({
|
||||
plugins: [nextCookies(), username()],
|
||||
hooks: {
|
||||
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 };
|
||||
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",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user