All files / src/app/api/user/two-factor route.ts

0% Statements 0/215
100% Branches 0/0
0% Functions 0/1
0% Lines 0/215

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                                                                                                                                                                                                                                                                                                                                                                                                                                               
export const dynamic = "force-dynamic";

/**
 * Two-Factor Authentication API Route
 *
 * Manages 2FA setup and verification for users.
 * GET - Get 2FA status
 * POST - Setup/Enable 2FA
 * DELETE - Disable 2FA
 */

import { NextRequest, NextResponse } from "next/server";
import { Session } from "next-auth";
import bcrypt from "bcryptjs";
import {
  withAuth,
  withErrorHandling,
  successResponse,
  errorResponse,
  ApiSuccessResponse,
  ApiErrorResponse,
  RouteContext,
} from "@/lib/api";
import {
  generateTwoFactorSecret,
  getTwoFactorQRCode,
  getManualEntryCode,
  enableTwoFactor,
  disableTwoFactor,
  getTwoFactorStatus,
  regenerateBackupCodes,
} from "@/lib/auth/two-factor";
import { prisma } from "@/lib/prisma";
import { z } from "zod";

interface TwoFactorStatusResponse {
  enabled: boolean;
  pendingSetup: boolean;
  backupCodesRemaining: number;
}

interface TwoFactorSetupResponse {
  qrCode: string;
  manualEntryCode: string;
}

interface TwoFactorEnableResponse {
  success: boolean;
  backupCodes?: string[];
}

const enableTwoFactorSchema = z.object({
  token: z.string().length(6).regex(/^\d+$/, "Token must be 6 digits"),
});

const disableTwoFactorSchema = z.object({
  password: z.string().min(1, "Password is required"),
});

const regenerateCodesSchema = z.object({
  password: z.string().min(1, "Password is required"),
});

/**
 * Verify user password against stored hash
 */
async function verifyUserPassword(userId: number, password: string): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { password: true },
  });

  if (!user?.password) {
    // OAuth users don't have passwords - they cannot modify 2FA with password
    return false;
  }

  return bcrypt.compare(password, user.password);
}

/**
 * GET /api/user/two-factor
 * Get 2FA status for current user
 */
async function handleGet(
  _request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<
  NextResponse<ApiSuccessResponse<TwoFactorStatusResponse> | ApiErrorResponse>
> {
  const userId = session.user?.id;
  if (!userId) {
    return errorResponse("UNAUTHORIZED", "User ID not found", { status: 401 });
  }

  const status = await getTwoFactorStatus(Number(userId));
  return successResponse(status);
}

/**
 * POST /api/user/two-factor
 * Handle 2FA operations: setup, enable, regenerate-codes
 * Query param: action (setup|enable|regenerate-codes)
 */
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<
  NextResponse<
    | ApiSuccessResponse<
        TwoFactorSetupResponse | TwoFactorEnableResponse | { backupCodes: string[] }
      >
    | ApiErrorResponse
  >
> {
  const userId = session.user?.id;
  const userEmail = session.user?.email;
  if (!userId || !userEmail) {
    return errorResponse("UNAUTHORIZED", "User ID or email not found", { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const action = searchParams.get("action") || "setup";

  if (action === "setup") {
    // Generate new secret and return QR code
    const secret = await generateTwoFactorSecret(Number(userId));
    const qrCode = await getTwoFactorQRCode(userEmail, secret);
    const manualEntryCode = getManualEntryCode(secret);

    return successResponse({
      qrCode,
      manualEntryCode,
    });
  }

  if (action === "enable") {
    const body = await request.json();
    const validation = enableTwoFactorSchema.safeParse(body);

    if (!validation.success) {
      return errorResponse("VALIDATION_ERROR", validation.error.issues[0].message, { status: 400 });
    }

    const result = await enableTwoFactor(Number(userId), validation.data.token);

    if (!result.success) {
      return errorResponse("VALIDATION_ERROR", "Invalid verification code", { status: 400 });
    }

    return successResponse({
      success: true,
      backupCodes: result.backupCodes,
    });
  }

  if (action === "regenerate-codes") {
    const body = await request.json();
    const validation = regenerateCodesSchema.safeParse(body);

    if (!validation.success) {
      return errorResponse("VALIDATION_ERROR", validation.error.issues[0].message, { status: 400 });
    }

    // Verify password before regenerating codes
    const isPasswordValid = await verifyUserPassword(Number(userId), validation.data.password);
    if (!isPasswordValid) {
      return errorResponse("UNAUTHORIZED", "Invalid password", { status: 401 });
    }

    const backupCodes = await regenerateBackupCodes(Number(userId));

    return successResponse({ backupCodes });
  }

  return errorResponse("VALIDATION_ERROR", "Invalid action", { status: 400 });
}

/**
 * DELETE /api/user/two-factor
 * Disable 2FA for current user
 */
async function handleDelete(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<{ success: boolean }> | ApiErrorResponse>> {
  const userId = session.user?.id;
  if (!userId) {
    return errorResponse("UNAUTHORIZED", "User ID not found", { status: 401 });
  }

  const body = await request.json();
  const validation = disableTwoFactorSchema.safeParse(body);

  if (!validation.success) {
    return errorResponse("VALIDATION_ERROR", validation.error.issues[0].message, { status: 400 });
  }

  // Verify password before disabling 2FA
  const isPasswordValid = await verifyUserPassword(Number(userId), validation.data.password);
  if (!isPasswordValid) {
    return errorResponse("UNAUTHORIZED", "Invalid password", { status: 401 });
  }

  await disableTwoFactor(Number(userId));

  return successResponse({ success: true });
}

export const GET = withErrorHandling(withAuth(handleGet));
export const POST = withErrorHandling(withAuth(handlePost));
export const DELETE = withErrorHandling(withAuth(handleDelete));