Lint / PHP (phpcs PSR-12) (push) Successful in 38s
Lint / JS (eslint) (push) Successful in 15s
Lint / PHP requirements (version + extensions) (push) Successful in 38s
Lint / Notify on failure (push) Skipped
Security / PHP Security (semgrep) (push) Successful in 1m27s
Lint / Deploy (push) Successful in 2s
api/bootstrap.php's centralized CSRF handling echoes CsrfMiddleware::getToken() on a 403 rejection specifically so lt.api's client-side resync (assets/js/base.js) can recover once window.CSRF_TOKEN goes stale (token expiry, or a write in another tab rotating the shared session-scoped token). 12 endpoints duplicate CsrfMiddleware::validateToken() inline instead of routing through bootstrap.php, and their 403 body omitted csrf_token entirely — custom_fields.php, clone_ticket.php, delete_comment.php, delete_attachment.php, bulk_operation.php, generate_api_key.php, manage_templates.php, manage_recurring.php, revoke_api_key.php, manage_workflows.php, ticket_dependencies.php, and upload_attachment.php. Once a client's token drifted out of sync, the next write to any of these 12 endpoints returned a 403 with no way to self-heal — every subsequent write to any endpoint kept failing until a manual reload, since the resync mechanism was only wired up on a minority of the app's write surface. Took the minimal fix the issue names as sufficient (add 'csrf_token' => CsrfMiddleware::getToken() to each rejection body) rather than restructuring all 12 through bootstrap.php, to avoid behavioral risk from rewiring each endpoint's differing auth/bootstrapping. generate_api_key.php and revoke_api_key.php threw a generic Exception for this case (swallowed into a plain error-message response with no room for extra fields), so those two now short-circuit with a direct JSON response instead, matching the other 10. Verified end-to-end against real running endpoints with a real session and real MariaDB: sent a wrong CSRF token to one endpoint of each response shape (plain json_encode, ResponseHelper::error, and the formerly exception-based path) and confirmed all three now return the current valid csrf_token in the 403 body. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lhz7pGMaoTfL5sdYS5XiKv
219 lines
9.0 KiB
PHP
219 lines
9.0 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Template Management API
|
|
* CRUD operations for ticket_templates table
|
|
*/
|
|
|
|
ini_set('display_errors', 0);
|
|
error_reporting(E_ALL);
|
|
|
|
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
|
|
RateLimitMiddleware::apply('api');
|
|
|
|
try {
|
|
require_once dirname(__DIR__) . '/config/config.php';
|
|
require_once dirname(__DIR__) . '/helpers/Database.php';
|
|
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
|
|
|
|
// Check authentication
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'error' => 'Authentication required']);
|
|
exit;
|
|
}
|
|
|
|
// Check admin privileges for write operations
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'GET' && !$_SESSION['user']['is_admin']) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'error' => 'Admin privileges required']);
|
|
exit;
|
|
}
|
|
|
|
// CSRF Protection for write operations
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
|
|
require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php';
|
|
$csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
|
|
if (!CsrfMiddleware::validateToken($csrfToken)) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'error' => 'Invalid CSRF token', 'csrf_token' => CsrfMiddleware::getToken()]);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
// Use centralized database connection
|
|
$conn = Database::getConnection();
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$auditLog = new AuditLogModel($conn);
|
|
$currentUserId = $_SESSION['user']['user_id'];
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
|
|
|
|
switch ($method) {
|
|
case 'GET':
|
|
if ($id) {
|
|
// Get single template
|
|
$stmt = $conn->prepare("SELECT * FROM ticket_templates WHERE template_id = ?");
|
|
$stmt->bind_param('i', $id);
|
|
$stmt->execute();
|
|
$result = $stmt->get_result();
|
|
$template = $result->fetch_assoc();
|
|
$stmt->close();
|
|
echo json_encode(['success' => true, 'template' => $template]);
|
|
} else {
|
|
// Get all templates
|
|
$result = $conn->query("SELECT * FROM ticket_templates ORDER BY template_name");
|
|
$templates = [];
|
|
while ($row = $result->fetch_assoc()) {
|
|
$templates[] = $row;
|
|
}
|
|
echo json_encode(['success' => true, 'templates' => $templates]);
|
|
}
|
|
break;
|
|
|
|
case 'POST':
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
// Validate required fields and lengths
|
|
$templateName = trim($data['template_name'] ?? '');
|
|
$titleTemplate = trim($data['title_template'] ?? '');
|
|
if (!$templateName || mb_strlen($templateName) > 100) {
|
|
echo json_encode(['success' => false, 'error' => 'Template name is required (max 100 chars)']);
|
|
exit;
|
|
}
|
|
if (!$titleTemplate || mb_strlen($titleTemplate) > 255) {
|
|
echo json_encode(['success' => false, 'error' => 'Title template is required (max 255 chars)']);
|
|
exit;
|
|
}
|
|
$allowedCategories = ['General','Hardware','Software','Network','Security'];
|
|
$allowedTypes = ['Issue','Maintenance','Install','Task','Upgrade','Problem'];
|
|
$category = in_array($data['category'] ?? '', $allowedCategories) ? $data['category'] : 'General';
|
|
$type = in_array($data['type'] ?? '', $allowedTypes) ? $data['type'] : 'Issue';
|
|
$priority = max(1, min(5, (int)($data['default_priority'] ?? 4)));
|
|
$isActive = $data['is_active'] ? 1 : 0;
|
|
$description = mb_substr($data['description_template'] ?? '', 0, 65535);
|
|
|
|
$stmt = $conn->prepare("INSERT INTO ticket_templates
|
|
(template_name, title_template, description_template, category, type, default_priority, is_active)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)");
|
|
$stmt->bind_param(
|
|
'sssssii',
|
|
$templateName,
|
|
$titleTemplate,
|
|
$description,
|
|
$category,
|
|
$type,
|
|
$priority,
|
|
$isActive
|
|
);
|
|
|
|
if ($stmt->execute()) {
|
|
$newTemplateId = $conn->insert_id;
|
|
$auditLog->log($currentUserId, 'create', 'template', (string)$newTemplateId, [
|
|
'template_name' => $templateName,
|
|
'category' => $category,
|
|
'type' => $type
|
|
]);
|
|
echo json_encode(['success' => true, 'template_id' => $newTemplateId]);
|
|
} else {
|
|
error_log("Template creation failed: " . $stmt->error);
|
|
echo json_encode(['success' => false, 'error' => 'Failed to create template']);
|
|
}
|
|
$stmt->close();
|
|
break;
|
|
|
|
case 'PUT':
|
|
if (!$id) {
|
|
echo json_encode(['success' => false, 'error' => 'ID required']);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
// Validate required fields and lengths
|
|
$templateName = trim($data['template_name'] ?? '');
|
|
$titleTemplate = trim($data['title_template'] ?? '');
|
|
if (!$templateName || mb_strlen($templateName) > 100) {
|
|
echo json_encode(['success' => false, 'error' => 'Template name is required (max 100 chars)']);
|
|
exit;
|
|
}
|
|
if (!$titleTemplate || mb_strlen($titleTemplate) > 255) {
|
|
echo json_encode(['success' => false, 'error' => 'Title template is required (max 255 chars)']);
|
|
exit;
|
|
}
|
|
$allowedCategories = ['General','Hardware','Software','Network','Security'];
|
|
$allowedTypes = ['Issue','Maintenance','Install','Task','Upgrade','Problem'];
|
|
$category = in_array($data['category'] ?? '', $allowedCategories) ? $data['category'] : 'General';
|
|
$type = in_array($data['type'] ?? '', $allowedTypes) ? $data['type'] : 'Issue';
|
|
$priority = max(1, min(5, (int)($data['default_priority'] ?? 4)));
|
|
$isActive = $data['is_active'] ? 1 : 0;
|
|
$description = mb_substr($data['description_template'] ?? '', 0, 65535);
|
|
|
|
$stmt = $conn->prepare("UPDATE ticket_templates SET
|
|
template_name = ?, title_template = ?, description_template = ?,
|
|
category = ?, type = ?, default_priority = ?, is_active = ?
|
|
WHERE template_id = ?");
|
|
$stmt->bind_param(
|
|
'sssssiii',
|
|
$templateName,
|
|
$titleTemplate,
|
|
$description,
|
|
$category,
|
|
$type,
|
|
$priority,
|
|
$isActive,
|
|
$id
|
|
);
|
|
|
|
$updated = $stmt->execute();
|
|
if ($updated) {
|
|
$auditLog->log($currentUserId, 'update', 'template', (string)$id, [
|
|
'template_name' => $templateName,
|
|
'category' => $category,
|
|
'type' => $type
|
|
]);
|
|
}
|
|
echo json_encode(['success' => $updated]);
|
|
$stmt->close();
|
|
break;
|
|
|
|
case 'DELETE':
|
|
if (!$id) {
|
|
echo json_encode(['success' => false, 'error' => 'ID required']);
|
|
exit;
|
|
}
|
|
|
|
// Capture the name before deletion for the audit record.
|
|
$nameStmt = $conn->prepare("SELECT template_name FROM ticket_templates WHERE template_id = ?");
|
|
$nameStmt->bind_param('i', $id);
|
|
$nameStmt->execute();
|
|
$delRow = $nameStmt->get_result()->fetch_assoc();
|
|
$nameStmt->close();
|
|
|
|
$stmt = $conn->prepare("DELETE FROM ticket_templates WHERE template_id = ?");
|
|
$stmt->bind_param('i', $id);
|
|
$deleted = $stmt->execute();
|
|
if ($deleted) {
|
|
$auditLog->log($currentUserId, 'delete', 'template', (string)$id, [
|
|
'template_name' => $delRow['template_name'] ?? 'unknown'
|
|
]);
|
|
}
|
|
echo json_encode(['success' => $deleted]);
|
|
$stmt->close();
|
|
break;
|
|
|
|
default:
|
|
http_response_code(405);
|
|
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
|
|
}
|
|
} catch (Exception $e) {
|
|
error_log("Template API error: " . $e->getMessage());
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'error' => 'An internal error occurred']);
|
|
}
|