|
6 | 6 | use App\Exceptions\SSHError; |
7 | 7 | use App\Models\Server; |
8 | 8 | use App\Models\SshKey; |
| 9 | +use Illuminate\Support\Facades\Validator; |
| 10 | +use Illuminate\Validation\Rule; |
9 | 11 |
|
10 | 12 | class DeployKeyToServer |
11 | 13 | { |
12 | 14 | /** |
| 15 | + * @param array<string, mixed> $input |
| 16 | + * |
13 | 17 | * @throws SSHError |
14 | 18 | */ |
15 | | - public function deploy(Server $server, SshKey $sshKey): void |
| 19 | + public function deploy(Server $server, SshKey $sshKey, array $input = []): void |
16 | 20 | { |
| 21 | + // Set default user for backward compatibility |
| 22 | + if (! isset($input['user'])) { |
| 23 | + $input['user'] = $server->getSshUser(); |
| 24 | + } |
| 25 | + |
| 26 | + $this->validate($server, $input); |
| 27 | + |
| 28 | + $user = $input['user']; |
| 29 | + |
17 | 30 | $server->sshKeys()->attach($sshKey, [ |
18 | 31 | 'status' => SshKeyStatus::ADDING, |
| 32 | + 'user' => $user, |
19 | 33 | ]); |
20 | | - $server->os()->deploySSHKey($sshKey->public_key); |
| 34 | + $server->os()->deploySSHKey($sshKey->public_key, $user); |
21 | 35 | $sshKey->servers()->updateExistingPivot($server->id, [ |
22 | 36 | 'status' => SshKeyStatus::ADDED, |
| 37 | + 'user' => $user, |
23 | 38 | ]); |
24 | 39 | } |
| 40 | + |
| 41 | + private function validate(Server $server, array $input): void |
| 42 | + { |
| 43 | + if (empty($input) || ! isset($input['user'])) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + $rules = [ |
| 48 | + 'user' => [ |
| 49 | + 'required', |
| 50 | + 'string', |
| 51 | + Rule::in($server->getSshUsers()), |
| 52 | + ], |
| 53 | + ]; |
| 54 | + |
| 55 | + Validator::make($input, $rules)->validate(); |
| 56 | + } |
25 | 57 | } |
0 commit comments