chore: update src/pages/api/auth/2fa/disable.ts
swadhinbiswas committed 8 months ago
25d2b94
1 parent 67cf10c
commit 25d2b94
1 file changed
+19 -4
Showing 1 changed file+19-4
▼src/pages/api/auth/2fa/disable.ts
+19-4
| @@ -2,9 +2,9 @@ | ||
2 | 2 | import type { APIRoute } from "astro"; |
3 | 3 | import type { NodePgDatabase } from "drizzle-orm/node-postgres"; |
4 | 4 | import { getDatabase, schema } from "@/db"; |
5 | -import { getUserFromRequest } from "@/lib/auth"; | |
5 | +import { getUserFromRequest, verify2FAToken } from "@/lib/auth"; | |
6 | 6 | import { eq } from "drizzle-orm"; |
7 | -import { unauthorized, success, serverError } from "@/lib/api"; | |
7 | +import { unauthorized, success, serverError, badRequest } from "@/lib/api"; | |
8 | 8 | |
9 | 9 | import { logger } from "@/lib/logger"; |
10 | 10 | import { withErrorHandler } from "@/lib/errors"; |
| @@ -16,9 +16,24 @@ export const POST: APIRoute = withErrorHandler(async ({ request }) => { | ||
16 | 16 | } |
17 | 17 | |
18 | 18 | const db = getDatabase() as NodePgDatabase<typeof schema>; |
19 | + const body = await request.json().catch(() => ({})); | |
20 | + const token = typeof body?.token === "string" ? body.token : ""; | |
19 | 21 | |
20 | - // In a real app, we might require a password or 2FA token to disable 2FA. | |
21 | - // For now, we will just disable it. | |
22 | + if (!token) { | |
23 | + return badRequest("Authentication code required"); | |
24 | + } | |
25 | + | |
26 | + const currentUser = await db.query.users.findFirst({ | |
27 | + where: eq(schema.users.id, userPayload.userId), | |
28 | + }); | |
29 | + if (!currentUser?.twoFactorEnabled || !currentUser.twoFactorSecret) { | |
30 | + return badRequest("2FA is not enabled"); | |
31 | + } | |
32 | + | |
33 | + const isValid = verify2FAToken(token, currentUser.twoFactorSecret); | |
34 | + if (!isValid) { | |
35 | + return badRequest("Invalid authentication code"); | |
36 | + } | |
22 | 37 | |
23 | 38 | await db.update(schema.users) |
24 | 39 | .set({ |
25 | 40 | |