Skip to content

Commit

Permalink
Merge pull request #78 from Crudzaso/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
DiegoAndresRamirez authored Nov 29, 2024
2 parents e49b4bc + 8ede8c3 commit af28c88
Show file tree
Hide file tree
Showing 14 changed files with 268 additions and 87 deletions.
49 changes: 49 additions & 0 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace App\Exceptions;

use Throwable;
use App\Helpers\DiscordNotifier;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
protected $dontReport = [
\Illuminate\Validation\ValidationException::class,
\Illuminate\Session\TokenMismatchException::class,
];

public function report(Throwable $exception)
{
// Notifica a Discord si no está en la lista de exclusión
if ($this->shouldReport($exception)) {
try {
$this->notifyDiscord($exception);
} catch (Throwable $e) {
// Evitar que fallos en la notificación rompan el flujo
logger()->error("Error al enviar notificación a Discord: " . $e->getMessage());
}
}

parent::report($exception);
}

protected function notifyDiscord(Throwable $exception)
{
$details = [
'message' => $exception->getMessage(),
'file' => "{$exception->getFile()}:{$exception->getLine()}",
'trace' => substr($exception->getTraceAsString(), 0, 1800),
];

// Logea el error antes de enviarlo a Discord
logger()->error('Excepción capturada', $details);

// Envía la notificación a Discord
DiscordNotifier::notifyEvent(
'Excepción en el sistema 🚨',
$details,
asset('images/logo.png')
);
}
}
67 changes: 67 additions & 0 deletions app/Helpers/DiscordNotifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Http;

class DiscordNotifier
{
public static function send($message, $embed = [])
{
$webhookUrl = env('DISCORD_WEBHOOK_URL');

if ($webhookUrl) {
$payload = [
'content' => $message,
];

if (!empty($embed)) {
$payload['embeds'] = [$embed];
}

Http::post($webhookUrl, $payload);
}
}

public static function notifyException(\Throwable $exception)
{
$trace = substr($exception->getTraceAsString(), 0, 1800); // Discord tiene límites.
$message = "**🚨 Exception Alert**\n"
. "**Mensaje:** {$exception->getMessage()}\n"
. "**Archivo:** {$exception->getFile()}:{$exception->getLine()}\n"
. "**Trace:** ```{$trace}```";

self::send($message);
}

public static function notifyEvent($eventType, $details = [], $imageUrl = null)
{
$webhookUrl = env('DISCORD_WEBHOOK_URL');

if ($webhookUrl) {
$logoUrl = $imageUrl ?? asset('logo.png'); // Imagen por defecto
$embed = [
'title' => '🔔 Notificación del Sistema',
'description' => "Se ha detectado un evento: **{$eventType}**.",
'color' => 7506394, // Color (hex: #72A0C1)
'fields' => [],
'footer' => [
'text' => 'Notificaciones del Sistema',
'icon_url' => $logoUrl,
],
'timestamp' => now()->toIso8601String(),
];

// Agregar detalles al mensaje.
foreach ($details as $key => $value) {
$embed['fields'][] = [
'name' => ucfirst($key),
'value' => $value,
'inline' => true,
];
}

self::send('', $embed);
}
}
}
30 changes: 30 additions & 0 deletions app/Http/Middleware/HandleExceptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Throwable;
use App\Helpers\DiscordNotifier;

class HandleExceptions
{
public function handle($request, Closure $next)
{
try {
return $next($request);
} catch (Throwable $e) {
$this->reportToDiscord($e); // Enviar notificación a Discord
throw $e; // Rethrow para permitir que el sistema maneje la excepción
}
}

protected function reportToDiscord(Throwable $exception)
{
$message = "**🚨 Excepción Crítica**\n"
. "**Mensaje:** {$exception->getMessage()}\n"
. "**Archivo:** {$exception->getFile()}:{$exception->getLine()}\n"
. "**Trace:** ```" . substr($exception->getTraceAsString(), 0, 1800) . "```";

DiscordNotifier::send($message);
}
}
23 changes: 23 additions & 0 deletions app/Listeners/SendLoginNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use App\Helpers\DiscordNotifier;

class SendLoginNotification
{
/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event)
{
DiscordNotifier::notifyEvent('User Logged In', [
'user_id' => $event->user->id,
'email' => $event->user->email,
]);
}
}
46 changes: 46 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Models;

use App\Helpers\DiscordNotifier;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
Expand Down Expand Up @@ -51,5 +52,50 @@ public function routeNotificationForWebhook()
return env('DISCORD_WEBHOOK_URL');
}

protected static function boot()
{
parent::boot();

// Evento cuando el modelo es creado
static::created(function ($model) {
$createdBy = auth()->user();
DiscordNotifier::notifyEvent('Usuario Creado', [
'ID Usuario Creado' => $model->id,
'Nombre Usuario Creado' => $model->name,
'ID Quien Creó' => $createdBy->id ?? 'Desconocido',
'Nombre Quien Creó' => $createdBy->name ?? 'Desconocido',
],
asset('images/logo.png')
);
});

// Evento cuando el modelo es actualizado
static::updated(function ($model) {
DiscordNotifier::notifyEvent('Usuario actualizado', [
'ID Usuario Actualizado' => $model->id,
'Nombre Usuario Actualizado' => $model->name,
'Cambios Realizados' => json_encode($model->getChanges()), // Cambios realizados en formato JSON
'ID Quien Actualizó' => $updatedBy->id ?? 'Desconocido',
'Nombre Quien Actualizó' => $updatedBy->name ?? 'Desconocido',
],
asset('images/logo.png')
);
});

// Evento cuando el modelo es eliminado
static::deleted(function ($model) {
$deletedBy = auth()->user(); // Usuario autenticado
DiscordNotifier::notifyEvent(
'Usuario Borrado',
[
'ID Usuario Eliminado' => $model->id,
'Nombre Usuario Eliminado' => $model->name,
'ID Quien Eliminó' => $deletedBy->id ?? 'Desconocido',
'Nombre Quien Eliminó' => $deletedBy->name ?? 'Desconocido',
],
asset('images/logo.png') // Ruta de imagen pública
);
});
}

}
22 changes: 0 additions & 22 deletions app/Notifications/Channels/DiscordChannel.php

This file was deleted.

62 changes: 0 additions & 62 deletions app/Notifications/DiscordNotification.php

This file was deleted.

31 changes: 31 additions & 0 deletions app/Providers/EventServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\Providers;

use Illuminate\Auth\Events\Login;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\Listeners\SendLoginNotification;

class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Login::class => [
SendLoginNotification::class,
],
];

/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
}
}
1 change: 1 addition & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
$middleware->web(append: [
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
\App\Http\Middleware\HandleExceptions::class,
]);

// Registra los alias de los middlewares de Spatie
Expand Down
1 change: 1 addition & 0 deletions bootstrap/providers.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

return [
App\Providers\AppServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\Filament\AdminPanelProvider::class,
App\Providers\FortifyServiceProvider::class,
App\Providers\JetstreamServiceProvider::class,
Expand Down
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,16 @@
"pestphp/pest": "^3.5",
"pestphp/pest-plugin-laravel": "^3.0"
},

"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"files": [
"app/Helpers/DiscordNotifier.php"
]
},
"autoload-dev": {
"psr-4": {
Expand Down
Loading

0 comments on commit af28c88

Please sign in to comment.