121 lines
2.8 KiB
PHP
121 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Database\Factories\WebhookEndpointFactory;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Concerns\HasUlids;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Support\Str;
|
|
|
|
class WebhookEndpoint extends Model
|
|
{
|
|
/** @use HasFactory<WebhookEndpointFactory> */
|
|
use HasFactory, HasUlids;
|
|
|
|
protected $fillable = [
|
|
'user_id',
|
|
'name',
|
|
'token',
|
|
'token_hash',
|
|
'is_public',
|
|
'is_active',
|
|
'expires_at',
|
|
'response_status',
|
|
'response_headers',
|
|
'response_body',
|
|
'last_request_at',
|
|
];
|
|
|
|
protected $hidden = [
|
|
'token',
|
|
'token_hash',
|
|
];
|
|
|
|
protected $attributes = [
|
|
'is_public' => true,
|
|
'is_active' => true,
|
|
'response_status' => 200,
|
|
'response_body' => '{}',
|
|
];
|
|
|
|
/**
|
|
* @return array<string, string>
|
|
*/
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'token' => 'encrypted',
|
|
'response_headers' => 'encrypted:array',
|
|
'is_public' => 'boolean',
|
|
'is_active' => 'boolean',
|
|
'expires_at' => 'datetime',
|
|
'last_request_at' => 'datetime',
|
|
'response_status' => 'integer',
|
|
];
|
|
}
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function requests(): HasMany
|
|
{
|
|
return $this->hasMany(WebhookRequest::class);
|
|
}
|
|
|
|
public function scopeOwnedBy(Builder $query, User $user): Builder
|
|
{
|
|
return $query->whereBelongsTo($user);
|
|
}
|
|
|
|
public function scopePublic(Builder $query): Builder
|
|
{
|
|
return $query->where('is_public', true);
|
|
}
|
|
|
|
public function scopeActive(Builder $query): Builder
|
|
{
|
|
return $query->where('is_active', true);
|
|
}
|
|
|
|
public static function tokenHash(string $token): string
|
|
{
|
|
return hash('sha256', $token);
|
|
}
|
|
|
|
public static function findByToken(string $token): ?self
|
|
{
|
|
return static::query()->where('token_hash', static::tokenHash($token))->first();
|
|
}
|
|
|
|
public function acceptsRequests(): bool
|
|
{
|
|
return $this->is_active && ! $this->isExpired();
|
|
}
|
|
|
|
public function isExpired(): bool
|
|
{
|
|
return $this->expires_at !== null && $this->expires_at->isPast();
|
|
}
|
|
|
|
public function publicUrl(): string
|
|
{
|
|
return route('inspect.show', ['token' => $this->token]);
|
|
}
|
|
|
|
public function webhookUrl(): string
|
|
{
|
|
return route('webhooks.receive', ['token' => $this->token]);
|
|
}
|
|
|
|
public static function generateToken(): string
|
|
{
|
|
return Str::random(48);
|
|
}
|
|
}
|