/ app / Http / Livewire / Keys / Create.php
Create.php
  1  <?php
  2  
  3  namespace App\Http\Livewire\Keys;
  4  
  5  use App\Http\Services\GpgService;
  6  use App\Http\Services\KeyService;
  7  use App\Models\Entity;
  8  use App\Models\User;
  9  use Crypt_GPG_BadPassphraseException;
 10  use Livewire\Component;
 11  use Exception;
 12  use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
 13  use Illuminate\Support\Str;
 14  use WireUi\Traits\Actions;
 15  
 16  class Create extends Component
 17  {
 18      use AuthorizesRequests;
 19      use Actions;
 20  
 21      public int $entityId;
 22      public bool $showPass = false;
 23      public ?string $gpgPassword = null;
 24  
 25      public string $entityType;
 26      public ?string $gpgKey = null;
 27      public ?string $passphrase = null;
 28      public bool $isPrivateKey = false;
 29  
 30      public $rules  = [
 31          'gpgKey' => 'required',
 32          'passphrase' => 'required_if:isPrivateKey,true',
 33      ];
 34  
 35      public function updated($propertyName)
 36      {
 37          $this->isPrivateKey = Str::startsWith(
 38              $this->gpgKey,
 39              '-----BEGIN PGP PRIVATE KEY BLOCK-----'
 40          );
 41      }
 42  
 43      public function create()
 44      {
 45          $this->validate();
 46  
 47          try {
 48              $result = KeyService::create($this->entityId, $this->entityType, $this->gpgKey, $this->passphrase);
 49              $this->gpgKey = null;
 50              $this->passphrase = null;
 51  
 52              // UI Trick for delaying spinner
 53              if (config('app.env') !== 'testing') {
 54                  sleep(1);
 55              }
 56              if ($result) {
 57                  $this->emitUp('closePanel');
 58                  $this->emitTo('keys.index', 'refresh');
 59  
 60                  $this->notification()->success(
 61                      __('keys.notifications.create.success.title'),
 62                      __('keys.notifications.create.success.message')
 63                  );
 64              } else {
 65                  throw new Exception('Error al crear la clave');
 66              }
 67          } catch (Crypt_GPG_BadPassphraseException $e) {
 68              $this->addError('passphrase', __('keys.errors.bad_input_passphrase'));
 69          } catch (Exception $e) {
 70              $this->notification()->error(
 71                  'Error',
 72                  $e->getMessage()
 73              );
 74          }
 75      }
 76  
 77      public function closePass()
 78      {
 79          $this->gpgPassword = null;
 80          $this->emit('closePanel');
 81          $this->showPass = false;
 82      }
 83  
 84      public function generateGpgKey(GpgService $service): void
 85      {
 86          try {
 87              // Verificar que entityId y entityType estén presentes
 88              if (!$this->entityId || !$this->entityType) {
 89                  throw new Exception(__('users.notifications.generate_gpg.error.message'));
 90              }
 91  
 92              $passphrase = $service->generateSecurePassword();
 93              $entity = null;
 94  
 95              // Obtener la entidad correcta según el tipo
 96              if ($this->entityType === 'entity') {
 97                  $entity = Entity::findOrFail($this->entityId);
 98  
 99                  // Verificar que la entidad tenga la información necesaria
100                  if (!$entity->name || !isset($entity->contactInfo) || !$entity->contactInfo->email) {
101                      throw new Exception(__('users.notifications.generate_gpg.not_name_or_email.message'));
102                  }
103  
104                  // Generar clave para la entidad
105                  $service->generateEntityKey($entity);
106              } elseif ($this->entityType === 'user') {
107                  $entity = User::findOrFail($this->entityId);
108  
109                  // Verificar que el usuario tenga la información necesaria
110                  if (!$entity->name || !$entity->email) {
111                      throw new Exception(__('users.notifications.generate_gpg.not_name_or_email.message'));
112                  }
113  
114                  // Generar clave para el usuario
115                  $service->generateUserKey($entity, $passphrase);
116              } else {
117                  throw new Exception('Tipo de entidad no válido');
118              }
119  
120              // Guardar la contraseña y mostrar el modal
121              $this->showPass = true;
122              $this->gpgPassword = $passphrase;
123  
124              $this->emitTo('keys.index', 'refresh');
125  
126              // Notificar éxito
127              $this->notification()->success(
128                  title: __('users.notifications.generate_gpg.success.title'),
129                  description: __('users.notifications.generate_gpg.success.message')
130              );
131  
132          } catch (\Exception $e) {
133              $this->notification()->error(
134                  title: __('users.notifications.generate_gpg.error.title'),
135                  description: $e->getMessage()
136              );
137              logger()->error('Error generando clave GPG: ' . $e->getMessage(), [
138                  'entityId' => $this->entityId,
139                  'entityType' => $this->entityType,
140                  'exception' => $e
141              ]);
142          }
143      }
144  
145      public function render()
146      {
147          return view('livewire.keys.create');
148      }
149  }