You've already forked Atomcms-edit
77 lines
1.9 KiB
PHP
Executable File
77 lines
1.9 KiB
PHP
Executable File
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Str;
|
|
|
|
class RadioApiKey extends Model
|
|
{
|
|
protected $fillable = [
|
|
'name',
|
|
'key',
|
|
'allowed_ips',
|
|
'permissions',
|
|
'rate_limit',
|
|
'expires_at',
|
|
'is_active',
|
|
];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'permissions' => 'array',
|
|
'is_active' => 'boolean',
|
|
'last_used_at' => 'datetime',
|
|
'expires_at' => 'datetime',
|
|
];
|
|
}
|
|
|
|
public static function generate(string $name, array $options = []): self
|
|
{
|
|
return static::create([
|
|
'name' => $name,
|
|
'key' => 'rad_' . Str::random(48),
|
|
'allowed_ips' => $options['allowed_ips'] ?? null,
|
|
'permissions' => $options['permissions'] ?? ['*'],
|
|
'rate_limit' => $options['rate_limit'] ?? 300,
|
|
'expires_at' => $options['expires_at'] ?? null,
|
|
'is_active' => true,
|
|
]);
|
|
}
|
|
|
|
public function scopeActive($query)
|
|
{
|
|
return $query->where('is_active', true)
|
|
->where(function ($q) {
|
|
$q->whereNull('expires_at')
|
|
->orWhere('expires_at', '>', now());
|
|
});
|
|
}
|
|
|
|
public function hasPermission(string $permission): bool
|
|
{
|
|
$permissions = $this->permissions ?? ['*'];
|
|
|
|
return in_array('*', $permissions, true) || in_array($permission, $permissions, true);
|
|
}
|
|
|
|
public function isAllowedIp(?string $ip): bool
|
|
{
|
|
if (empty($this->allowed_ips)) {
|
|
return true;
|
|
}
|
|
|
|
$allowed = array_map('trim', explode(',', $this->allowed_ips));
|
|
|
|
return in_array($ip, $allowed, true);
|
|
}
|
|
|
|
public function touchLastUsed(): void
|
|
{
|
|
$this->update(['last_used_at' => now()]);
|
|
}
|
|
}
|