coolify/app/Livewire/Security/ApiTokens.php

75 lines
1.9 KiB
PHP
Raw Normal View History

2023-10-20 12:51:01 +00:00
<?php
2023-12-07 18:06:32 +00:00
namespace App\Livewire\Security;
2023-10-20 12:51:01 +00:00
use App\Models\InstanceSettings;
2023-10-20 12:51:01 +00:00
use Livewire\Component;
class ApiTokens extends Component
{
public ?string $description = null;
2024-06-10 20:43:34 +00:00
2023-10-20 12:51:01 +00:00
public $tokens = [];
2024-06-10 20:43:34 +00:00
2024-10-30 08:06:50 +00:00
public array $permissions = ['read'];
public $isApiEnabled;
2023-10-20 12:51:01 +00:00
public function render()
{
return view('livewire.security.api-tokens');
2023-10-20 12:51:01 +00:00
}
2024-06-10 20:43:34 +00:00
2023-10-20 12:51:01 +00:00
public function mount()
{
$this->isApiEnabled = InstanceSettings::get()->is_api_enabled;
2024-12-09 09:52:38 +00:00
$this->getTokens();
}
private function getTokens()
{
$this->tokens = auth()->user()->tokens->sortByDesc('created_at');
}
public function updatedPermissions($permissionToUpdate)
{
2024-12-09 09:52:38 +00:00
if ($permissionToUpdate == 'root') {
$this->permissions = ['root'];
} elseif ($permissionToUpdate == 'read:sensitive' && ! in_array('read', $this->permissions)) {
2024-10-30 08:06:50 +00:00
$this->permissions[] = 'read';
} elseif ($permissionToUpdate == 'deploy') {
$this->permissions = ['deploy'];
} else {
if (count($this->permissions) == 0) {
$this->permissions = ['read'];
}
}
sort($this->permissions);
2023-10-20 12:51:01 +00:00
}
2024-06-10 20:43:34 +00:00
2023-10-20 12:51:01 +00:00
public function addNewToken()
{
try {
$this->validate([
'description' => 'required|min:3|max:255',
]);
2024-10-30 08:06:50 +00:00
$token = auth()->user()->createToken($this->description, array_values($this->permissions));
2024-12-09 09:52:38 +00:00
$this->getTokens();
2023-10-20 12:51:01 +00:00
session()->flash('token', $token->plainTextToken);
} catch (\Exception $e) {
return handleError($e, $this);
}
}
2024-06-10 20:43:34 +00:00
2023-10-20 12:51:01 +00:00
public function revoke(int $id)
{
2024-12-09 09:52:38 +00:00
try {
$token = auth()->user()->tokens()->where('id', $id)->firstOrFail();
$token->delete();
$this->getTokens();
} catch (\Exception $e) {
return handleError($e, $this);
}
2023-10-20 12:51:01 +00:00
}
}