RecipientKeyController.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\UpdateRecipientKeyRequest;
  5. use App\Http\Resources\RecipientResource;
  6. class RecipientKeyController extends Controller
  7. {
  8. protected $gnupg;
  9. public function __construct()
  10. {
  11. $this->gnupg = new \gnupg();
  12. }
  13. public function update(UpdateRecipientKeyRequest $request, $id)
  14. {
  15. $recipient = user()->recipients()->findOrFail($id);
  16. $info = $this->gnupg->import($request->key_data);
  17. if (!$info || !$info['fingerprint']) {
  18. return response('Key could not be imported', 404);
  19. }
  20. $recipient->update([
  21. 'should_encrypt' => true,
  22. 'fingerprint' => $info['fingerprint']
  23. ]);
  24. return new RecipientResource($recipient->fresh());
  25. }
  26. public function destroy($id)
  27. {
  28. $recipient = user()->recipients()->findOrFail($id);
  29. $key = $this->gnupg->keyinfo($recipient->fingerprint);
  30. if (! isset($key[0]['uids'][0]['email'])) {
  31. return response('Key could not be deleted', 404);
  32. }
  33. $recipientEmails = user()->verifiedRecipients()
  34. ->get()
  35. ->map(function ($item) {
  36. return $item->email;
  37. })
  38. ->toArray();
  39. // Check that the user can delete the key.
  40. if (in_array(strtolower($key[0]['uids'][0]['email']), $recipientEmails)) {
  41. if (!$this->gnupg->deletekey($recipient->fingerprint)) {
  42. return response('Key could not be deleted', 404);
  43. }
  44. }
  45. // Remove the key from all user recipients using that same fingerprint.
  46. user()
  47. ->recipients()
  48. ->get()
  49. ->where('fingerprint', $recipient->fingerprint)
  50. ->each(function ($recipient) {
  51. $recipient->update([
  52. 'should_encrypt' => false,
  53. 'fingerprint' => null
  54. ]);
  55. });
  56. return response('', 204);
  57. }
  58. }