fix: 强制 username 登录也需要邮箱验证
- 添加 sendOnSignIn: true 配置 - 在 hook 中拦截 /sign-in/username 请求 - 检查用户邮箱是否已验证,未验证返回 403
This commit is contained in:
34
src/auth.ts
34
src/auth.ts
@@ -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,13 +51,34 @@ 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 };
|
||||||
|
if (!body.username || body.username.trim() === "") {
|
||||||
|
throw new APIError("BAD_REQUEST", {
|
||||||
|
message: "Username is required",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const body = ctx.body as { username?: string };
|
if (ctx.path === "/sign-in/username") {
|
||||||
if (!body.username || body.username.trim() === "") {
|
const body = ctx.body as { username?: string };
|
||||||
throw new APIError("BAD_REQUEST", {
|
if (body.username) {
|
||||||
message: "Username is required",
|
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