false, 'message' => 'Invalid request method.'], 405); } // Check if the user is logged in require_logged_in(); // Include database configuration include "../../config/config.php"; include "../utils/create_key.php"; include "../utils/generate_pin.php"; // Create a new database connection $conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE); // Check for database connection errors if ($conn->connect_error) { echo json_encode([ 'success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error ]); exit(); } // Get the logged-in user's ID and username from the session $id = $_SESSION["id"]; $username = $_SESSION["username"]; // Get the raw POST data (JSON) $data = json_decode(file_get_contents("php://input")); if(!isset($data->enable_2fa) || !is_bool($data->enable_2fa)){ echo json_encode(['success' => false, 'message' => 'Missing required fields.']); exit(); } if($data->enable_2fa==true){ $twofa_pin = trim((string)($data->twofa_pin ?? "")); if ($twofa_pin === "") { $twofa_secret=generateBase32Secret(); $_SESSION["pending_2fa_secret"]=$twofa_secret; echo json_encode(['success' => true, 'pending' => true, 'message' => 'Scan this QR code, then enter the current 2FA code to confirm enrollment.', 'token' => $twofa_secret]); exit(); } check_rate_limit($conn, 'setup_2fa', 5, 10 * 60, (string)$id); $twofa_secret = $_SESSION["pending_2fa_secret"] ?? ""; if ($twofa_secret === "" || !hash_equals(generateTOTP($twofa_secret), $twofa_pin)) { echo json_encode(['success' => false, 'message' => 'Invalid 2FA code.']); exit(); } $sql="UPDATE users SET 2fa = ?, auth_method_enabled_2fa = 1, auth_method_required_2fa = 1 WHERE id = ?"; if ($update_stmt = $conn->prepare($sql)) { $update_stmt->bind_param("si", $twofa_secret, $id); if ($update_stmt->execute()) { unset($_SESSION["pending_2fa_secret"]); clear_rate_limit($conn, 'setup_2fa', (string)$id); echo json_encode(['success' => true, 'message' => '2FA enabled.']); } else { echo json_encode(['success' => false, 'message' => 'Failed to enable 2fa.']); } $update_stmt->close(); } else { echo json_encode(['success' => false, 'message' => 'Database error.']); } } if($data->enable_2fa==false){ unset($_SESSION["pending_2fa_secret"]); $sql="UPDATE users SET 2fa = '', auth_method_enabled_2fa = 0, auth_method_required_2fa = 0 WHERE id = ?"; if ($update_stmt = $conn->prepare($sql)) { $update_stmt->bind_param("i",$id); if ($update_stmt->execute()) { echo json_encode(['success' => true, 'message' => '2FA disabled.']); } else { echo json_encode(['success' => false, 'message' => 'Failed to disable 2fa.']); } $update_stmt->close(); } else { echo json_encode(['success' => false, 'message' => 'Database error.']); } } ?>