Skip to content

Commit

Permalink
add: notification in user model when a user is delete,create and update
Browse files Browse the repository at this point in the history
  • Loading branch information
alejandro-velasquez committed Nov 25, 2024
1 parent 4e918fc commit c1195ee
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 69 deletions.
17 changes: 3 additions & 14 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace App\Exceptions;

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

class Handler extends ExceptionHandler
Expand All @@ -29,20 +29,9 @@ public function report(Throwable $exception)
{
parent::report($exception);

if ($this->shouldReportToDiscord($exception)) {
// Reporta la excepción a Discord si debe reportarse
if ($this->shouldReport($exception)) {
DiscordNotifier::notifyException($exception);
}
}

/**
* Determina si la excepción debe reportarse a Discord.
*
* @param \Throwable $exception
* @return bool
*/
protected function shouldReportToDiscord(Throwable $exception): bool
{
// Filtrar excepciones no reportables
return !$this->shouldntReport($exception);
}
}
53 changes: 40 additions & 13 deletions app/Helpers/DiscordNotifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,60 @@

class DiscordNotifier
{
protected static $webhookUrl = 'https://discord.com/api/webhooks/1310023183461646406/m4tupDKnQ05qMoUs8eARIYzg0v2rLjTB1Degz98JQrOzWy2Z5mALup4RQOQlH3kC_o__';

public static function send($message)
{
if (self::$webhookUrl) {
Http::post(self::$webhookUrl, [
$webhookUrl = env('DISCORD_WEBHOOK_URL');

if ($webhookUrl) {
Http::post($webhookUrl, [
'content' => $message,
]);
}
}

public static function notifyException(\Throwable $exception)
{
$trace = substr($exception->getTraceAsString(), 0, 1800); // Límite ajustado para Discord
$message = "**Exception Alert**\n"
. "**Message:** {$exception->getMessage()}\n"
. "**File:** {$exception->getFile()}:{$exception->getLine()}\n"
. "**Trace:** ```{$exception->getTraceAsString()}```";
. "**Trace:** ```{$trace}```";

self::send($message);
}

public static function notifyEvent($eventType, $details = [])
{
$message = "**Event Notification**\n"
. "**Type:** {$eventType}\n"
. "**Details:** " . json_encode($details, JSON_PRETTY_PRINT);

self::send($message);
public static function notifyEvent($eventType, $details = [])
{
$webhookUrl = env('DISCORD_WEBHOOK_URL');

if ($webhookUrl) {
$logoUrl = 'https://755e-186-113-97-221.ngrok-free.app/gananza-logov1.png';
$embed = [
'title' => '🔔 Gananza Alerts',
'description' => "Se ha detectado un evento: **{$eventType}**.",
'color' => 7506394, // Color (ejemplo: azul)
'fields' => [],
'footer' => [
'text' => 'Notificaciones del Sistema',
'icon_url' => $logoUrl, // Cambiar al logo de tu sitio
],
'timestamp' => now()->toIso8601String(),
];

// Añadir los detalles al mensaje si están disponibles
foreach ($details as $key => $value) {
$embed['fields'][] = [
'name' => ucfirst($key),
'value' => $value,
'inline' => true,
];
}

Http::post($webhookUrl, [
'embeds' => [$embed],
'username' => 'Sistema de Notificaciones', // Nombre personalizado
'avatar_url' => $logoUrl, // Cambiar al logo de tu sitio
]);
}
}
}
9 changes: 8 additions & 1 deletion config/telescope.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
],

'ignore_commands' => [
//
'http:post https://discord.com/api/webhooks/*',
],

/*
Expand Down Expand Up @@ -204,4 +204,11 @@
Watchers\ScheduleWatcher::class => env('TELESCOPE_SCHEDULE_WATCHER', true),
Watchers\ViewWatcher::class => env('TELESCOPE_VIEW_WATCHER', true),
],

'filter' => [
'type' => [
Illuminate\Http\Client\RequestException::class,
Symfony\Component\HttpKernel\Exception\HttpException::class,
],
],
];
Binary file added public/gananza-logov1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
60 changes: 19 additions & 41 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\PaymentVerificationController;
use App\Http\Middleware\AdminPasswordVerification;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use App\Models\User;
use Illuminate\Auth\Middleware\Authorize;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use Laravel\Telescope\Telescope;
use Modules\Raffle\Http\Controllers\RaffleController;
use Modules\Ticket\Http\Controllers\TicketController;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

// Ruta pública
Route::get('/', function () {
Expand All @@ -26,44 +25,23 @@
'phpVersion' => PHP_VERSION,
]);
});
Route::get('/test-exception', function () {
throw new Exception("Esto es una prueba de excepción para Discord.");
});

Route::get('/test-discord', function () {
\App\Helpers\DiscordNotifier::send("Prueba directa de notificación a Discord.");
return "Mensaje enviado.";
});

Route::get('/test-missing-user', function () {
// Lanzará ModelNotFoundException
return User::findOrFail(99999);
});

// Grupo de rutas para testing con prefijo /test-error
Route::prefix('test-error')->group(function () {
// Error 403 - Forbidden
Route::get('/403', function () {
throw new AccessDeniedHttpException('USER DOES NOT HAVE THE RIGHT ROLES.');
})->name('test.403');

// Error 401 - Unauthorized
Route::get('/401', function () {
throw new AuthenticationException('Usuario no autenticado');
})->name('test.401');

// Error 404 - Not Found
Route::get('/404', function () {
throw new NotFoundHttpException('Recurso no encontrado');
})->name('test.404');

// Error 500 - Server Error
Route::get('/500', function () {
throw new \Exception('Error interno del servidor');
})->name('test.500');

// Error de Autorización (también 403)
Route::get('/forbidden', function () {
throw new AuthorizationException('No tienes permiso para realizar esta acción');
})->name('test.forbidden');

// Error personalizado
Route::get('/custom', function () {
$errorMessage = [
'error' => 'Error personalizado',
'details' => 'Detalles adicionales del error',
'timestamp' => now()->toIso8601String(),
];

throw new \Exception(json_encode($errorMessage));
})->name('test.custom');
Route::get('/test-sql-error', function () {
// Lanzará QueryException
return DB::table('non_existent_table')->get();
});

// Grupo de rutas autenticadas
Expand Down

0 comments on commit c1195ee

Please sign in to comment.