new funcionality

This commit is contained in:
2026-07-27 17:20:02 +02:00
parent c2b5291a74
commit c5ce8a7a36
101 changed files with 6889 additions and 176 deletions

77
app/Models/AuditLog.php Normal file
View File

@@ -0,0 +1,77 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Http\Request;
#[Fillable(['actor_id', 'action', 'subject_type', 'subject_id', 'subject_label', 'metadata', 'ip_address', 'user_agent', 'created_at'])]
class AuditLog extends Model
{
const UPDATED_AT = null;
protected $casts = [
'metadata' => 'array',
];
public function actor(): BelongsTo
{
return $this->belongsTo(User::class, 'actor_id');
}
/**
* Listado paginado y filtrable — compartido por Admin\AuditLogController
* (sesión) y Api\AuditLogController (token), igual que AnalyticsSummary.
*/
public static function paginatedFor(Request $request)
{
$perPage = min(max((int) $request->integer('per_page', 25), 5), 100);
return self::query()
->with('actor:id,name,email')
->when($request->filled('action'), fn ($q) => $q->where('action', $request->string('action')))
->when($request->filled('subject_type'), fn ($q) => $q->where('subject_type', $request->string('subject_type')))
->latest('created_at')
->paginate($perPage)
->through(fn ($log) => [
'id' => $log->id,
'actor_name' => $log->actor?->name,
'actor_email' => $log->actor?->email,
'action' => $log->action,
'subject_type' => $log->subject_type,
'subject_id' => $log->subject_id,
'subject_label' => $log->subject_label,
'metadata' => $log->metadata,
'ip_address' => $log->ip_address,
'created_at' => $log->created_at,
]);
}
/**
* Registra un evento de auditoría. $subjectId se castea a string a propósito:
* cubre tanto ids autoincrementales (User) como uuid (Client) sin necesitar
* una relación polimórfica real (que mezclaría tipos de clave entre modelos).
*/
public static function record(
Request $request,
string $action,
string $subjectType,
int|string $subjectId,
?string $subjectLabel = null,
?array $metadata = null,
): void {
self::create([
'actor_id' => $request->user()?->id,
'action' => $action,
'subject_type' => $subjectType,
'subject_id' => (string) $subjectId,
'subject_label' => $subjectLabel,
'metadata' => $metadata,
'ip_address' => $request->ip(),
'user_agent' => $request->userAgent(),
'created_at' => now(),
]);
}
}

View File

@@ -3,11 +3,12 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Laravel\Passport\Client;
#[Fillable(['user_id', 'client_id', 'type', 'ip_address', 'user_agent', 'created_at'])]
#[Fillable(['user_id', 'client_id', 'type', 'outcome', 'ip_address', 'user_agent', 'created_at'])]
class LoginEvent extends Model
{
const UPDATED_AT = null;
@@ -21,4 +22,9 @@ class LoginEvent extends Model
{
return $this->belongsTo(Client::class);
}
public function scopeSuccessful(Builder $query): Builder
{
return $query->where('outcome', 'success');
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Laravel\Passport\Client;
#[Fillable(['user_id', 'client_id', 'outcome', 'scopes', 'ip_address', 'user_agent', 'created_at'])]
class OAuthAuthorizationEvent extends Model
{
const UPDATED_AT = null;
protected $table = 'oauth_authorization_events';
protected $casts = [
'scopes' => 'array',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function client(): BelongsTo
{
return $this->belongsTo(Client::class);
}
}

View File

@@ -3,6 +3,8 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Notifications\ResetPasswordNotification;
use App\Support\TwoFactorVerification;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -10,11 +12,13 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
#[Fillable(['name', 'email', 'password', 'is_active', 'approved_at'])]
#[Hidden(['password', 'remember_token'])]
#[Hidden(['password', 'remember_token', 'two_factor_secret', 'two_factor_recovery_codes'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
@@ -33,6 +37,9 @@ class User extends Authenticatable
'is_active' => 'boolean',
'deleted_at' => 'datetime',
'approved_at' => 'datetime',
'two_factor_secret' => 'encrypted',
'two_factor_recovery_codes' => 'encrypted:array',
'two_factor_confirmed_at' => 'datetime',
];
}
@@ -40,4 +47,41 @@ class User extends Authenticatable
{
return $this->approved_at === null;
}
public function hasTwoFactorEnabled(): bool
{
return $this->two_factor_confirmed_at !== null;
}
/**
* Hook que reconoce Passport\Bridge\UserRepository para el Password Grant.
* Sin esto, POST /oauth/token con grant_type=password sólo chequeaba la
* contraseña — un bypass real de 2FA si el usuario lo tenía activo para
* el login de sesión. Con 2FA activo exige además un campo "otp" (código
* TOTP o de recuperación) en el mismo request.
*/
public function validateForPassportPasswordGrant(string $password): bool
{
if (! Hash::check($password, $this->password)) {
return false;
}
if (! $this->hasTwoFactorEnabled()) {
return true;
}
$otp = request()->input('otp');
return is_string($otp) && $otp !== '' && TwoFactorVerification::verify($this, $otp);
}
/**
* Override del notification default de Laravel (en inglés, sin plantilla
* propia) — manda el email en el idioma de la sesión que originó el
* pedido, ver App\Notifications\ResetPasswordNotification.
*/
public function sendPasswordResetNotification($token): void
{
$this->notify(new ResetPasswordNotification($token, App::getLocale()));
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Http\Request;
#[Fillable(['webhook_endpoint_id', 'event', 'payload', 'response_status', 'response_body', 'attempts', 'delivered_at', 'created_at'])]
class WebhookDelivery extends Model
{
const UPDATED_AT = null;
protected $casts = [
'payload' => 'array',
'delivered_at' => 'datetime',
];
public function endpoint(): BelongsTo
{
return $this->belongsTo(WebhookEndpoint::class, 'webhook_endpoint_id');
}
/**
* Historial paginado de intentos de entrega de un webhook — compartido
* por OAuth\WebhookController (sesión) y Api\WebhookController (token),
* mismo patrón que AuditLog::paginatedFor.
*/
public static function paginatedFor(WebhookEndpoint $endpoint, Request $request)
{
$perPage = min(max((int) $request->integer('per_page', 15), 5), 100);
return self::where('webhook_endpoint_id', $endpoint->id)
->latest('created_at')
->paginate($perPage)
->through(fn (self $delivery) => [
'id' => $delivery->id,
'event' => $delivery->event,
'response_status' => $delivery->response_status,
'response_body' => $delivery->response_body,
'attempts' => $delivery->attempts,
'delivered_at' => $delivery->delivered_at,
'created_at' => $delivery->created_at,
]);
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Laravel\Passport\Client;
#[Fillable(['client_id', 'url', 'secret', 'events', 'active'])]
#[Hidden(['secret'])]
class WebhookEndpoint extends Model
{
protected $casts = [
'secret' => 'encrypted',
'events' => 'array',
'active' => 'boolean',
];
public function client(): BelongsTo
{
return $this->belongsTo(Client::class);
}
public function deliveries(): HasMany
{
return $this->hasMany(WebhookDelivery::class);
}
public function subscribesTo(string $event): bool
{
return $this->active && in_array($event, $this->events ?? [], true);
}
}