|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\GraphQL\Mutations; |
| 6 | + |
| 7 | +use App\Enums\GlobalRole; |
| 8 | +use App\Mail\InvitedToCdash; |
| 9 | +use App\Models\GlobalInvitation; |
| 10 | +use App\Models\User; |
| 11 | +use Exception; |
| 12 | +use Illuminate\Support\Carbon; |
| 13 | +use Illuminate\Support\Facades\Hash; |
| 14 | +use Illuminate\Support\Facades\Mail; |
| 15 | +use Illuminate\Support\Facades\Validator; |
| 16 | +use Illuminate\Support\Str; |
| 17 | +use Illuminate\Validation\Rule; |
| 18 | + |
| 19 | +final class CreateGlobalInvitation extends AbstractMutation |
| 20 | +{ |
| 21 | + public ?GlobalInvitation $invitedUser = null; |
| 22 | + |
| 23 | + /** |
| 24 | + * @param array{ |
| 25 | + * email: string, |
| 26 | + * role: GlobalRole, |
| 27 | + * } $args |
| 28 | + * |
| 29 | + * @throws Exception |
| 30 | + */ |
| 31 | + protected function mutate(array $args): void |
| 32 | + { |
| 33 | + // This field might not reset when testing since the same mocked request is reused. |
| 34 | + $this->invitedUser = null; |
| 35 | + |
| 36 | + Validator::make($args, [ |
| 37 | + 'email' => [ |
| 38 | + 'required', |
| 39 | + 'email:strict', |
| 40 | + ], |
| 41 | + 'role' => [ |
| 42 | + 'required', |
| 43 | + Rule::enum(GlobalRole::class), |
| 44 | + ], |
| 45 | + ])->validate(); |
| 46 | + |
| 47 | + /** @var ?User $user */ |
| 48 | + $user = auth()->user(); |
| 49 | + if ($user === null) { |
| 50 | + // This should never happen, but we handle the case anyway to make PHPStan happy. |
| 51 | + throw new Exception('Attempt to invite user when not signed in.'); |
| 52 | + } |
| 53 | + |
| 54 | + if ($user->cannot('createInvitation', GlobalInvitation::class)) { |
| 55 | + abort(401, 'This action is unauthorized.'); |
| 56 | + } |
| 57 | + |
| 58 | + if (GlobalInvitation::where('email', $args['email'])->exists()) { |
| 59 | + abort(400, 'Duplicate invitations are not allowed.'); |
| 60 | + } |
| 61 | + |
| 62 | + if (User::where('email', $args['email'])->exists()) { |
| 63 | + abort(401, 'User is already a member of this instance.'); |
| 64 | + } |
| 65 | + |
| 66 | + $password = Str::password(); |
| 67 | + |
| 68 | + $this->invitedUser = GlobalInvitation::create([ |
| 69 | + 'email' => $args['email'], |
| 70 | + 'invited_by_id' => $user->id, |
| 71 | + 'role' => $args['role'], // Note: we assume that anyone who can invite users can assign them any role. |
| 72 | + 'invitation_timestamp' => Carbon::now(), |
| 73 | + 'password' => Hash::make($password), |
| 74 | + ]); |
| 75 | + |
| 76 | + // The email gets sent to the queue, so we have no way to know immediately whether it was sent or not. |
| 77 | + // TODO: We should eventually track whether the email was actually sent. |
| 78 | + Mail::to($args['email'])->send(new InvitedToCdash($this->invitedUser, $password)); |
| 79 | + } |
| 80 | +} |
0 commit comments