coolify/app/Livewire/Security/ApiTokens.php

82 lines
2.2 KiB
PHP
Raw Normal View History

2023-10-20 14:51:01 +02:00
<?php
2023-12-07 19:06:32 +01:00
namespace App\Livewire\Security;
2023-10-20 14:51:01 +02:00
use Livewire\Component;
class ApiTokens extends Component
{
public ?string $description = null;
2024-06-10 22:43:34 +02:00
2023-10-20 14:51:01 +02:00
public $tokens = [];
2024-06-10 22:43:34 +02:00
public bool $viewSensitiveData = false;
public bool $readOnly = true;
public array $permissions = ['read-only'];
2023-10-20 14:51:01 +02:00
public function render()
{
return view('livewire.security.api-tokens');
}
2024-06-10 22:43:34 +02:00
2023-10-20 14:51:01 +02:00
public function mount()
{
$this->tokens = auth()->user()->tokens->sortByDesc('created_at');
}
public function updatedViewSensitiveData()
{
if ($this->viewSensitiveData) {
$this->permissions[] = 'view:sensitive';
$this->permissions = array_diff($this->permissions, ['*']);
} else {
$this->permissions = array_diff($this->permissions, ['view:sensitive']);
}
if (count($this->permissions) == 0) {
$this->permissions = ['*'];
}
}
public function updatedReadOnly()
{
if ($this->readOnly) {
$this->permissions[] = 'read-only';
$this->permissions = array_diff($this->permissions, ['*']);
} else {
$this->permissions = array_diff($this->permissions, ['read-only']);
}
if (count($this->permissions) == 0) {
$this->permissions = ['*'];
}
2023-10-20 14:51:01 +02:00
}
2024-06-10 22:43:34 +02:00
2023-10-20 14:51:01 +02:00
public function addNewToken()
{
try {
$this->validate([
'description' => 'required|min:3|max:255',
]);
// if ($this->viewSensitiveData) {
// $this->permissions[] = 'view:sensitive';
// }
// if ($this->readOnly) {
// $this->permissions[] = 'read-only';
// }
$token = auth()->user()->createToken($this->description, $this->permissions);
2023-10-20 14:51:01 +02:00
$this->tokens = auth()->user()->tokens;
session()->flash('token', $token->plainTextToken);
} catch (\Exception $e) {
return handleError($e, $this);
}
}
2024-06-10 22:43:34 +02:00
2023-10-20 14:51:01 +02:00
public function revoke(int $id)
{
$token = auth()->user()->tokens()->where('id', $id)->first();
$token->delete();
$this->tokens = auth()->user()->tokens;
}
}