41 lines
1.2 KiB
PHP
41 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace Modules\Api\Models;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Support\Str;
|
|
|
|
final class ApiToken extends Model
|
|
{
|
|
protected $fillable = ['user_id', 'name', 'token', 'abilities', 'last_used_at', 'expires_at'];
|
|
|
|
protected $hidden = ['token'];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return ['abilities' => 'array', 'last_used_at' => 'datetime', 'expires_at' => 'datetime'];
|
|
}
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public static function issue(User $u, string $name, array $abilities = ['*'], ?\DateTimeInterface $expires = null): array
|
|
{
|
|
$plain = config('api.token_prefix', 'cms_').Str::random(64);
|
|
$record = self::query()->create(['user_id' => $u->id, 'name' => $name, 'token' => hash('sha256', $plain), 'abilities' => $abilities, 'expires_at' => $expires]);
|
|
|
|
return [$record, $plain];
|
|
}
|
|
|
|
public function allows(string $ability): bool
|
|
{
|
|
$a = $this->abilities ?: [];
|
|
|
|
return in_array('*', $a, true) || in_array($ability, $a, true);
|
|
}
|
|
}
|