Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

6.3 KB
Raw Blame
<?php

namespace App\Livewire\Server\New;

use App\Enums\ProxyTypes;
use App\Enums\ServerRole;
use App\Models\PrivateKey;
use App\Models\Server;
use App\Models\Team;
use App\Rules\ValidServerIp;
use App\Support\ValidationPatterns;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Locked;
use Livewire\Component;

class ByIp extends Component
{
    use AuthorizesRequests;

    #[Locked]
    public $private_keys;

    #[Locked]
    public $limit_reached;

    public ?int $private_key_id = null;

    public $new_private_key_name;

    public $new_private_key_description;

    public $new_private_key_value;

    public string $name;

    public ?string $description = null;

    public string $ip;

    public string $user = 'root';

    public int $port = 22;

    public string $server_role = ServerRole::BOTH->value;

    public function mount()
    {
        $this->name = generate_random_name();
        $this->private_key_id = $this->private_keys->first()?->id;
    }

    protected function rules(): array
    {
        return [
            'private_key_id' => ['nullable', 'integer', Rule::exists('private_keys', 'id')->where('team_id', currentTeam()->id)],
            'new_private_key_name' => 'nullable|string',
            'new_private_key_description' => 'nullable|string',
            'new_private_key_value' => 'nullable|string',
            'name' => ValidationPatterns::nameRules(),
            'description' => ValidationPatterns::descriptionRules(),
            'ip' => ['required', 'string', new ValidServerIp],
            'user' => ValidationPatterns::serverUsernameRules(),
            'port' => 'required|integer|between:1,65535',
            'server_role' => ['required', 'in:deployment,build,both'],
        ];
    }

    protected function messages(): array
    {
        return array_merge(ValidationPatterns::combinedMessages(), [
            'private_key_id.integer' => 'The Private Key field must be an integer.',
            'private_key_id.nullable' => 'The Private Key field is optional.',
            'private_key_id.exists' => 'The selected Private Key is invalid.',
            'new_private_key_name.string' => 'The Private Key Name must be a string.',
            'new_private_key_description.string' => 'The Private Key Description must be a string.',
            'new_private_key_value.string' => 'The Private Key Value must be a string.',
            'ip.required' => 'The IP Address/Domain is required.',
            'ip.string' => 'The IP Address/Domain must be a string.',
            'user.required' => 'The User field is required.',
            'user.string' => 'The User field must be a string.',
            ...ValidationPatterns::serverUsernameMessages(),
            'port.required' => 'The Port field is required.',
            'port.integer' => 'The Port field must be an integer.',
            'port.between' => 'The Port field must be between 1 and 65535.',
            'server_role.required' => 'The Server Role field is required.',
            'server_role.in' => 'The selected Server Role is invalid.',
        ]);
    }

    public function getListeners(): array
    {
        return [
            'privateKeyCreated' => 'handlePrivateKeyCreated',
        ];
    }

    public function setPrivateKey(string $private_key_id)
    {
        $this->private_key_id = $private_key_id;
    }

    public function generatePrivateKey(string $type): void
    {
        try {
            $this->authorize('create', PrivateKey::class);

            if (! in_array($type, ['ed25519', 'rsa'], true)) {
                $this->dispatch('error', 'Invalid private key type.');

                return;
            }

            $keyData = PrivateKey::generateNewKeyPair($type);
            $privateKey = PrivateKey::createAndStore([
                'name' => $keyData['name'],
                'description' => $keyData['description'],
                'private_key' => $keyData['private_key'],
                'team_id' => currentTeam()->id,
            ]);

            $this->handlePrivateKeyCreated($privateKey->id);
            $this->dispatch('success', 'Private key created successfully.');
        } catch (\Throwable $e) {
            handleError($e, $this);
        }
    }

    public function handlePrivateKeyCreated($keyId): void
    {
        $this->private_keys = PrivateKey::ownedAndOnlySShKeys()->where('id', '!=', 0)->get();
        $this->private_key_id = $keyId;
        $this->resetErrorBag('private_key_id');
    }

    public function instantSave()
    {
        // $this->dispatch('success', 'Application settings updated!');
    }

    public function submit()
    {
        $this->validate();
        try {
            $this->authorize('create', Server::class);
            $this->ip = Server::normalizeIp($this->ip);
            $foundServer = Server::whereIp($this->ip)->first();
            if ($foundServer) {
                return $this->dispatch('error', 'A server with this IP/Domain already exists.');
            }

            if (is_null($this->private_key_id)) {
                return $this->dispatch('error', 'You must select a private key');
            }
            if (Team::serverLimitReached()) {
                return $this->dispatch('error', 'You have reached the server limit for your subscription.');
            }
            $payload = [
                'name' => $this->name,
                'description' => $this->description,
                'ip' => $this->ip,
                'user' => $this->user,
                'port' => $this->port,
                'team_id' => currentTeam()->id,
                'private_key_id' => $this->private_key_id,
            ];
            if ($this->server_role === ServerRole::BUILD->value) {
                data_forget($payload, 'proxy');
            }
            $server = Team::createServerWithinLimit(currentTeam()->id, $payload);
            $server->proxy->set('status', 'exited');
            $server->proxy->set('type', ProxyTypes::TRAEFIK->value);
            $server->save();
            $server->settings->server_role = ServerRole::from($this->server_role);
            $server->settings->is_build_server = $this->server_role === ServerRole::BUILD->value;
            $server->settings->save();

            return redirectRoute($this, 'server.show', [$server->uuid]);
        } catch (\Throwable $e) {
            return handleError($e, $this);
        }
    }
}