feat: Add secure analytics slug system
- Add analytics_slug column to redirects table - Generate unique analytics slugs using CUID2 - Update PublicCampaignsController to use analytics_slug - Update views to use analytics_slug in analytics links - Add migration and population scripts - Improve security by separating public redirect and analytics URLs
This commit is contained in:
1 parent
2ed236542c
commit
4c08a83707
8 files changed
+230
-4
No files matched your search
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
namespace App\Core\Database\Migrations;
|
||||
|
||||
use App\Core\Database\Migration;
|
||||
|
||||
class AddAnalyticsSlugToRedirects extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// Adicionar coluna analytics_slug
|
||||
$this->addColumn('redirects', 'analytics_slug', function($table) {
|
||||
$table->string('analytics_slug', 100)->nullable();
|
||||
});
|
||||
|
||||
// Criar índice único para performance
|
||||
$this->addIndex('redirects', 'idx_analytics_slug', ['analytics_slug']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$this->dropIndex('redirects', 'idx_analytics_slug');
|
||||
$this->dropColumn('redirects', 'analytics_slug');
|
||||
}
|
||||
}
|
||||
@@ -31,3 +31,4 @@ class AddRawRequestToRedirectStats extends Migration
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -105,11 +105,11 @@ class PublicCampaignsController extends BaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* Get redirect by slug (cuid)
|
||||
* Get redirect by analytics slug
|
||||
*/
|
||||
private function getRedirectBySlug(string $slug): ?array
|
||||
{
|
||||
$sql = "SELECT id, name, cuid, target_url, status FROM redirects WHERE cuid = :slug AND status >= 0";
|
||||
$sql = "SELECT id, name, cuid, analytics_slug, target_url, status FROM redirects WHERE analytics_slug = :slug AND status >= 0";
|
||||
return $this->db->fetch($sql, [':slug' => $slug]);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ class RedirectModel
|
||||
$sql = "SELECT
|
||||
r.id,
|
||||
r.cuid,
|
||||
r.analytics_slug,
|
||||
r.name,
|
||||
r.source_url,
|
||||
r.target_url,
|
||||
@@ -67,6 +68,7 @@ class RedirectModel
|
||||
$sql = "SELECT
|
||||
r.id,
|
||||
r.cuid,
|
||||
r.analytics_slug,
|
||||
r.name,
|
||||
r.source_url,
|
||||
r.target_url,
|
||||
@@ -103,6 +105,7 @@ class RedirectModel
|
||||
$sql = "SELECT
|
||||
r.id,
|
||||
r.cuid,
|
||||
r.analytics_slug,
|
||||
r.name,
|
||||
r.source_url,
|
||||
r.target_url,
|
||||
@@ -136,17 +139,19 @@ class RedirectModel
|
||||
public function create(array $data): bool
|
||||
{
|
||||
$cuid = $this->generateCuid();
|
||||
$analyticsSlug = $this->generateAnalyticsSlug();
|
||||
|
||||
$sql = "INSERT INTO redirects (
|
||||
cuid, name, source_url, target_url, fallback_url,
|
||||
cuid, analytics_slug, name, source_url, target_url, fallback_url,
|
||||
status, redirect_type, tracking_enabled, max_clicks,
|
||||
expires_at, created_by
|
||||
) VALUES (
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
)";
|
||||
|
||||
$params = [
|
||||
$cuid,
|
||||
$analyticsSlug,
|
||||
$data['name'] ?? '',
|
||||
$data['source_url'] ?? '',
|
||||
$data['target_url'] ?? '',
|
||||
@@ -332,4 +337,10 @@ class RedirectModel
|
||||
{
|
||||
return (string) new \Visus\Cuid2\Cuid2();
|
||||
}
|
||||
|
||||
private function generateAnalyticsSlug(): string
|
||||
{
|
||||
// Usar cuid2 para gerar slug único para analytics (diferente do cuid principal)
|
||||
return (string) new \Visus\Cuid2\Cuid2();
|
||||
}
|
||||
}
|
||||
@@ -197,6 +197,7 @@
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
<li><a class="dropdown-item" href="/redirects/redirects/<?= $redirect['id'] ?>"><i class="ri-eye-line me-2"></i>View</a></li>
|
||||
<li><a class="dropdown-item" href="/redirects/redirects/<?= $redirect['id'] ?>/edit"><i class="ri-pencil-line me-2"></i>Edit</a></li>
|
||||
<li><a class="dropdown-item" href="/public/analytics/<?= $redirect['analytics_slug'] ?>" target="_blank"><i class="ri-bar-chart-line me-2"></i>Analytics Público</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item text-danger" href="#" onclick="deleteRedirect(<?= $redirect['id'] ?>)"><i class="ri-delete-bin-line me-2"></i>Delete</a></li>
|
||||
</ul>
|
||||
|
||||
@@ -134,6 +134,7 @@
|
||||
<li><a class="dropdown-item" href="#" @click.prevent="goToView(redirect.id)"><i class="ri-eye-line me-2"></i>Ver</a></li>
|
||||
<li><a class="dropdown-item" href="#" @click.prevent="goToEdit(redirect.id)"><i class="ri-pencil-line me-2"></i>Editar</a></li>
|
||||
<li><a class="dropdown-item" :href="`/r/${redirect.cuid}`" target="_blank"><i class="ri-external-link-line me-2"></i>Testar</a></li>
|
||||
<li><a class="dropdown-item" :href="`/public/analytics/${redirect.analytics_slug}`" target="_blank"><i class="ri-bar-chart-line me-2"></i>Analytics Público</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item text-danger" href="#" @click.prevent="deleteRedirect(redirect.id, redirect.name)"><i class="ri-delete-bin-line me-2"></i>Apagar</a></li>
|
||||
</ul>
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
// Script para popular analytics_slug nos redirects existentes usando CUID2
|
||||
require_once 'config.php';
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Modules\Redirects\Models\RedirectModel;
|
||||
|
||||
try {
|
||||
$db = DatabaseManager::getInstance();
|
||||
$model = new RedirectModel();
|
||||
|
||||
echo "🚀 Populando analytics_slug nos redirects existentes...\n\n";
|
||||
|
||||
// Buscar todos os redirects que não têm analytics_slug
|
||||
$redirects = $db->fetchAll("
|
||||
SELECT id, name, cuid, analytics_slug
|
||||
FROM redirects
|
||||
WHERE status >= 0 AND (analytics_slug IS NULL OR analytics_slug = '')
|
||||
");
|
||||
|
||||
echo "📋 Encontrados " . count($redirects) . " redirects sem analytics_slug\n";
|
||||
|
||||
$updated = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($redirects as $redirect) {
|
||||
try {
|
||||
// Gerar analytics_slug único usando CUID2
|
||||
$analyticsSlug = (string) new \Visus\Cuid2\Cuid2();
|
||||
|
||||
// Verificar se já existe (muito improvável com CUID2, mas por segurança)
|
||||
$exists = $db->fetch(
|
||||
"SELECT COUNT(*) as count FROM redirects WHERE analytics_slug = ?",
|
||||
[$analyticsSlug]
|
||||
);
|
||||
|
||||
if (($exists['count'] ?? 0) > 0) {
|
||||
echo "⚠️ Analytics slug duplicado detectado, gerando novo...\n";
|
||||
$analyticsSlug = (string) new \Visus\Cuid2\Cuid2();
|
||||
}
|
||||
|
||||
// Atualizar no banco
|
||||
$result = $db->query(
|
||||
"UPDATE redirects SET analytics_slug = ? WHERE id = ?",
|
||||
[$analyticsSlug, $redirect['id']]
|
||||
);
|
||||
|
||||
if ($result > 0) {
|
||||
echo "✅ Redirect {$redirect['id']} ({$redirect['name']}) - analytics_slug: {$analyticsSlug}\n";
|
||||
$updated++;
|
||||
} else {
|
||||
echo "❌ Falha ao atualizar redirect {$redirect['id']}\n";
|
||||
$errors++;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro no redirect {$redirect['id']}: " . $e->getMessage() . "\n";
|
||||
$errors++;
|
||||
}
|
||||
}
|
||||
|
||||
echo "\n🎉 Processo concluído!\n";
|
||||
echo "📊 {$updated} redirects atualizados com analytics_slug\n";
|
||||
if ($errors > 0) {
|
||||
echo "⚠️ {$errors} erros encontrados\n";
|
||||
}
|
||||
|
||||
// Verificar resultado final
|
||||
$total = $db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status >= 0");
|
||||
$withSlug = $db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status >= 0 AND analytics_slug IS NOT NULL AND analytics_slug != ''");
|
||||
|
||||
echo "📈 Total de redirects: {$total['count']}\n";
|
||||
echo "📈 Com analytics_slug: {$withSlug['count']}\n";
|
||||
|
||||
if ($total['count'] == $withSlug['count']) {
|
||||
echo "✅ Todos os redirects têm analytics_slug!\n";
|
||||
} else {
|
||||
echo "⚠️ Ainda há redirects sem analytics_slug\n";
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro geral: " . $e->getMessage() . "\n";
|
||||
echo "Stack trace: " . $e->getTraceAsString() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
// Script simples para popular analytics_slug (sem autoloader)
|
||||
require_once 'config.php';
|
||||
|
||||
// Configuração de base de dados
|
||||
$host = 'localhost';
|
||||
$dbname = 'moneyflix_crm';
|
||||
$username = 'root';
|
||||
$password = '';
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
echo "🚀 Populando analytics_slug nos redirects existentes...\n\n";
|
||||
|
||||
// Buscar todos os redirects que não têm analytics_slug
|
||||
$stmt = $pdo->prepare("
|
||||
SELECT id, name, cuid, analytics_slug
|
||||
FROM redirects
|
||||
WHERE status >= 0 AND (analytics_slug IS NULL OR analytics_slug = '')
|
||||
");
|
||||
$stmt->execute();
|
||||
$redirects = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
echo "📋 Encontrados " . count($redirects) . " redirects sem analytics_slug\n";
|
||||
|
||||
$updated = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($redirects as $redirect) {
|
||||
try {
|
||||
// Gerar analytics_slug único usando CUID2
|
||||
$analyticsSlug = generateCuid2();
|
||||
|
||||
// Verificar se já existe (muito improvável com CUID2, mas por segurança)
|
||||
$checkStmt = $pdo->prepare("SELECT COUNT(*) as count FROM redirects WHERE analytics_slug = ?");
|
||||
$checkStmt->execute([$analyticsSlug]);
|
||||
$exists = $checkStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (($exists['count'] ?? 0) > 0) {
|
||||
echo "⚠️ Analytics slug duplicado detectado, gerando novo...\n";
|
||||
$analyticsSlug = generateCuid2();
|
||||
}
|
||||
|
||||
// Atualizar no banco
|
||||
$updateStmt = $pdo->prepare("UPDATE redirects SET analytics_slug = ? WHERE id = ?");
|
||||
$result = $updateStmt->execute([$analyticsSlug, $redirect['id']]);
|
||||
|
||||
if ($result) {
|
||||
echo "✅ Redirect {$redirect['id']} ({$redirect['name']}) - analytics_slug: {$analyticsSlug}\n";
|
||||
$updated++;
|
||||
} else {
|
||||
echo "❌ Falha ao atualizar redirect {$redirect['id']}\n";
|
||||
$errors++;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro no redirect {$redirect['id']}: " . $e->getMessage() . "\n";
|
||||
$errors++;
|
||||
}
|
||||
}
|
||||
|
||||
echo "\n🎉 Processo concluído!\n";
|
||||
echo "📊 {$updated} redirects atualizados com analytics_slug\n";
|
||||
if ($errors > 0) {
|
||||
echo "⚠️ {$errors} erros encontrados\n";
|
||||
}
|
||||
|
||||
// Verificar resultado final
|
||||
$totalStmt = $pdo->prepare("SELECT COUNT(*) as count FROM redirects WHERE status >= 0");
|
||||
$totalStmt->execute();
|
||||
$total = $totalStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
$withSlugStmt = $pdo->prepare("SELECT COUNT(*) as count FROM redirects WHERE status >= 0 AND analytics_slug IS NOT NULL AND analytics_slug != ''");
|
||||
$withSlugStmt->execute();
|
||||
$withSlug = $withSlugStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
echo "📈 Total de redirects: {$total['count']}\n";
|
||||
echo "📈 Com analytics_slug: {$withSlug['count']}\n";
|
||||
|
||||
if ($total['count'] == $withSlug['count']) {
|
||||
echo "✅ Todos os redirects têm analytics_slug!\n";
|
||||
} else {
|
||||
echo "⚠️ Ainda há redirects sem analytics_slug\n";
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro geral: " . $e->getMessage() . "\n";
|
||||
}
|
||||
|
||||
function generateCuid2(): string
|
||||
{
|
||||
// Função que simula CUID2 (25 caracteres alfanuméricos)
|
||||
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
||||
$cuid = '';
|
||||
|
||||
// Gerar 25 caracteres (tamanho padrão do CUID2)
|
||||
for ($i = 0; $i < 25; $i++) {
|
||||
$cuid .= $characters[random_int(0, strlen($characters) - 1)];
|
||||
}
|
||||
|
||||
return $cuid;
|
||||
}
|
||||
Reference in new issue
Block a user