repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/OauthSetting.php | app/Models/OauthSetting.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
class OauthSetting extends Model
{
use HasFactory;
protected $fillable = ['provider', 'client_id', 'client_secret', 'redirect_uri', 'tenant', 'base_url', 'enabled'];
protected function clientSecret(): Attribute
{
return Attribute::make(
get: fn (?string $value) => empty($value) ? null : Crypt::decryptString($value),
set: fn (?string $value) => empty($value) ? null : Crypt::encryptString($value),
);
}
public function couldBeEnabled(): bool
{
switch ($this->provider) {
case 'azure':
return filled($this->client_id) && filled($this->client_secret) && filled($this->tenant);
case 'authentik':
case 'clerk':
return filled($this->client_id) && filled($this->client_secret) && filled($this->base_url);
default:
return filled($this->client_id) && filled($this->client_secret);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Subscription.php | app/Models/Subscription.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Subscription extends Model
{
protected $guarded = [];
public function team()
{
return $this->belongsTo(Team::class);
}
public function type()
{
if (isStripe()) {
if (! $this->stripe_plan_id) {
return 'zero';
}
$subscription = Subscription::where('id', $this->id)->first();
if (! $subscription) {
return null;
}
$subscriptionPlanId = data_get($subscription, 'stripe_plan_id');
if (! $subscriptionPlanId) {
return null;
}
$subscriptionInvoicePaid = data_get($subscription, 'stripe_invoice_paid');
if (! $subscriptionInvoicePaid) {
return null;
}
$subscriptionConfigs = collect(config('subscription'));
$stripePlanId = null;
$subscriptionConfigs->map(function ($value, $key) use ($subscriptionPlanId, &$stripePlanId) {
if ($value === $subscriptionPlanId) {
$stripePlanId = $key;
}
})->first();
if ($stripePlanId) {
return str($stripePlanId)->after('stripe_price_id_')->before('_')->lower();
}
}
return 'zero';
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ScheduledDatabaseBackupExecution.php | app/Models/ScheduledDatabaseBackupExecution.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ScheduledDatabaseBackupExecution extends BaseModel
{
protected $guarded = [];
protected function casts(): array
{
return [
's3_uploaded' => 'boolean',
'local_storage_deleted' => 'boolean',
's3_storage_deleted' => 'boolean',
];
}
public function scheduledDatabaseBackup(): BelongsTo
{
return $this->belongsTo(ScheduledDatabaseBackup::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Application.php | app/Models/Application.php | <?php
namespace App\Models;
use App\Enums\ApplicationDeploymentStatus;
use App\Services\ConfigurationGenerator;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasConfiguration;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use OpenApi\Attributes as OA;
use RuntimeException;
use Spatie\Activitylog\Models\Activity;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
use Visus\Cuid2\Cuid2;
#[OA\Schema(
description: 'Application model',
type: 'object',
properties: [
'id' => ['type' => 'integer', 'description' => 'The application identifier in the database.'],
'description' => ['type' => 'string', 'nullable' => true, 'description' => 'The application description.'],
'repository_project_id' => ['type' => 'integer', 'nullable' => true, 'description' => 'The repository project identifier.'],
'uuid' => ['type' => 'string', 'description' => 'The application UUID.'],
'name' => ['type' => 'string', 'description' => 'The application name.'],
'fqdn' => ['type' => 'string', 'nullable' => true, 'description' => 'The application domains.'],
'config_hash' => ['type' => 'string', 'description' => 'Configuration hash.'],
'git_repository' => ['type' => 'string', 'description' => 'Git repository URL.'],
'git_branch' => ['type' => 'string', 'description' => 'Git branch.'],
'git_commit_sha' => ['type' => 'string', 'description' => 'Git commit SHA.'],
'git_full_url' => ['type' => 'string', 'nullable' => true, 'description' => 'Git full URL.'],
'docker_registry_image_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker registry image name.'],
'docker_registry_image_tag' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker registry image tag.'],
'build_pack' => ['type' => 'string', 'description' => 'Build pack.', 'enum' => ['nixpacks', 'static', 'dockerfile', 'dockercompose']],
'static_image' => ['type' => 'string', 'description' => 'Static image used when static site is deployed.'],
'install_command' => ['type' => 'string', 'description' => 'Install command.'],
'build_command' => ['type' => 'string', 'description' => 'Build command.'],
'start_command' => ['type' => 'string', 'description' => 'Start command.'],
'ports_exposes' => ['type' => 'string', 'description' => 'Ports exposes.'],
'ports_mappings' => ['type' => 'string', 'nullable' => true, 'description' => 'Ports mappings.'],
'custom_network_aliases' => ['type' => 'string', 'nullable' => true, 'description' => 'Network aliases for Docker container.'],
'base_directory' => ['type' => 'string', 'description' => 'Base directory for all commands.'],
'publish_directory' => ['type' => 'string', 'description' => 'Publish directory.'],
'health_check_enabled' => ['type' => 'boolean', 'description' => 'Health check enabled.'],
'health_check_path' => ['type' => 'string', 'description' => 'Health check path.'],
'health_check_port' => ['type' => 'string', 'nullable' => true, 'description' => 'Health check port.'],
'health_check_host' => ['type' => 'string', 'nullable' => true, 'description' => 'Health check host.'],
'health_check_method' => ['type' => 'string', 'description' => 'Health check method.'],
'health_check_return_code' => ['type' => 'integer', 'description' => 'Health check return code.'],
'health_check_scheme' => ['type' => 'string', 'description' => 'Health check scheme.'],
'health_check_response_text' => ['type' => 'string', 'nullable' => true, 'description' => 'Health check response text.'],
'health_check_interval' => ['type' => 'integer', 'description' => 'Health check interval in seconds.'],
'health_check_timeout' => ['type' => 'integer', 'description' => 'Health check timeout in seconds.'],
'health_check_retries' => ['type' => 'integer', 'description' => 'Health check retries count.'],
'health_check_start_period' => ['type' => 'integer', 'description' => 'Health check start period in seconds.'],
'limits_memory' => ['type' => 'string', 'description' => 'Memory limit.'],
'limits_memory_swap' => ['type' => 'string', 'description' => 'Memory swap limit.'],
'limits_memory_swappiness' => ['type' => 'integer', 'description' => 'Memory swappiness.'],
'limits_memory_reservation' => ['type' => 'string', 'description' => 'Memory reservation.'],
'limits_cpus' => ['type' => 'string', 'description' => 'CPU limit.'],
'limits_cpuset' => ['type' => 'string', 'nullable' => true, 'description' => 'CPU set.'],
'limits_cpu_shares' => ['type' => 'integer', 'description' => 'CPU shares.'],
'status' => ['type' => 'string', 'description' => 'Application status.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'destination_type' => ['type' => 'string', 'description' => 'Destination type.'],
'destination_id' => ['type' => 'integer', 'description' => 'Destination identifier.'],
'source_id' => ['type' => 'integer', 'nullable' => true, 'description' => 'Source identifier.'],
'private_key_id' => ['type' => 'integer', 'nullable' => true, 'description' => 'Private key identifier.'],
'environment_id' => ['type' => 'integer', 'description' => 'Environment identifier.'],
'dockerfile' => ['type' => 'string', 'nullable' => true, 'description' => 'Dockerfile content. Used for dockerfile build pack.'],
'dockerfile_location' => ['type' => 'string', 'description' => 'Dockerfile location.'],
'custom_labels' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom labels.'],
'dockerfile_target_build' => ['type' => 'string', 'nullable' => true, 'description' => 'Dockerfile target build.'],
'manual_webhook_secret_github' => ['type' => 'string', 'nullable' => true, 'description' => 'Manual webhook secret for GitHub.'],
'manual_webhook_secret_gitlab' => ['type' => 'string', 'nullable' => true, 'description' => 'Manual webhook secret for GitLab.'],
'manual_webhook_secret_bitbucket' => ['type' => 'string', 'nullable' => true, 'description' => 'Manual webhook secret for Bitbucket.'],
'manual_webhook_secret_gitea' => ['type' => 'string', 'nullable' => true, 'description' => 'Manual webhook secret for Gitea.'],
'docker_compose_location' => ['type' => 'string', 'description' => 'Docker compose location.'],
'docker_compose' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker compose content. Used for docker compose build pack.'],
'docker_compose_raw' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker compose raw content.'],
'docker_compose_domains' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker compose domains.'],
'docker_compose_custom_start_command' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker compose custom start command.'],
'docker_compose_custom_build_command' => ['type' => 'string', 'nullable' => true, 'description' => 'Docker compose custom build command.'],
'swarm_replicas' => ['type' => 'integer', 'nullable' => true, 'description' => 'Swarm replicas. Only used for swarm deployments.'],
'swarm_placement_constraints' => ['type' => 'string', 'nullable' => true, 'description' => 'Swarm placement constraints. Only used for swarm deployments.'],
'custom_docker_run_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom docker run options.'],
'post_deployment_command' => ['type' => 'string', 'nullable' => true, 'description' => 'Post deployment command.'],
'post_deployment_command_container' => ['type' => 'string', 'nullable' => true, 'description' => 'Post deployment command container.'],
'pre_deployment_command' => ['type' => 'string', 'nullable' => true, 'description' => 'Pre deployment command.'],
'pre_deployment_command_container' => ['type' => 'string', 'nullable' => true, 'description' => 'Pre deployment command container.'],
'watch_paths' => ['type' => 'string', 'nullable' => true, 'description' => 'Watch paths.'],
'custom_healthcheck_found' => ['type' => 'boolean', 'description' => 'Custom healthcheck found.'],
'redirect' => ['type' => 'string', 'nullable' => true, 'description' => 'How to set redirect with Traefik / Caddy. www<->non-www.', 'enum' => ['www', 'non-www', 'both']],
'created_at' => ['type' => 'string', 'format' => 'date-time', 'description' => 'The date and time when the application was created.'],
'updated_at' => ['type' => 'string', 'format' => 'date-time', 'description' => 'The date and time when the application was last updated.'],
'deleted_at' => ['type' => 'string', 'format' => 'date-time', 'nullable' => true, 'description' => 'The date and time when the application was deleted.'],
'compose_parsing_version' => ['type' => 'string', 'description' => 'How Coolify parse the compose file.'],
'custom_nginx_configuration' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom Nginx configuration base64 encoded.'],
'is_http_basic_auth_enabled' => ['type' => 'boolean', 'description' => 'HTTP Basic Authentication enabled.'],
'http_basic_auth_username' => ['type' => 'string', 'nullable' => true, 'description' => 'Username for HTTP Basic Authentication'],
'http_basic_auth_password' => ['type' => 'string', 'nullable' => true, 'description' => 'Password for HTTP Basic Authentication'],
]
)]
class Application extends BaseModel
{
use ClearsGlobalSearchCache, HasConfiguration, HasFactory, HasSafeStringAttribute, SoftDeletes;
private static $parserVersion = '5';
protected $guarded = [];
protected $appends = ['server_status'];
protected $casts = [
'http_basic_auth_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
];
protected static function booted()
{
static::addGlobalScope('withRelations', function ($builder) {
$builder->withCount([
'additional_servers',
'additional_networks',
]);
});
static::saving(function ($application) {
$payload = [];
if ($application->isDirty('fqdn')) {
if ($application->fqdn === '') {
$application->fqdn = null;
}
$payload['fqdn'] = $application->fqdn;
}
if ($application->isDirty('install_command')) {
$payload['install_command'] = str($application->install_command)->trim();
}
if ($application->isDirty('build_command')) {
$payload['build_command'] = str($application->build_command)->trim();
}
if ($application->isDirty('start_command')) {
$payload['start_command'] = str($application->start_command)->trim();
}
if ($application->isDirty('base_directory')) {
$payload['base_directory'] = str($application->base_directory)->trim();
}
if ($application->isDirty('publish_directory')) {
$payload['publish_directory'] = str($application->publish_directory)->trim();
}
if ($application->isDirty('git_repository')) {
$payload['git_repository'] = str($application->git_repository)->trim();
}
if ($application->isDirty('git_branch')) {
$payload['git_branch'] = str($application->git_branch)->trim();
}
if ($application->isDirty('git_commit_sha')) {
$payload['git_commit_sha'] = str($application->git_commit_sha)->trim();
}
if ($application->isDirty('status')) {
$payload['last_online_at'] = now();
}
if ($application->isDirty('custom_nginx_configuration')) {
if ($application->custom_nginx_configuration === '') {
$payload['custom_nginx_configuration'] = null;
}
}
if (count($payload) > 0) {
$application->forceFill($payload);
}
// Buildpack switching cleanup logic
if ($application->isDirty('build_pack')) {
$originalBuildPack = $application->getOriginal('build_pack');
// Clear Docker Compose specific data when switching away from dockercompose
if ($originalBuildPack === 'dockercompose') {
$application->docker_compose_domains = null;
$application->docker_compose_raw = null;
// Remove SERVICE_FQDN_* and SERVICE_URL_* environment variables
$application->environment_variables()
->where(function ($q) {
$q->where('key', 'LIKE', 'SERVICE_FQDN_%')
->orWhere('key', 'LIKE', 'SERVICE_URL_%');
})
->delete();
$application->environment_variables_preview()
->where(function ($q) {
$q->where('key', 'LIKE', 'SERVICE_FQDN_%')
->orWhere('key', 'LIKE', 'SERVICE_URL_%');
})
->delete();
}
// Clear Dockerfile specific data when switching away from dockerfile
if ($originalBuildPack === 'dockerfile') {
$application->dockerfile = null;
$application->dockerfile_location = null;
$application->dockerfile_target_build = null;
$application->custom_healthcheck_found = false;
}
}
});
static::created(function ($application) {
ApplicationSetting::create([
'application_id' => $application->id,
]);
$application->compose_parsing_version = self::$parserVersion;
$application->save();
// Add default NIXPACKS_NODE_VERSION environment variable for Nixpacks applications
if ($application->build_pack === 'nixpacks') {
EnvironmentVariable::create([
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
'is_multiline' => false,
'is_literal' => false,
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => false,
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
]);
}
});
static::forceDeleting(function ($application) {
$application->update(['fqdn' => null]);
$application->settings()->delete();
$application->persistentStorages()->delete();
$application->environment_variables()->delete();
$application->environment_variables_preview()->delete();
foreach ($application->scheduled_tasks as $task) {
$task->delete();
}
$application->tags()->detach();
$application->previews()->delete();
foreach ($application->deployment_queue as $deployment) {
$deployment->delete();
}
});
}
public function customNetworkAliases(): Attribute
{
return Attribute::make(
set: function ($value) {
if (is_null($value) || $value === '') {
return null;
}
// If it's already a JSON string, decode it
if (is_string($value) && $this->isJson($value)) {
$value = json_decode($value, true);
}
// If it's a string but not JSON, treat it as a comma-separated list
if (is_string($value) && ! is_array($value)) {
$value = explode(',', $value);
}
$value = collect($value)
->map(function ($alias) {
if (is_string($alias)) {
return str_replace(' ', '-', trim($alias));
}
return null;
})
->filter()
->unique() // Remove duplicate values
->values()
->toArray();
return empty($value) ? null : json_encode($value);
},
get: function ($value) {
if (is_null($value)) {
return null;
}
if (is_string($value) && $this->isJson($value)) {
$decoded = json_decode($value, true);
// Return as comma-separated string, not array
return is_array($decoded) ? implode(',', $decoded) : $value;
}
return $value;
}
);
}
/**
* Get custom_network_aliases as an array
*/
public function customNetworkAliasesArray(): Attribute
{
return Attribute::make(
get: function () {
$value = $this->getRawOriginal('custom_network_aliases');
if (is_null($value)) {
return null;
}
if (is_string($value) && $this->isJson($value)) {
return json_decode($value, true);
}
return is_array($value) ? $value : [];
}
);
}
/**
* Check if a string is a valid JSON
*/
private function isJson($string)
{
if (! is_string($string)) {
return false;
}
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
public static function ownedByCurrentTeamAPI(int $teamId)
{
return Application::whereRelation('environment.project.team', 'id', $teamId)->orderBy('name');
}
/**
* Get query builder for applications owned by current team.
* If you need all applications without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return Application::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all applications owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return Application::ownedByCurrentTeam()->get();
});
}
public function getContainersToStop(Server $server, bool $previewDeployments = false): array
{
$containers = $previewDeployments
? getCurrentApplicationContainerStatus($server, $this->id, includePullrequests: true)
: getCurrentApplicationContainerStatus($server, $this->id, 0);
return $containers->pluck('Names')->toArray();
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($this->build_pack === 'dockercompose') {
$server = data_get($this, 'destination.server');
instant_remote_process(["cd {$this->dirOnServer()} && docker compose down -v"], $server, false);
} else {
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
}
public function deleteConnectedNetworks()
{
$uuid = $this->uuid;
$server = data_get($this, 'destination.server');
instant_remote_process(["docker network disconnect {$uuid} coolify-proxy"], $server, false);
instant_remote_process(["docker network rm {$uuid}"], $server, false);
}
public function additional_servers()
{
return $this->belongsToMany(Server::class, 'additional_destinations')
->withPivot('standalone_docker_id', 'status');
}
public function additional_networks()
{
return $this->belongsToMany(StandaloneDocker::class, 'additional_destinations')
->withPivot('server_id', 'status');
}
public function is_public_repository(): bool
{
if (data_get($this, 'source.is_public')) {
return true;
}
return false;
}
public function is_github_based(): bool
{
if (data_get($this, 'source')) {
return true;
}
return false;
}
public function isForceHttpsEnabled()
{
return data_get($this, 'settings.is_force_https_enabled', false);
}
public function isStripprefixEnabled()
{
return data_get($this, 'settings.is_stripprefix_enabled', true);
}
public function isGzipEnabled()
{
return data_get($this, 'settings.is_gzip_enabled', true);
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.application.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'application_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function taskLink($task_uuid)
{
if (data_get($this, 'environment.project.uuid')) {
$route = route('project.application.scheduled-tasks', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'application_uuid' => data_get($this, 'uuid'),
'task_uuid' => $task_uuid,
]);
$settings = instanceSettings();
if (data_get($settings, 'fqdn')) {
$url = Url::fromString($route);
$url = $url->withPort(null);
$fqdn = data_get($settings, 'fqdn');
$fqdn = str_replace(['http://', 'https://'], '', $fqdn);
$url = $url->withHost($fqdn);
return $url->__toString();
}
return $route;
}
return null;
}
public function settings()
{
return $this->hasOne(ApplicationSetting::class);
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function type()
{
return 'application';
}
public function publishDirectory(): Attribute
{
return Attribute::make(
set: fn ($value) => $value ? '/'.ltrim($value, '/') : null,
);
}
public function gitBranchLocation(): Attribute
{
return Attribute::make(
get: function () {
$base_dir = $this->base_directory ?? '/';
if (! is_null($this->source?->html_url) && ! is_null($this->git_repository) && ! is_null($this->git_branch)) {
if (str($this->git_repository)->contains('bitbucket')) {
return "{$this->source->html_url}/{$this->git_repository}/src/{$this->git_branch}{$base_dir}";
}
return "{$this->source->html_url}/{$this->git_repository}/tree/{$this->git_branch}{$base_dir}";
}
// Convert the SSH URL to HTTPS URL
if (strpos($this->git_repository, 'git@') === 0) {
$git_repository = str_replace(['git@', ':', '.git'], ['', '/', ''], $this->git_repository);
if (str($this->git_repository)->contains('bitbucket')) {
return "https://{$git_repository}/src/{$this->git_branch}{$base_dir}";
}
return "https://{$git_repository}/tree/{$this->git_branch}{$base_dir}";
}
return $this->git_repository;
}
);
}
public function gitWebhook(): Attribute
{
return Attribute::make(
get: function () {
if (! is_null($this->source?->html_url) && ! is_null($this->git_repository) && ! is_null($this->git_branch)) {
return "{$this->source->html_url}/{$this->git_repository}/settings/hooks";
}
// Convert the SSH URL to HTTPS URL
if (strpos($this->git_repository, 'git@') === 0) {
$git_repository = str_replace(['git@', ':', '.git'], ['', '/', ''], $this->git_repository);
return "https://{$git_repository}/settings/hooks";
}
return $this->git_repository;
}
);
}
public function gitCommits(): Attribute
{
return Attribute::make(
get: function () {
if (! is_null($this->source?->html_url) && ! is_null($this->git_repository) && ! is_null($this->git_branch)) {
return "{$this->source->html_url}/{$this->git_repository}/commits/{$this->git_branch}";
}
// Convert the SSH URL to HTTPS URL
if (strpos($this->git_repository, 'git@') === 0) {
$git_repository = str_replace(['git@', ':', '.git'], ['', '/', ''], $this->git_repository);
return "https://{$git_repository}/commits/{$this->git_branch}";
}
return $this->git_repository;
}
);
}
public function gitCommitLink($link): string
{
if (! is_null(data_get($this, 'source.html_url')) && ! is_null(data_get($this, 'git_repository')) && ! is_null(data_get($this, 'git_branch'))) {
if (str($this->source->html_url)->contains('bitbucket')) {
return "{$this->source->html_url}/{$this->git_repository}/commits/{$link}";
}
return "{$this->source->html_url}/{$this->git_repository}/commit/{$link}";
}
if (str($this->git_repository)->contains('bitbucket')) {
$git_repository = str_replace('.git', '', $this->git_repository);
$url = Url::fromString($git_repository);
$url = $url->withUserInfo('');
$url = $url->withPath($url->getPath().'/commits/'.$link);
return $url->__toString();
}
if (strpos($this->git_repository, 'git@') === 0) {
$git_repository = str_replace(['git@', ':', '.git'], ['', '/', ''], $this->git_repository);
if (data_get($this, 'source.html_url')) {
return "{$this->source->html_url}/{$git_repository}/commit/{$link}";
}
return "{$git_repository}/commit/{$link}";
}
return $this->git_repository;
}
public function dockerfileLocation(): Attribute
{
return Attribute::make(
set: function ($value) {
if (is_null($value) || $value === '') {
return '/Dockerfile';
} else {
if ($value !== '/') {
return Str::start(Str::replaceEnd('/', '', $value), '/');
}
return Str::start($value, '/');
}
}
);
}
public function dockerComposeLocation(): Attribute
{
return Attribute::make(
set: function ($value) {
if (is_null($value) || $value === '') {
return '/docker-compose.yaml';
} else {
if ($value !== '/') {
return Str::start(Str::replaceEnd('/', '', $value), '/');
}
return Str::start($value, '/');
}
}
);
}
public function baseDirectory(): Attribute
{
return Attribute::make(
set: fn ($value) => '/'.ltrim($value, '/'),
);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function isRunning()
{
return (bool) str($this->status)->startsWith('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
// Check main server infrastructure health
$main_server_functional = $this->destination?->server?->isFunctional() ?? false;
if (! $main_server_functional) {
return false;
}
// Check additional servers infrastructure health (not container status!)
if ($this->relationLoaded('additional_servers') && $this->additional_servers->count() > 0) {
foreach ($this->additional_servers as $server) {
if (! $server->isFunctional()) {
return false; // Real server infrastructure problem
}
}
}
return true;
}
);
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if ($this->additional_servers->count() === 0) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
} else {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
}
},
get: function ($value) {
if ($this->additional_servers->count() === 0) {
// running (healthy)
if (str($value)->contains('(')) {
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Environment.php | app/Models/Environment.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use OpenApi\Attributes as OA;
#[OA\Schema(
description: 'Environment model',
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'name' => ['type' => 'string'],
'project_id' => ['type' => 'integer'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
'description' => ['type' => 'string'],
]
)]
class Environment extends BaseModel
{
use ClearsGlobalSearchCache;
use HasSafeStringAttribute;
protected $guarded = [];
protected static function booted()
{
static::deleting(function ($environment) {
$shared_variables = $environment->environment_variables();
foreach ($shared_variables as $shared_variable) {
$shared_variable->delete();
}
});
}
public static function ownedByCurrentTeam()
{
return Environment::whereRelation('project.team', 'id', currentTeam()->id)->orderBy('name');
}
public function isEmpty()
{
return $this->applications()->count() == 0 &&
$this->redis()->count() == 0 &&
$this->postgresqls()->count() == 0 &&
$this->mysqls()->count() == 0 &&
$this->keydbs()->count() == 0 &&
$this->dragonflies()->count() == 0 &&
$this->clickhouses()->count() == 0 &&
$this->mariadbs()->count() == 0 &&
$this->mongodbs()->count() == 0 &&
$this->services()->count() == 0;
}
public function environment_variables()
{
return $this->hasMany(SharedEnvironmentVariable::class);
}
public function applications()
{
return $this->hasMany(Application::class);
}
public function postgresqls()
{
return $this->hasMany(StandalonePostgresql::class);
}
public function redis()
{
return $this->hasMany(StandaloneRedis::class);
}
public function mongodbs()
{
return $this->hasMany(StandaloneMongodb::class);
}
public function mysqls()
{
return $this->hasMany(StandaloneMysql::class);
}
public function mariadbs()
{
return $this->hasMany(StandaloneMariadb::class);
}
public function keydbs()
{
return $this->hasMany(StandaloneKeydb::class);
}
public function dragonflies()
{
return $this->hasMany(StandaloneDragonfly::class);
}
public function clickhouses()
{
return $this->hasMany(StandaloneClickhouse::class);
}
public function databases()
{
$postgresqls = $this->postgresqls;
$redis = $this->redis;
$mongodbs = $this->mongodbs;
$mysqls = $this->mysqls;
$mariadbs = $this->mariadbs;
$keydbs = $this->keydbs;
$dragonflies = $this->dragonflies;
$clickhouses = $this->clickhouses;
return $postgresqls->concat($redis)->concat($mongodbs)->concat($mysqls)->concat($mariadbs)->concat($keydbs)->concat($dragonflies)->concat($clickhouses);
}
public function project()
{
return $this->belongsTo(Project::class);
}
public function services()
{
return $this->hasMany(Service::class);
}
protected function customizeName($value)
{
return str($value)->lower()->trim()->replace('/', '-')->toString();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ServiceApplication.php | app/Models/ServiceApplication.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class ServiceApplication extends BaseModel
{
use HasFactory, SoftDeletes;
protected $guarded = [];
protected static function booted()
{
static::deleting(function ($service) {
$service->update(['fqdn' => null]);
$service->persistentStorages()->delete();
$service->fileStorages()->delete();
});
static::saving(function ($service) {
if ($service->isDirty('status')) {
$service->forceFill(['last_online_at' => now()]);
}
});
}
public function restart()
{
$container_id = $this->name.'-'.$this->service->uuid;
instant_remote_process(["docker restart {$container_id}"], $this->service->server);
}
public static function ownedByCurrentTeamAPI(int $teamId)
{
return ServiceApplication::whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');
}
/**
* Get query builder for service applications owned by current team.
* If you need all service applications without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return ServiceApplication::whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all service applications owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return ServiceApplication::ownedByCurrentTeam()->get();
});
}
public function isRunning()
{
return str($this->status)->contains('running');
}
public function isExited()
{
return str($this->status)->contains('exited');
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function isStripprefixEnabled()
{
return data_get($this, 'is_stripprefix_enabled', true);
}
public function isGzipEnabled()
{
return data_get($this, 'is_gzip_enabled', true);
}
public function type()
{
return 'service';
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function workdir()
{
return service_configuration_dir()."/{$this->service->uuid}";
}
public function serviceType()
{
$found = str(collect(SPECIFIC_SERVICES)->filter(function ($service) {
return str($this->image)->before(':')->value() === $service;
})->first());
if ($found->isNotEmpty()) {
return $found;
}
return null;
}
public function service()
{
return $this->belongsTo(Service::class);
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function fqdns(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->fqdn)
? []
: explode(',', $this->fqdn),
);
}
/**
* Extract port number from a given FQDN URL.
* Returns null if no port is specified.
*/
public static function extractPortFromUrl(string $url): ?int
{
try {
// Ensure URL has a scheme for proper parsing
if (! str_starts_with($url, 'http://') && ! str_starts_with($url, 'https://')) {
$url = 'http://'.$url;
}
$parsed = parse_url($url);
$port = $parsed['port'] ?? null;
return $port ? (int) $port : null;
} catch (\Throwable) {
return null;
}
}
/**
* Check if all FQDNs have a port specified.
*/
public function allFqdnsHavePort(): bool
{
if (is_null($this->fqdn) || $this->fqdn === '') {
return false;
}
$fqdns = explode(',', $this->fqdn);
foreach ($fqdns as $fqdn) {
$fqdn = trim($fqdn);
if (empty($fqdn)) {
continue;
}
$port = self::extractPortFromUrl($fqdn);
if ($port === null) {
return false;
}
}
return true;
}
public function getFilesFromServer(bool $isInit = false)
{
getFilesystemVolumesFromServer($this, $isInit);
}
public function isBackupSolutionAvailable()
{
return false;
}
/**
* Get the required port for this service application.
* Extracts port from SERVICE_URL_* or SERVICE_FQDN_* environment variables
* stored at the Service level, filtering by normalized container name.
* Falls back to service-level port if no port-specific variable is found.
*/
public function getRequiredPort(): ?int
{
try {
// Parse the Docker Compose to find SERVICE_URL/SERVICE_FQDN variables DIRECTLY DECLARED
// for this specific service container (not just referenced from other containers)
$dockerComposeRaw = data_get($this->service, 'docker_compose_raw');
if (! $dockerComposeRaw) {
// Fall back to service-level port if no compose file
return $this->service->getRequiredPort();
}
$dockerCompose = \Symfony\Component\Yaml\Yaml::parse($dockerComposeRaw);
$serviceConfig = data_get($dockerCompose, "services.{$this->name}");
if (! $serviceConfig) {
return $this->service->getRequiredPort();
}
$environment = data_get($serviceConfig, 'environment', []);
// Extract SERVICE_URL and SERVICE_FQDN variables DIRECTLY DECLARED in this service's environment
// (not variables that are merely referenced with ${VAR} syntax)
$portFound = null;
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style: "- SERVICE_URL_APP_3000" or "- SERVICE_URL_APP_3000=value"
// Extract variable name (before '=' if present)
$envVarName = str($value)->before('=')->trim();
// Only process direct declarations
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
// Parse to check if it has a port suffix
$parsed = parseServiceEnvironmentVariable($envVarName->value());
if ($parsed['has_port'] && $parsed['port']) {
// Found a port-specific variable for this service
$portFound = (int) $parsed['port'];
break;
}
}
} elseif (is_string($key)) {
// Map-style: "SERVICE_URL_APP_3000: value" or "SERVICE_FQDN_DB: localhost"
$envVarName = str($key);
// Only process direct declarations
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
// Parse to check if it has a port suffix
$parsed = parseServiceEnvironmentVariable($envVarName->value());
if ($parsed['has_port'] && $parsed['port']) {
// Found a port-specific variable for this service
$portFound = (int) $parsed['port'];
break;
}
}
}
}
// If a port was found in the template, return it
if ($portFound !== null) {
return $portFound;
}
// No port-specific variables found for this service, return null
// (DO NOT fall back to service-level port, as that applies to all services)
return null;
} catch (\Throwable $e) {
return null;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ScheduledDatabaseBackup.php | app/Models/ScheduledDatabaseBackup.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class ScheduledDatabaseBackup extends BaseModel
{
protected $guarded = [];
public static function ownedByCurrentTeam()
{
return ScheduledDatabaseBackup::whereRelation('team', 'id', currentTeam()->id)->orderBy('created_at', 'desc');
}
public static function ownedByCurrentTeamAPI(int $teamId)
{
return ScheduledDatabaseBackup::whereRelation('team', 'id', $teamId)->orderBy('created_at', 'desc');
}
public function team()
{
return $this->belongsTo(Team::class);
}
public function database(): MorphTo
{
return $this->morphTo();
}
public function latest_log(): HasOne
{
return $this->hasOne(ScheduledDatabaseBackupExecution::class)->latest();
}
public function executions(): HasMany
{
// Last execution first
return $this->hasMany(ScheduledDatabaseBackupExecution::class)->orderBy('created_at', 'desc');
}
public function s3()
{
return $this->belongsTo(S3Storage::class, 's3_storage_id');
}
public function get_last_days_backup_status($days = 7)
{
return $this->hasMany(ScheduledDatabaseBackupExecution::class)->where('created_at', '>=', now()->subDays($days))->get();
}
public function executionsPaginated(int $skip = 0, int $take = 10)
{
$executions = $this->hasMany(ScheduledDatabaseBackupExecution::class)->orderBy('created_at', 'desc');
$count = $executions->count();
$executions = $executions->skip($skip)->take($take)->get();
return [
'count' => $count,
'executions' => $executions,
];
}
public function server()
{
if ($this->database) {
if ($this->database instanceof ServiceDatabase) {
$destination = data_get($this->database->service, 'destination');
$server = data_get($destination, 'server');
} else {
$destination = data_get($this->database, 'destination');
$server = data_get($destination, 'server');
}
if ($server) {
return $server;
}
}
return null;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/PersonalAccessToken.php | app/Models/PersonalAccessToken.php | <?php
namespace App\Models;
use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;
class PersonalAccessToken extends SanctumPersonalAccessToken
{
protected $fillable = [
'name',
'token',
'abilities',
'expires_at',
'team_id',
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/WebhookNotificationSettings.php | app/Models/WebhookNotificationSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class WebhookNotificationSettings extends Model
{
use Notifiable;
public $timestamps = false;
protected $fillable = [
'team_id',
'webhook_enabled',
'webhook_url',
'deployment_success_webhook_notifications',
'deployment_failure_webhook_notifications',
'status_change_webhook_notifications',
'backup_success_webhook_notifications',
'backup_failure_webhook_notifications',
'scheduled_task_success_webhook_notifications',
'scheduled_task_failure_webhook_notifications',
'docker_cleanup_success_webhook_notifications',
'docker_cleanup_failure_webhook_notifications',
'server_disk_usage_webhook_notifications',
'server_reachable_webhook_notifications',
'server_unreachable_webhook_notifications',
'server_patch_webhook_notifications',
'traefik_outdated_webhook_notifications',
];
protected function casts(): array
{
return [
'webhook_enabled' => 'boolean',
'webhook_url' => 'encrypted',
'deployment_success_webhook_notifications' => 'boolean',
'deployment_failure_webhook_notifications' => 'boolean',
'status_change_webhook_notifications' => 'boolean',
'backup_success_webhook_notifications' => 'boolean',
'backup_failure_webhook_notifications' => 'boolean',
'scheduled_task_success_webhook_notifications' => 'boolean',
'scheduled_task_failure_webhook_notifications' => 'boolean',
'docker_cleanup_success_webhook_notifications' => 'boolean',
'docker_cleanup_failure_webhook_notifications' => 'boolean',
'server_disk_usage_webhook_notifications' => 'boolean',
'server_reachable_webhook_notifications' => 'boolean',
'server_unreachable_webhook_notifications' => 'boolean',
'server_patch_webhook_notifications' => 'boolean',
'traefik_outdated_webhook_notifications' => 'boolean',
];
}
public function team()
{
return $this->belongsTo(Team::class);
}
public function isEnabled()
{
return $this->webhook_enabled;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Project.php | app/Models/Project.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use OpenApi\Attributes as OA;
use Visus\Cuid2\Cuid2;
#[OA\Schema(
description: 'Project model',
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'uuid' => ['type' => 'string'],
'name' => ['type' => 'string'],
'description' => ['type' => 'string'],
'environments' => new OA\Property(
property: 'environments',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/Environment'),
description: 'The environments of the project.'
),
]
)]
class Project extends BaseModel
{
use ClearsGlobalSearchCache;
use HasSafeStringAttribute;
protected $guarded = [];
/**
* Get query builder for projects owned by current team.
* If you need all projects without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return Project::whereTeamId(currentTeam()->id)->orderByRaw('LOWER(name)');
}
/**
* Get all projects owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return Project::ownedByCurrentTeam()->get();
});
}
protected static function booted()
{
static::created(function ($project) {
ProjectSetting::create([
'project_id' => $project->id,
]);
Environment::create([
'name' => 'production',
'project_id' => $project->id,
'uuid' => (string) new Cuid2,
]);
});
static::deleting(function ($project) {
$project->environments()->delete();
$project->settings()->delete();
$shared_variables = $project->environment_variables();
foreach ($shared_variables as $shared_variable) {
$shared_variable->delete();
}
});
}
public function environment_variables()
{
return $this->hasMany(SharedEnvironmentVariable::class);
}
public function environments()
{
return $this->hasMany(Environment::class);
}
public function settings()
{
return $this->hasOne(ProjectSetting::class);
}
public function team()
{
return $this->belongsTo(Team::class);
}
public function services()
{
return $this->hasManyThrough(Service::class, Environment::class);
}
public function applications()
{
return $this->hasManyThrough(Application::class, Environment::class);
}
public function postgresqls()
{
return $this->hasManyThrough(StandalonePostgresql::class, Environment::class);
}
public function redis()
{
return $this->hasManyThrough(StandaloneRedis::class, Environment::class);
}
public function keydbs()
{
return $this->hasManyThrough(StandaloneKeydb::class, Environment::class);
}
public function dragonflies()
{
return $this->hasManyThrough(StandaloneDragonfly::class, Environment::class);
}
public function clickhouses()
{
return $this->hasManyThrough(StandaloneClickhouse::class, Environment::class);
}
public function mongodbs()
{
return $this->hasManyThrough(StandaloneMongodb::class, Environment::class);
}
public function mysqls()
{
return $this->hasManyThrough(StandaloneMysql::class, Environment::class);
}
public function mariadbs()
{
return $this->hasManyThrough(StandaloneMariadb::class, Environment::class);
}
public function isEmpty()
{
return $this->applications()->count() == 0 &&
$this->redis()->count() == 0 &&
$this->postgresqls()->count() == 0 &&
$this->mysqls()->count() == 0 &&
$this->keydbs()->count() == 0 &&
$this->dragonflies()->count() == 0 &&
$this->clickhouses()->count() == 0 &&
$this->mariadbs()->count() == 0 &&
$this->mongodbs()->count() == 0 &&
$this->services()->count() == 0;
}
public function databases()
{
return $this->postgresqls()->get()->merge($this->redis()->get())->merge($this->mongodbs()->get())->merge($this->mysqls()->get())->merge($this->mariadbs()->get())->merge($this->keydbs()->get())->merge($this->dragonflies()->get())->merge($this->clickhouses()->get());
}
public function navigateTo()
{
if ($this->environments->count() === 1) {
return route('project.resource.index', [
'project_uuid' => $this->uuid,
'environment_uuid' => $this->environments->first()->uuid,
]);
}
return route('project.show', ['project_uuid' => $this->uuid]);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/TelegramNotificationSettings.php | app/Models/TelegramNotificationSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class TelegramNotificationSettings extends Model
{
use Notifiable;
public $timestamps = false;
protected $fillable = [
'team_id',
'telegram_enabled',
'telegram_token',
'telegram_chat_id',
'deployment_success_telegram_notifications',
'deployment_failure_telegram_notifications',
'status_change_telegram_notifications',
'backup_success_telegram_notifications',
'backup_failure_telegram_notifications',
'scheduled_task_success_telegram_notifications',
'scheduled_task_failure_telegram_notifications',
'docker_cleanup_telegram_notifications',
'server_disk_usage_telegram_notifications',
'server_reachable_telegram_notifications',
'server_unreachable_telegram_notifications',
'server_patch_telegram_notifications',
'traefik_outdated_telegram_notifications',
'telegram_notifications_deployment_success_thread_id',
'telegram_notifications_deployment_failure_thread_id',
'telegram_notifications_status_change_thread_id',
'telegram_notifications_backup_success_thread_id',
'telegram_notifications_backup_failure_thread_id',
'telegram_notifications_scheduled_task_success_thread_id',
'telegram_notifications_scheduled_task_failure_thread_id',
'telegram_notifications_docker_cleanup_thread_id',
'telegram_notifications_server_disk_usage_thread_id',
'telegram_notifications_server_reachable_thread_id',
'telegram_notifications_server_unreachable_thread_id',
'telegram_notifications_server_patch_thread_id',
'telegram_notifications_traefik_outdated_thread_id',
];
protected $casts = [
'telegram_enabled' => 'boolean',
'telegram_token' => 'encrypted',
'telegram_chat_id' => 'encrypted',
'deployment_success_telegram_notifications' => 'boolean',
'deployment_failure_telegram_notifications' => 'boolean',
'status_change_telegram_notifications' => 'boolean',
'backup_success_telegram_notifications' => 'boolean',
'backup_failure_telegram_notifications' => 'boolean',
'scheduled_task_success_telegram_notifications' => 'boolean',
'scheduled_task_failure_telegram_notifications' => 'boolean',
'docker_cleanup_telegram_notifications' => 'boolean',
'server_disk_usage_telegram_notifications' => 'boolean',
'server_reachable_telegram_notifications' => 'boolean',
'server_unreachable_telegram_notifications' => 'boolean',
'server_patch_telegram_notifications' => 'boolean',
'traefik_outdated_telegram_notifications' => 'boolean',
'telegram_notifications_deployment_success_thread_id' => 'encrypted',
'telegram_notifications_deployment_failure_thread_id' => 'encrypted',
'telegram_notifications_status_change_thread_id' => 'encrypted',
'telegram_notifications_backup_success_thread_id' => 'encrypted',
'telegram_notifications_backup_failure_thread_id' => 'encrypted',
'telegram_notifications_scheduled_task_success_thread_id' => 'encrypted',
'telegram_notifications_scheduled_task_failure_thread_id' => 'encrypted',
'telegram_notifications_docker_cleanup_thread_id' => 'encrypted',
'telegram_notifications_server_disk_usage_thread_id' => 'encrypted',
'telegram_notifications_server_reachable_thread_id' => 'encrypted',
'telegram_notifications_server_unreachable_thread_id' => 'encrypted',
'telegram_notifications_server_patch_thread_id' => 'encrypted',
'telegram_notifications_traefik_outdated_thread_id' => 'encrypted',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function isEnabled()
{
return $this->telegram_enabled;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/S3Storage.php | app/Models/S3Storage.php | <?php
namespace App\Models;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Storage;
class S3Storage extends BaseModel
{
use HasFactory, HasSafeStringAttribute;
protected $guarded = [];
protected $casts = [
'is_usable' => 'boolean',
'key' => 'encrypted',
'secret' => 'encrypted',
];
/**
* Boot the model and register event listeners.
*/
protected static function boot(): void
{
parent::boot();
// Trim whitespace from credentials before saving to prevent
// "Malformed Access Key Id" errors from accidental whitespace in pasted values.
// Note: We use the saving event instead of Attribute mutators because key/secret
// use Laravel's 'encrypted' cast. Attribute mutators fire before casts, which
// would cause issues with the encryption/decryption cycle.
static::saving(function (S3Storage $storage) {
if ($storage->key !== null) {
$storage->key = trim($storage->key);
}
if ($storage->secret !== null) {
$storage->secret = trim($storage->secret);
}
});
}
public static function ownedByCurrentTeam(array $select = ['*'])
{
$selectArray = collect($select)->concat(['id']);
return S3Storage::whereTeamId(currentTeam()->id)->select($selectArray->all())->orderBy('name');
}
public function isUsable()
{
return $this->is_usable;
}
public function team()
{
return $this->belongsTo(Team::class);
}
public function awsUrl()
{
return "{$this->endpoint}/{$this->bucket}";
}
protected function path(): Attribute
{
return Attribute::make(
set: function (?string $value) {
if ($value === null || $value === '') {
return null;
}
return str($value)->trim()->start('/')->value();
}
);
}
/**
* Trim whitespace from endpoint to prevent malformed URLs.
*/
protected function endpoint(): Attribute
{
return Attribute::make(
set: fn (?string $value) => $value ? trim($value) : null,
);
}
/**
* Trim whitespace from bucket name to prevent connection errors.
*/
protected function bucket(): Attribute
{
return Attribute::make(
set: fn (?string $value) => $value ? trim($value) : null,
);
}
/**
* Trim whitespace from region to prevent connection errors.
*/
protected function region(): Attribute
{
return Attribute::make(
set: fn (?string $value) => $value ? trim($value) : null,
);
}
public function testConnection(bool $shouldSave = false)
{
try {
$disk = Storage::build([
'driver' => 's3',
'region' => $this['region'],
'key' => $this['key'],
'secret' => $this['secret'],
'bucket' => $this['bucket'],
'endpoint' => $this['endpoint'],
'use_path_style_endpoint' => true,
]);
// Test the connection by listing files with ListObjectsV2 (S3)
$disk->files();
$this->unusable_email_sent = false;
$this->is_usable = true;
} catch (\Throwable $e) {
$this->is_usable = false;
if ($this->unusable_email_sent === false && is_transactional_emails_enabled()) {
$mail = new MailMessage;
$mail->subject('Coolify: S3 Storage Connection Error');
$mail->view('emails.s3-connection-error', ['name' => $this->name, 'reason' => $e->getMessage(), 'url' => route('storage.show', ['storage_uuid' => $this->uuid])]);
// Load the team with its members and their roles explicitly
$team = $this->team()->with(['members' => function ($query) {
$query->withPivot('role');
}])->first();
// Get admins directly from the pivot relationship for this specific team
$users = $team->members()->wherePivotIn('role', ['admin', 'owner'])->get(['users.id', 'users.email']);
foreach ($users as $user) {
send_user_an_email($mail, $user->email);
}
$this->unusable_email_sent = true;
}
throw $e;
} finally {
if ($shouldSave) {
$this->save();
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/SharedEnvironmentVariable.php | app/Models/SharedEnvironmentVariable.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SharedEnvironmentVariable extends Model
{
protected $guarded = [];
protected $casts = [
'key' => 'string',
'value' => 'encrypted',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function project()
{
return $this->belongsTo(Project::class);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Service.php | app/Models/Service.php | <?php
namespace App\Models;
use App\Enums\ProcessStatus;
use App\Services\ContainerStatusAggregator;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use OpenApi\Attributes as OA;
use Spatie\Activitylog\Models\Activity;
use Spatie\Url\Url;
use Visus\Cuid2\Cuid2;
#[OA\Schema(
description: 'Service model',
type: 'object',
properties: [
'id' => ['type' => 'integer', 'description' => 'The unique identifier of the service. Only used for database identification.'],
'uuid' => ['type' => 'string', 'description' => 'The unique identifier of the service.'],
'name' => ['type' => 'string', 'description' => 'The name of the service.'],
'environment_id' => ['type' => 'integer', 'description' => 'The unique identifier of the environment where the service is attached to.'],
'server_id' => ['type' => 'integer', 'description' => 'The unique identifier of the server where the service is running.'],
'description' => ['type' => 'string', 'description' => 'The description of the service.'],
'docker_compose_raw' => ['type' => 'string', 'description' => 'The raw docker-compose.yml file of the service.'],
'docker_compose' => ['type' => 'string', 'description' => 'The docker-compose.yml file that is parsed and modified by Coolify.'],
'destination_type' => ['type' => 'string', 'description' => 'Destination type.'],
'destination_id' => ['type' => 'integer', 'description' => 'The unique identifier of the destination where the service is running.'],
'connect_to_docker_network' => ['type' => 'boolean', 'description' => 'The flag to connect the service to the predefined Docker network.'],
'is_container_label_escape_enabled' => ['type' => 'boolean', 'description' => 'The flag to enable the container label escape.'],
'is_container_label_readonly_enabled' => ['type' => 'boolean', 'description' => 'The flag to enable the container label readonly.'],
'config_hash' => ['type' => 'string', 'description' => 'The hash of the service configuration.'],
'service_type' => ['type' => 'string', 'description' => 'The type of the service.'],
'created_at' => ['type' => 'string', 'description' => 'The date and time when the service was created.'],
'updated_at' => ['type' => 'string', 'description' => 'The date and time when the service was last updated.'],
'deleted_at' => ['type' => 'string', 'description' => 'The date and time when the service was deleted.'],
],
)]
class Service extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
private static $parserVersion = '5';
protected $guarded = [];
protected $appends = ['server_status', 'status'];
protected static function booted()
{
static::creating(function ($service) {
if (blank($service->name)) {
$service->name = 'service-'.(new Cuid2);
}
});
static::created(function ($service) {
$service->compose_parsing_version = self::$parserVersion;
$service->save();
});
}
public function isConfigurationChanged(bool $save = false)
{
$domains = $this->applications()->get()->pluck('fqdn')->sort()->toArray();
$domains = implode(',', $domains);
$applicationImages = $this->applications()->get()->pluck('image')->sort();
$databaseImages = $this->databases()->get()->pluck('image')->sort();
$images = $applicationImages->merge($databaseImages);
$images = implode(',', $images->toArray());
$applicationStorages = $this->applications()->get()->pluck('persistentStorages')->flatten()->sortBy('id');
$databaseStorages = $this->databases()->get()->pluck('persistentStorages')->flatten()->sortBy('id');
$storages = $applicationStorages->merge($databaseStorages)->implode('updated_at');
$newConfigHash = $images.$domains.$images.$storages;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->server->isFunctional();
}
);
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->contains('exited');
}
public function isStarting(): bool
{
try {
$activity = Activity::where('properties->type_uuid', $this->uuid)->latest()->first();
$status = data_get($activity, 'properties.status');
return $status === ProcessStatus::QUEUED->value || $status === ProcessStatus::IN_PROGRESS->value;
} catch (\Throwable) {
return false;
}
}
public function type()
{
return 'service';
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
/**
* Get query builder for services owned by current team.
* If you need all services without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return Service::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all services owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return Service::ownedByCurrentTeam()->get();
});
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteConnectedNetworks()
{
$server = data_get($this, 'destination.server');
instant_remote_process(["docker network disconnect {$this->uuid} coolify-proxy"], $server, false);
instant_remote_process(["docker network rm {$this->uuid}"], $server, false);
}
/**
* Calculate the service's aggregate status from its applications and databases.
*
* This method aggregates status from Eloquent model relationships (not Docker containers).
* It differs from the CalculatesExcludedStatus trait which works with Docker container objects
* during container inspection. This accessor runs on-demand for UI display and works with
* already-stored status strings from the database.
*
* Status format: "{status}:{health}" or "{status}:{health}:excluded"
* - Status values: running, exited, degraded, starting, paused, restarting
* - Health values: healthy, unhealthy, unknown
* - :excluded suffix: Indicates all containers are excluded from health monitoring
*
* @return string The aggregate status in format "status:health" or "status:health:excluded"
*/
public function getStatusAttribute()
{
if ($this->isStarting()) {
return 'starting:unhealthy';
}
$applications = $this->applications;
$databases = $this->databases;
[$complexStatus, $complexHealth, $hasNonExcluded] = $this->aggregateResourceStatuses(
$applications,
$databases,
excludedOnly: false
);
// If all services are excluded from status checks, calculate status from excluded containers
// but mark it with :excluded to indicate monitoring is disabled
if (! $hasNonExcluded && ($complexStatus === null && $complexHealth === null)) {
[$excludedStatus, $excludedHealth] = $this->aggregateResourceStatuses(
$applications,
$databases,
excludedOnly: true
);
// Return status with :excluded suffix to indicate monitoring is disabled
if ($excludedStatus && $excludedHealth) {
return "{$excludedStatus}:{$excludedHealth}:excluded";
}
// If no status was calculated at all (no containers exist), return unknown
if ($excludedStatus === null && $excludedHealth === null) {
return 'unknown:unknown:excluded';
}
return 'exited';
}
// If health is null/empty, return just the status without trailing colon
if ($complexHealth === null || $complexHealth === '') {
return $complexStatus;
}
return "{$complexStatus}:{$complexHealth}";
}
/**
* Aggregate status and health from collections of applications and databases.
*
* This helper method consolidates status aggregation logic using ContainerStatusAggregator.
* It processes container status strings stored in the database (not live Docker data).
*
* @param \Illuminate\Database\Eloquent\Collection $applications Collection of Application models
* @param \Illuminate\Database\Eloquent\Collection $databases Collection of Database models
* @param bool $excludedOnly If true, only process excluded containers; if false, only process non-excluded
* @return array{0: string|null, 1: string|null, 2?: bool} [status, health, hasNonExcluded (only when excludedOnly=false)]
*/
private function aggregateResourceStatuses($applications, $databases, bool $excludedOnly = false): array
{
$hasNonExcluded = false;
$statusStrings = collect();
// Process both applications and databases using the same logic
$resources = $applications->concat($databases);
foreach ($resources as $resource) {
$isExcluded = $resource->exclude_from_status || str($resource->status)->contains(':excluded');
// Filter based on excludedOnly flag
if ($excludedOnly && ! $isExcluded) {
continue;
}
if (! $excludedOnly && $isExcluded) {
continue;
}
if (! $excludedOnly) {
$hasNonExcluded = true;
}
// Strip :excluded suffix before aggregation (it's in the 3rd part of "status:health:excluded")
$status = str($resource->status)->before(':excluded')->toString();
$statusStrings->push($status);
}
// If no status strings collected, return nulls
if ($statusStrings->isEmpty()) {
return $excludedOnly ? [null, null] : [null, null, $hasNonExcluded];
}
// Use ContainerStatusAggregator service for state machine logic
$aggregator = new ContainerStatusAggregator;
$aggregatedStatus = $aggregator->aggregateFromStrings($statusStrings);
// Parse the aggregated "status:health" string
$parts = explode(':', $aggregatedStatus);
$status = $parts[0] ?? null;
$health = $parts[1] ?? null;
if ($excludedOnly) {
return [$status, $health];
}
return [$status, $health, $hasNonExcluded];
}
public function extraFields()
{
$fields = collect([]);
$applications = $this->applications()->get();
foreach ($applications as $application) {
$image = str($application->image)->before(':');
if ($image->isEmpty()) {
continue;
}
switch ($image) {
case $image->contains('drizzle-team/gateway'):
$data = collect([]);
$masterpass = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_DRIZZLE')->first();
$data = $data->merge([
'Master Password' => [
'key' => data_get($masterpass, 'key'),
'value' => data_get($masterpass, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
$fields->put('Drizzle', $data->toArray());
break;
case $image->contains('castopod'):
$data = collect([]);
$disable_https = $this->environment_variables()->where('key', 'CP_DISABLE_HTTPS')->first();
if ($disable_https) {
$data = $data->merge([
'Disable HTTPS' => [
'key' => 'CP_DISABLE_HTTPS',
'value' => data_get($disable_https, 'value'),
'rules' => 'required',
'customHelper' => 'If you want to use https, set this to 0. Variable name: CP_DISABLE_HTTPS',
],
]);
}
$fields->put('Castopod', $data->toArray());
break;
case $image->contains('label-studio'):
$data = collect([]);
$username = $this->environment_variables()->where('key', 'LABEL_STUDIO_USERNAME')->first();
$password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_LABELSTUDIO')->first();
if ($username) {
$data = $data->merge([
'Username' => [
'key' => 'LABEL_STUDIO_USERNAME',
'value' => data_get($username, 'value'),
'rules' => 'required',
],
]);
}
if ($password) {
$data = $data->merge([
'Password' => [
'key' => data_get($password, 'key'),
'value' => data_get($password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Label Studio', $data->toArray());
break;
case $image->contains('litellm'):
$data = collect([]);
$username = $this->environment_variables()->where('key', 'SERVICE_USER_UI')->first();
$password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_UI')->first();
if ($username) {
$data = $data->merge([
'Username' => [
'key' => data_get($username, 'key'),
'value' => data_get($username, 'value'),
'rules' => 'required',
],
]);
}
if ($password) {
$data = $data->merge([
'Password' => [
'key' => data_get($password, 'key'),
'value' => data_get($password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Litellm', $data->toArray());
break;
case $image->contains('langfuse'):
$data = collect([]);
$email = $this->environment_variables()->where('key', 'LANGFUSE_INIT_USER_EMAIL')->first();
if ($email) {
$data = $data->merge([
'Admin Email' => [
'key' => data_get($email, 'key'),
'value' => data_get($email, 'value'),
'rules' => 'required|email',
],
]);
}
$password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_LANGFUSE')->first();
if ($password) {
$data = $data->merge([
'Admin Password' => [
'key' => data_get($password, 'key'),
'value' => data_get($password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Langfuse', $data->toArray());
break;
case $image->contains('invoiceninja'):
$data = collect([]);
$email = $this->environment_variables()->where('key', 'IN_USER_EMAIL')->first();
$data = $data->merge([
'Email' => [
'key' => data_get($email, 'key'),
'value' => data_get($email, 'value'),
'rules' => 'required|email',
],
]);
$password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_INVOICENINJAUSER')->first();
$data = $data->merge([
'Password' => [
'key' => data_get($password, 'key'),
'value' => data_get($password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
$fields->put('Invoice Ninja', $data->toArray());
break;
case $image->contains('argilla'):
$data = collect([]);
$api_key = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_APIKEY')->first();
$data = $data->merge([
'API Key' => [
'key' => data_get($api_key, 'key'),
'value' => data_get($api_key, 'value'),
'isPassword' => true,
'rules' => 'required',
],
]);
$data = $data->merge([
'API Key' => [
'key' => data_get($api_key, 'key'),
'value' => data_get($api_key, 'value'),
'isPassword' => true,
'rules' => 'required',
],
]);
$username = $this->environment_variables()->where('key', 'ARGILLA_USERNAME')->first();
$data = $data->merge([
'Username' => [
'key' => data_get($username, 'key'),
'value' => data_get($username, 'value'),
'rules' => 'required',
],
]);
$password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_ARGILLA')->first();
$data = $data->merge([
'Password' => [
'key' => data_get($password, 'key'),
'value' => data_get($password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
$fields->put('Argilla', $data->toArray());
break;
case $image->contains('rabbitmq'):
$data = collect([]);
$host_port = $this->environment_variables()->where('key', 'PORT')->first();
$username = $this->environment_variables()->where('key', 'SERVICE_USER_RABBITMQ')->first();
$password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_RABBITMQ')->first();
if ($host_port) {
$data = $data->merge([
'Host Port Binding' => [
'key' => data_get($host_port, 'key'),
'value' => data_get($host_port, 'value'),
'rules' => 'required',
],
]);
}
if ($username) {
$data = $data->merge([
'Username' => [
'key' => data_get($username, 'key'),
'value' => data_get($username, 'value'),
'rules' => 'required',
],
]);
}
if ($password) {
$data = $data->merge([
'Password' => [
'key' => data_get($password, 'key'),
'value' => data_get($password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('RabbitMQ', $data->toArray());
break;
case $image->contains('tolgee'):
$data = collect([]);
$admin_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_TOLGEE')->first();
$data = $data->merge([
'Admin User' => [
'key' => 'TOLGEE_AUTHENTICATION_INITIAL_USERNAME',
'value' => 'admin',
'readonly' => true,
'rules' => 'required',
],
]);
if ($admin_password) {
$data = $data->merge([
'Admin Password' => [
'key' => data_get($admin_password, 'key'),
'value' => data_get($admin_password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Tolgee', $data->toArray());
break;
case $image->contains('logto'):
$data = collect([]);
$logto_endpoint = $this->environment_variables()->where('key', 'LOGTO_ENDPOINT')->first();
$logto_admin_endpoint = $this->environment_variables()->where('key', 'LOGTO_ADMIN_ENDPOINT')->first();
if ($logto_endpoint) {
$data = $data->merge([
'Endpoint' => [
'key' => data_get($logto_endpoint, 'key'),
'value' => data_get($logto_endpoint, 'value'),
'rules' => 'required|url',
],
]);
}
if ($logto_admin_endpoint) {
$data = $data->merge([
'Admin Endpoint' => [
'key' => data_get($logto_admin_endpoint, 'key'),
'value' => data_get($logto_admin_endpoint, 'value'),
'rules' => 'required|url',
],
]);
}
$fields->put('Logto', $data->toArray());
break;
case $image->contains('unleash-server'):
$data = collect([]);
$admin_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_UNLEASH')->first();
$data = $data->merge([
'Admin User' => [
'key' => 'SERVICE_USER_UNLEASH',
'value' => 'admin',
'readonly' => true,
'rules' => 'required',
],
]);
if ($admin_password) {
$data = $data->merge([
'Admin Password' => [
'key' => data_get($admin_password, 'key'),
'value' => data_get($admin_password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Unleash', $data->toArray());
break;
case $image->contains('grafana'):
$data = collect([]);
$admin_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_GRAFANA')->first();
$data = $data->merge([
'Admin User' => [
'key' => 'GF_SECURITY_ADMIN_USER',
'value' => 'admin',
'readonly' => true,
'rules' => 'required',
],
]);
if ($admin_password) {
$data = $data->merge([
'Admin Password' => [
'key' => data_get($admin_password, 'key'),
'value' => data_get($admin_password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Grafana', $data->toArray());
break;
case $image->contains('elasticsearch'):
$data = collect([]);
$elastic_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_ELASTICSEARCH')->first();
if ($elastic_password) {
$data = $data->merge([
'Password (default user: elastic)' => [
'key' => data_get($elastic_password, 'key'),
'value' => data_get($elastic_password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Elasticsearch', $data->toArray());
break;
case $image->contains('directus'):
$data = collect([]);
$admin_email = $this->environment_variables()->where('key', 'ADMIN_EMAIL')->first();
$admin_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_ADMIN')->first();
if ($admin_email) {
$data = $data->merge([
'Admin Email' => [
'key' => data_get($admin_email, 'key'),
'value' => data_get($admin_email, 'value'),
'rules' => 'required|email',
],
]);
}
if ($admin_password) {
$data = $data->merge([
'Admin Password' => [
'key' => data_get($admin_password, 'key'),
'value' => data_get($admin_password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Directus', $data->toArray());
break;
case $image->contains('kong'):
$data = collect([]);
$dashboard_user = $this->environment_variables()->where('key', 'SERVICE_USER_ADMIN')->first();
$dashboard_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_ADMIN')->first();
if ($dashboard_user) {
$data = $data->merge([
'Dashboard User' => [
'key' => data_get($dashboard_user, 'key'),
'value' => data_get($dashboard_user, 'value'),
'rules' => 'required',
],
]);
}
if ($dashboard_password) {
$data = $data->merge([
'Dashboard Password' => [
'key' => data_get($dashboard_password, 'key'),
'value' => data_get($dashboard_password, 'value'),
'rules' => 'required',
'isPassword' => true,
],
]);
}
$fields->put('Supabase', $data->toArray());
case $image->contains('minio'):
$data = collect([]);
$console_url = $this->environment_variables()->where('key', 'MINIO_BROWSER_REDIRECT_URL')->first();
$s3_api_url = $this->environment_variables()->where('key', 'MINIO_SERVER_URL')->first();
$admin_user = $this->environment_variables()->where('key', 'SERVICE_USER_MINIO')->first();
if (is_null($admin_user)) {
$admin_user = $this->environment_variables()->where('key', 'MINIO_ROOT_USER')->first();
}
$admin_password = $this->environment_variables()->where('key', 'SERVICE_PASSWORD_MINIO')->first();
if (is_null($admin_password)) {
$admin_password = $this->environment_variables()->where('key', 'MINIO_ROOT_PASSWORD')->first();
}
if ($console_url) {
$data = $data->merge([
'Console URL' => [
'key' => data_get($console_url, 'key'),
'value' => data_get($console_url, 'value'),
'rules' => 'required|url',
],
]);
}
if ($s3_api_url) {
$data = $data->merge([
'S3 API URL' => [
'key' => data_get($s3_api_url, 'key'),
'value' => data_get($s3_api_url, 'value'),
'rules' => 'required|url',
],
]);
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/LocalFileVolume.php | app/Models/LocalFileVolume.php | <?php
namespace App\Models;
use App\Events\FileStorageChanged;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Symfony\Component\Yaml\Yaml;
class LocalFileVolume extends BaseModel
{
protected $casts = [
// 'fs_path' => 'encrypted',
// 'mount_path' => 'encrypted',
'content' => 'encrypted',
'is_directory' => 'boolean',
];
use HasFactory;
protected $guarded = [];
public $appends = ['is_binary'];
protected static function booted()
{
static::created(function (LocalFileVolume $fileVolume) {
$fileVolume->load(['service']);
dispatch(new \App\Jobs\ServerStorageSaveJob($fileVolume));
});
}
protected function isBinary(): Attribute
{
return Attribute::make(
get: function () {
return $this->content === '[binary file]';
}
);
}
public function service()
{
return $this->morphTo('resource');
}
public function loadStorageOnServer()
{
$this->load(['service']);
$isService = data_get($this->resource, 'service');
if ($isService) {
$workdir = $this->resource->service->workdir();
$server = $this->resource->service->server;
} else {
$workdir = $this->resource->workdir();
$server = $this->resource->destination->server;
}
$commands = collect([]);
$path = data_get_str($this, 'fs_path');
if ($path->startsWith('.')) {
$path = $path->after('.');
$path = $workdir.$path;
}
// Validate and escape path to prevent command injection
validateShellSafePath($path, 'storage path');
$escapedPath = escapeshellarg($path);
$isFile = instant_remote_process(["test -f {$escapedPath} && echo OK || echo NOK"], $server);
if ($isFile === 'OK') {
$content = instant_remote_process(["cat {$escapedPath}"], $server, false);
// Check if content contains binary data by looking for null bytes or non-printable characters
if (str_contains($content, "\0") || preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $content)) {
$content = '[binary file]';
}
$this->content = $content;
$this->is_directory = false;
$this->save();
}
}
public function deleteStorageOnServer()
{
$this->load(['service']);
$isService = data_get($this->resource, 'service');
if ($isService) {
$workdir = $this->resource->service->workdir();
$server = $this->resource->service->server;
} else {
$workdir = $this->resource->workdir();
$server = $this->resource->destination->server;
}
$commands = collect([]);
$path = data_get_str($this, 'fs_path');
if ($path->startsWith('.')) {
$path = $path->after('.');
$path = $workdir.$path;
}
// Validate and escape path to prevent command injection
validateShellSafePath($path, 'storage path');
$escapedPath = escapeshellarg($path);
$isFile = instant_remote_process(["test -f {$escapedPath} && echo OK || echo NOK"], $server);
$isDir = instant_remote_process(["test -d {$escapedPath} && echo OK || echo NOK"], $server);
if ($path && $path != '/' && $path != '.' && $path != '..') {
if ($isFile === 'OK') {
$commands->push("rm -rf {$escapedPath} > /dev/null 2>&1 || true");
} elseif ($isDir === 'OK') {
$commands->push("rm -rf {$escapedPath} > /dev/null 2>&1 || true");
$commands->push("rmdir {$escapedPath} > /dev/null 2>&1 || true");
}
}
if ($commands->count() > 0) {
return instant_remote_process($commands, $server);
}
}
public function saveStorageOnServer()
{
$this->load(['service']);
$isService = data_get($this->resource, 'service');
if ($isService) {
$workdir = $this->resource->service->workdir();
$server = $this->resource->service->server;
} else {
$workdir = $this->resource->workdir();
$server = $this->resource->destination->server;
}
$commands = collect([]);
if ($this->is_directory) {
$commands->push("mkdir -p $this->fs_path > /dev/null 2>&1 || true");
$commands->push("mkdir -p $workdir > /dev/null 2>&1 || true");
$commands->push("cd $workdir");
}
if (str($this->fs_path)->startsWith('.') || str($this->fs_path)->startsWith('/') || str($this->fs_path)->startsWith('~')) {
$parent_dir = str($this->fs_path)->beforeLast('/');
if ($parent_dir != '') {
$commands->push("mkdir -p $parent_dir > /dev/null 2>&1 || true");
}
}
$path = data_get_str($this, 'fs_path');
$content = data_get($this, 'content');
if ($path->startsWith('.')) {
$path = $path->after('.');
$path = $workdir.$path;
}
// Validate and escape path to prevent command injection
validateShellSafePath($path, 'storage path');
$escapedPath = escapeshellarg($path);
$isFile = instant_remote_process(["test -f {$escapedPath} && echo OK || echo NOK"], $server);
$isDir = instant_remote_process(["test -d {$escapedPath} && echo OK || echo NOK"], $server);
if ($isFile === 'OK' && $this->is_directory) {
$content = instant_remote_process(["cat {$escapedPath}"], $server, false);
$this->is_directory = false;
$this->content = $content;
$this->save();
FileStorageChanged::dispatch(data_get($server, 'team_id'));
throw new \Exception('The following file is a file on the server, but you are trying to mark it as a directory. Please delete the file on the server or mark it as directory.');
} elseif ($isDir === 'OK' && ! $this->is_directory) {
if ($path === '/' || $path === '.' || $path === '..' || $path === '' || str($path)->isEmpty() || is_null($path)) {
$this->is_directory = true;
$this->save();
throw new \Exception('The following file is a directory on the server, but you are trying to mark it as a file. <br><br>Please delete the directory on the server or mark it as directory.');
}
instant_remote_process([
"rm -fr {$escapedPath}",
"touch {$escapedPath}",
], $server, false);
FileStorageChanged::dispatch(data_get($server, 'team_id'));
}
if ($isDir === 'NOK' && ! $this->is_directory) {
$chmod = data_get($this, 'chmod');
$chown = data_get($this, 'chown');
if ($content) {
$content = base64_encode($content);
$commands->push("echo '$content' | base64 -d | tee {$escapedPath} > /dev/null");
} else {
$commands->push("touch {$escapedPath}");
}
$commands->push("chmod +x {$escapedPath}");
if ($chown) {
$commands->push("chown $chown {$escapedPath}");
}
if ($chmod) {
$commands->push("chmod $chmod {$escapedPath}");
}
} elseif ($isDir === 'NOK' && $this->is_directory) {
$commands->push("mkdir -p {$escapedPath} > /dev/null 2>&1 || true");
}
return instant_remote_process($commands, $server);
}
// Accessor for convenient access
protected function plainMountPath(): Attribute
{
return Attribute::make(
get: fn () => $this->mount_path,
set: fn ($value) => $this->mount_path = $value
);
}
// Scope for searching
public function scopeWherePlainMountPath($query, $path)
{
return $query->get()->where('plain_mount_path', $path);
}
// Check if this volume belongs to a service resource
public function isServiceResource(): bool
{
return in_array($this->resource_type, [
'App\Models\ServiceApplication',
'App\Models\ServiceDatabase',
]);
}
// Determine if this volume should be read-only in the UI
// File/directory mounts can be edited even for services
public function shouldBeReadOnlyInUI(): bool
{
// Check for explicit :ro flag in compose (existing logic)
return $this->isReadOnlyVolume();
}
// Check if this volume is read-only by parsing the docker-compose content
public function isReadOnlyVolume(): bool
{
try {
// Only check for services
$service = $this->service;
if (! $service || ! method_exists($service, 'service')) {
return false;
}
$actualService = $service->service;
if (! $actualService || ! $actualService->docker_compose_raw) {
return false;
}
// Parse the docker-compose content
$compose = Yaml::parse($actualService->docker_compose_raw);
if (! isset($compose['services'])) {
return false;
}
// Find the service that this volume belongs to
$serviceName = $service->name;
if (! isset($compose['services'][$serviceName]['volumes'])) {
return false;
}
$volumes = $compose['services'][$serviceName]['volumes'];
// Check each volume to find a match
// Note: We match on mount_path (container path) only, since fs_path gets transformed
// from relative (./file) to absolute (/data/coolify/services/uuid/file) during parsing
foreach ($volumes as $volume) {
// Volume can be string like "host:container:ro" or "host:container"
if (is_string($volume)) {
$parts = explode(':', $volume);
// Check if this volume matches our mount_path
if (count($parts) >= 2) {
$containerPath = $parts[1];
$options = $parts[2] ?? null;
// Match based on mount_path
// Remove leading slash from mount_path if present for comparison
$mountPath = str($this->mount_path)->ltrim('/')->toString();
$containerPathClean = str($containerPath)->ltrim('/')->toString();
if ($mountPath === $containerPathClean || $this->mount_path === $containerPath) {
return $options === 'ro';
}
}
} elseif (is_array($volume)) {
// Long-form syntax: { type: bind, source: ..., target: ..., read_only: true }
$containerPath = data_get($volume, 'target');
$readOnly = data_get($volume, 'read_only', false);
// Match based on mount_path
// Remove leading slash from mount_path if present for comparison
$mountPath = str($this->mount_path)->ltrim('/')->toString();
$containerPathClean = str($containerPath)->ltrim('/')->toString();
if ($mountPath === $containerPathClean || $this->mount_path === $containerPath) {
return $readOnly === true;
}
}
}
return false;
} catch (\Throwable $e) {
ray($e->getMessage(), 'Error checking read-only volume');
return false;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Server.php | app/Models/Server.php | <?php
namespace App\Models;
use App\Actions\Proxy\StartProxy;
use App\Actions\Server\InstallDocker;
use App\Actions\Server\InstallPrerequisites;
use App\Actions\Server\StartSentinel;
use App\Actions\Server\ValidatePrerequisites;
use App\Enums\ProxyTypes;
use App\Events\ServerReachabilityChanged;
use App\Helpers\SslHelper;
use App\Jobs\CheckAndStartSentinelJob;
use App\Jobs\RegenerateSslCertJob;
use App\Notifications\Server\Reachable;
use App\Notifications\Server\Unreachable;
use App\Services\ConfigurationRepository;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Stringable;
use OpenApi\Attributes as OA;
use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;
use Spatie\SchemalessAttributes\SchemalessAttributesTrait;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
use Visus\Cuid2\Cuid2;
/**
* @property array{
* current: string,
* latest: string,
* type: 'patch_update'|'minor_upgrade',
* checked_at: string,
* newer_branch_target?: string,
* newer_branch_latest?: string,
* upgrade_target?: string
* }|null $traefik_outdated_info Traefik version tracking information.
*
* This JSON column stores information about outdated Traefik proxy versions on this server.
* The structure varies depending on the type of update available:
*
* **For patch updates** (e.g., 3.5.0 → 3.5.2):
* ```php
* [
* 'current' => '3.5.0', // Current version (without 'v' prefix)
* 'latest' => '3.5.2', // Latest patch version available
* 'type' => 'patch_update', // Update type identifier
* 'checked_at' => '2025-11-14T10:00:00Z', // ISO8601 timestamp
* 'newer_branch_target' => 'v3.6', // (Optional) Available major/minor version
* 'newer_branch_latest' => '3.6.2' // (Optional) Latest version in that branch
* ]
* ```
*
* **For minor/major upgrades** (e.g., 3.5.6 → 3.6.2):
* ```php
* [
* 'current' => '3.5.6', // Current version
* 'latest' => '3.6.2', // Latest version in target branch
* 'type' => 'minor_upgrade', // Update type identifier
* 'upgrade_target' => 'v3.6', // Target branch (with 'v' prefix)
* 'checked_at' => '2025-11-14T10:00:00Z' // ISO8601 timestamp
* ]
* ```
*
* **Null value**: Set to null when:
* - Server is fully up-to-date with the latest version
* - Traefik image uses the 'latest' tag (no fixed version tracking)
* - No Traefik version detected on the server
*
* @see \App\Jobs\CheckTraefikVersionForServerJob Where this data is populated
* @see \App\Livewire\Server\Proxy Where this data is read and displayed
*/
#[OA\Schema(
description: 'Server model',
type: 'object',
properties: [
'id' => ['type' => 'integer', 'description' => 'The server ID.'],
'uuid' => ['type' => 'string', 'description' => 'The server UUID.'],
'name' => ['type' => 'string', 'description' => 'The server name.'],
'description' => ['type' => 'string', 'description' => 'The server description.'],
'ip' => ['type' => 'string', 'description' => 'The IP address.'],
'user' => ['type' => 'string', 'description' => 'The user.'],
'port' => ['type' => 'integer', 'description' => 'The port number.'],
'proxy' => ['type' => 'object', 'description' => 'The proxy configuration.'],
'proxy_type' => ['type' => 'string', 'enum' => ['traefik', 'caddy', 'none'], 'description' => 'The proxy type.'],
'high_disk_usage_notification_sent' => ['type' => 'boolean', 'description' => 'The flag to indicate if the high disk usage notification has been sent.'],
'unreachable_notification_sent' => ['type' => 'boolean', 'description' => 'The flag to indicate if the unreachable notification has been sent.'],
'unreachable_count' => ['type' => 'integer', 'description' => 'The unreachable count for your server.'],
'validation_logs' => ['type' => 'string', 'description' => 'The validation logs.'],
'log_drain_notification_sent' => ['type' => 'boolean', 'description' => 'The flag to indicate if the log drain notification has been sent.'],
'swarm_cluster' => ['type' => 'string', 'description' => 'The swarm cluster configuration.'],
'settings' => ['$ref' => '#/components/schemas/ServerSetting'],
]
)]
class Server extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, SchemalessAttributesTrait, SoftDeletes;
public static $batch_counter = 0;
protected $appends = ['is_coolify_host'];
protected static function booted()
{
static::saving(function ($server) {
$payload = [];
if ($server->user) {
$payload['user'] = str($server->user)->trim();
}
if ($server->ip) {
$payload['ip'] = str($server->ip)->trim();
// Update ip_previous when ip is being changed
if ($server->isDirty('ip') && $server->getOriginal('ip')) {
$payload['ip_previous'] = $server->getOriginal('ip');
}
}
$server->forceFill($payload);
});
static::saved(function ($server) {
if ($server->privateKey?->isDirty()) {
refresh_server_connection($server->privateKey);
}
});
static::created(function ($server) {
ServerSetting::create([
'server_id' => $server->id,
]);
if ($server->id === 0) {
if ($server->isSwarm()) {
SwarmDocker::create([
'id' => 0,
'name' => 'coolify',
'network' => 'coolify-overlay',
'server_id' => $server->id,
]);
} else {
StandaloneDocker::create([
'id' => 0,
'name' => 'coolify',
'network' => 'coolify',
'server_id' => $server->id,
]);
}
} else {
if ($server->isSwarm()) {
SwarmDocker::create([
'name' => 'coolify-overlay',
'network' => 'coolify-overlay',
'server_id' => $server->id,
]);
} else {
$standaloneDocker = new StandaloneDocker([
'name' => 'coolify',
'uuid' => (string) new Cuid2,
'network' => 'coolify',
'server_id' => $server->id,
]);
$standaloneDocker->saveQuietly();
}
}
if (! isset($server->proxy->redirect_enabled)) {
$server->proxy->redirect_enabled = true;
}
});
static::retrieved(function ($server) {
if (! isset($server->proxy->redirect_enabled)) {
$server->proxy->redirect_enabled = true;
}
});
static::forceDeleting(function ($server) {
$server->destinations()->each(function ($destination) {
$destination->delete();
});
$server->settings()->delete();
$server->sslCertificates()->delete();
});
}
protected $casts = [
'proxy' => SchemalessAttributes::class,
'traefik_outdated_info' => 'array',
'logdrain_axiom_api_key' => 'encrypted',
'logdrain_newrelic_license_key' => 'encrypted',
'delete_unused_volumes' => 'boolean',
'delete_unused_networks' => 'boolean',
'unreachable_notification_sent' => 'boolean',
'is_build_server' => 'boolean',
'force_disabled' => 'boolean',
];
protected $schemalessAttributes = [
'proxy',
];
protected $fillable = [
'name',
'ip',
'port',
'user',
'description',
'private_key_id',
'cloud_provider_token_id',
'team_id',
'hetzner_server_id',
'hetzner_server_status',
'is_validating',
'detected_traefik_version',
'traefik_outdated_info',
];
protected $guarded = [];
use HasSafeStringAttribute;
public function type()
{
return 'server';
}
protected function isCoolifyHost(): Attribute
{
return Attribute::make(
get: function () {
return $this->id === 0;
}
);
}
public static function isReachable()
{
return Server::ownedByCurrentTeam()->whereRelation('settings', 'is_reachable', true);
}
/**
* Get query builder for servers owned by current team.
* If you need all servers without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam(array $select = ['*'])
{
$teamId = currentTeam()->id;
$selectArray = collect($select)->concat(['id']);
return Server::whereTeamId($teamId)->with('settings', 'swarmDockers', 'standaloneDockers')->select($selectArray->all())->orderBy('name');
}
/**
* Get all servers owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return Server::ownedByCurrentTeam()->get();
});
}
public static function isUsable()
{
return Server::ownedByCurrentTeam()->whereRelation('settings', 'is_reachable', true)->whereRelation('settings', 'is_usable', true)->whereRelation('settings', 'is_swarm_worker', false)->whereRelation('settings', 'is_build_server', false)->whereRelation('settings', 'force_disabled', false);
}
public static function destinationsByServer(string $server_id)
{
$server = Server::ownedByCurrentTeam()->get()->where('id', $server_id)->firstOrFail();
$standaloneDocker = collect($server->standaloneDockers->all());
$swarmDocker = collect($server->swarmDockers->all());
return $standaloneDocker->concat($swarmDocker);
}
public function settings()
{
return $this->hasOne(ServerSetting::class);
}
public function dockerCleanupExecutions()
{
return $this->hasMany(DockerCleanupExecution::class);
}
public function proxySet()
{
return $this->proxyType() && $this->proxyType() !== 'NONE' && $this->isFunctional() && ! $this->isSwarmWorker() && ! $this->settings->is_build_server;
}
public function setupDefaultRedirect()
{
$banner =
"# This file is generated by Coolify, do not edit it manually.\n".
"# Disable the default redirect to customize (only if you know what are you doing).\n\n";
$dynamic_conf_path = $this->proxyPath().'/dynamic';
$proxy_type = $this->proxyType();
$redirect_enabled = $this->proxy->redirect_enabled ?? true;
$redirect_url = $this->proxy->redirect_url;
if (isDev()) {
if ($proxy_type === ProxyTypes::CADDY->value) {
$dynamic_conf_path = '/data/coolify/proxy/caddy/dynamic';
}
}
if ($proxy_type === ProxyTypes::TRAEFIK->value) {
$default_redirect_file = "$dynamic_conf_path/default_redirect_503.yaml";
} elseif ($proxy_type === ProxyTypes::CADDY->value) {
$default_redirect_file = "$dynamic_conf_path/default_redirect_503.caddy";
}
instant_remote_process([
"mkdir -p $dynamic_conf_path",
"rm -f $dynamic_conf_path/default_redirect_404.yaml",
"rm -f $dynamic_conf_path/default_redirect_404.caddy",
], $this);
if ($redirect_enabled === false) {
instant_remote_process(["rm -f $default_redirect_file"], $this);
} else {
if ($proxy_type === ProxyTypes::CADDY->value) {
if (filled($redirect_url)) {
$conf = ":80, :443 {
redir $redirect_url
}";
} else {
$conf = ':80, :443 {
respond 503
}';
}
} elseif ($proxy_type === ProxyTypes::TRAEFIK->value) {
$dynamic_conf = [
'http' => [
'routers' => [
'catchall' => [
'entryPoints' => [
0 => 'http',
1 => 'https',
],
'service' => 'noop',
'rule' => 'PathPrefix(`/`)',
'tls' => [
'certResolver' => 'letsencrypt',
],
'priority' => -1000,
],
],
'services' => [
'noop' => [
'loadBalancer' => [
'servers' => [],
],
],
],
],
];
if (filled($redirect_url)) {
$dynamic_conf['http']['routers']['catchall']['middlewares'] = [
0 => 'redirect-regexp',
];
$dynamic_conf['http']['services']['noop']['loadBalancer']['servers'][0] = [
'url' => '',
];
$dynamic_conf['http']['middlewares'] = [
'redirect-regexp' => [
'redirectRegex' => [
'regex' => '(.*)',
'replacement' => $redirect_url,
'permanent' => false,
],
],
];
}
$conf = Yaml::dump($dynamic_conf, 12, 2);
}
$conf = $banner.$conf;
$base64 = base64_encode($conf);
instant_remote_process([
"echo '$base64' | base64 -d | tee $default_redirect_file > /dev/null",
], $this);
}
if ($proxy_type === 'CADDY') {
$this->reloadCaddy();
}
}
public function setupDynamicProxyConfiguration()
{
$settings = instanceSettings();
$dynamic_config_path = $this->proxyPath().'/dynamic';
if ($this->proxyType() === ProxyTypes::TRAEFIK->value) {
$file = "$dynamic_config_path/coolify.yaml";
if (empty($settings->fqdn) || (isCloud() && $this->id !== 0) || ! $this->isLocalhost()) {
instant_remote_process([
"rm -f $file",
], $this);
} else {
$url = Url::fromString($settings->fqdn);
$host = $url->getHost();
$schema = $url->getScheme();
$traefik_dynamic_conf = [
'http' => [
'middlewares' => [
'redirect-to-https' => [
'redirectscheme' => [
'scheme' => 'https',
],
],
'gzip' => [
'compress' => true,
],
],
'routers' => [
'coolify-http' => [
'middlewares' => [
0 => 'gzip',
],
'entryPoints' => [
0 => 'http',
],
'service' => 'coolify',
'rule' => "Host(`{$host}`)",
],
'coolify-realtime-ws' => [
'entryPoints' => [
0 => 'http',
],
'service' => 'coolify-realtime',
'rule' => "Host(`{$host}`) && PathPrefix(`/app`)",
],
'coolify-terminal-ws' => [
'entryPoints' => [
0 => 'http',
],
'service' => 'coolify-terminal',
'rule' => "Host(`{$host}`) && PathPrefix(`/terminal/ws`)",
],
],
'services' => [
'coolify' => [
'loadBalancer' => [
'servers' => [
0 => [
'url' => 'http://coolify:8080',
],
],
],
],
'coolify-realtime' => [
'loadBalancer' => [
'servers' => [
0 => [
'url' => 'http://coolify-realtime:6001',
],
],
],
],
'coolify-terminal' => [
'loadBalancer' => [
'servers' => [
0 => [
'url' => 'http://coolify-realtime:6002',
],
],
],
],
],
],
];
if ($schema === 'https') {
$traefik_dynamic_conf['http']['routers']['coolify-http']['middlewares'] = [
0 => 'redirect-to-https',
];
$traefik_dynamic_conf['http']['routers']['coolify-https'] = [
'entryPoints' => [
0 => 'https',
],
'service' => 'coolify',
'rule' => "Host(`{$host}`)",
'tls' => [
'certresolver' => 'letsencrypt',
],
];
$traefik_dynamic_conf['http']['routers']['coolify-realtime-wss'] = [
'entryPoints' => [
0 => 'https',
],
'service' => 'coolify-realtime',
'rule' => "Host(`{$host}`) && PathPrefix(`/app`)",
'tls' => [
'certresolver' => 'letsencrypt',
],
];
$traefik_dynamic_conf['http']['routers']['coolify-terminal-wss'] = [
'entryPoints' => [
0 => 'https',
],
'service' => 'coolify-terminal',
'rule' => "Host(`{$host}`) && PathPrefix(`/terminal/ws`)",
'tls' => [
'certresolver' => 'letsencrypt',
],
];
}
$yaml = Yaml::dump($traefik_dynamic_conf, 12, 2);
$yaml =
"# This file is automatically generated by Coolify.\n".
"# Do not edit it manually (only if you know what are you doing).\n\n".
$yaml;
$base64 = base64_encode($yaml);
instant_remote_process([
"mkdir -p $dynamic_config_path",
"echo '$base64' | base64 -d | tee $file > /dev/null",
], $this);
}
} elseif ($this->proxyType() === 'CADDY') {
$file = "$dynamic_config_path/coolify.caddy";
if (empty($settings->fqdn) || (isCloud() && $this->id !== 0) || ! $this->isLocalhost()) {
instant_remote_process([
"rm -f $file",
], $this);
$this->reloadCaddy();
} else {
$url = Url::fromString($settings->fqdn);
$host = $url->getHost();
$schema = $url->getScheme();
$caddy_file = "
$schema://$host {
handle /app/* {
reverse_proxy coolify-realtime:6001
}
handle /terminal/ws {
reverse_proxy coolify-realtime:6002
}
reverse_proxy coolify:8080
}";
$base64 = base64_encode($caddy_file);
instant_remote_process([
"echo '$base64' | base64 -d | tee $file > /dev/null",
], $this);
$this->reloadCaddy();
}
}
}
public function reloadCaddy()
{
return instant_remote_process([
'docker exec coolify-proxy caddy reload --config /config/caddy/Caddyfile.autosave',
], $this);
}
public function proxyPath()
{
$base_path = config('constants.coolify.base_config_path');
$proxyType = $this->proxyType();
$proxy_path = "$base_path/proxy";
if ($proxyType === ProxyTypes::TRAEFIK->value) {
$proxy_path = $proxy_path.'/';
} elseif ($proxyType === ProxyTypes::CADDY->value) {
$proxy_path = $proxy_path.'/caddy';
} elseif ($proxyType === ProxyTypes::NGINX->value) {
$proxy_path = $proxy_path.'/nginx';
}
return $proxy_path;
}
public function proxyType()
{
return data_get($this->proxy, 'type');
}
public function scopeWithProxy(): Builder
{
return $this->proxy->modelScope();
}
public function scopeWhereProxyType(Builder $query, string $proxyType): Builder
{
return $query->where('proxy->type', $proxyType);
}
public function isLocalhost()
{
return $this->ip === 'host.docker.internal' || $this->id === 0;
}
public static function buildServers($teamId)
{
return Server::whereTeamId($teamId)->whereRelation('settings', 'is_reachable', true)->whereRelation('settings', 'is_build_server', true);
}
public function isForceDisabled()
{
return $this->settings->force_disabled;
}
public function forceEnableServer()
{
$this->settings->force_disabled = false;
$this->settings->save();
}
public function forceDisableServer()
{
$this->settings->force_disabled = true;
$this->settings->save();
$sshKeyFileLocation = "id.root@{$this->uuid}";
Storage::disk('ssh-keys')->delete($sshKeyFileLocation);
$this->disableSshMux();
}
public function sentinelHeartbeat(bool $isReset = false)
{
$this->sentinel_updated_at = $isReset ? now()->subMinutes(6000) : now();
$this->save();
}
/**
* Get the wait time for Sentinel to push before performing an SSH check.
*
* @return int The wait time in seconds.
*/
public function waitBeforeDoingSshCheck(): int
{
$wait = $this->settings->sentinel_push_interval_seconds * 3;
if ($wait < 120) {
$wait = 120;
}
return $wait;
}
public function isSentinelLive()
{
return Carbon::parse($this->sentinel_updated_at)->isAfter(now()->subSeconds($this->waitBeforeDoingSshCheck()));
}
public function isSentinelEnabled()
{
return ($this->isMetricsEnabled() || $this->isServerApiEnabled()) && ! $this->isBuildServer();
}
public function isMetricsEnabled()
{
return $this->settings->is_metrics_enabled;
}
public function isServerApiEnabled()
{
return $this->settings->is_sentinel_enabled;
}
public function checkSentinel()
{
CheckAndStartSentinelJob::dispatch($this);
}
public function getCpuMetrics(int $mins = 5)
{
if ($this->isMetricsEnabled()) {
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$cpu = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$this->settings->sentinel_token}\" http://localhost:8888/api/cpu/history?from=$from'"], $this, false);
if (str($cpu)->contains('error')) {
$error = json_decode($cpu, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$cpu = json_decode($cpu, true);
$metrics = collect($cpu)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
})->toArray();
// Downsample for intervals > 60 minutes to prevent browser freeze
if ($mins > 60 && count($metrics) > 1000) {
$metrics = $this->downsampleLTTB($metrics, 1000);
}
return collect($metrics);
}
}
public function getMemoryMetrics(int $mins = 5)
{
if ($this->isMetricsEnabled()) {
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$memory = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$this->settings->sentinel_token}\" http://localhost:8888/api/memory/history?from=$from'"], $this, false);
if (str($memory)->contains('error')) {
$error = json_decode($memory, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$memory = json_decode($memory, true);
$metrics = collect($memory)->map(function ($metric) {
$usedPercent = $metric['usedPercent'] ?? 0.0;
return [(int) $metric['time'], (float) $usedPercent];
})->toArray();
// Downsample for intervals > 60 minutes to prevent browser freeze
if ($mins > 60 && count($metrics) > 1000) {
$metrics = $this->downsampleLTTB($metrics, 1000);
}
return collect($metrics);
}
}
/**
* Downsample metrics using the Largest-Triangle-Three-Buckets (LTTB) algorithm.
* This preserves the visual shape of the data better than simple averaging.
*
* @param array $data Array of [timestamp, value] pairs
* @param int $threshold Target number of points
* @return array Downsampled data
*/
private function downsampleLTTB(array $data, int $threshold): array
{
$dataLength = count($data);
// Return unchanged if threshold >= data length, or if threshold <= 2
// (threshold <= 2 would cause division by zero in bucket calculation)
if ($threshold >= $dataLength || $threshold <= 2) {
return $data;
}
$sampled = [];
$sampled[] = $data[0]; // Always keep first point
$bucketSize = ($dataLength - 2) / ($threshold - 2);
$a = 0; // Index of previous selected point
for ($i = 0; $i < $threshold - 2; $i++) {
// Calculate bucket range
$bucketStart = (int) floor(($i + 1) * $bucketSize) + 1;
$bucketEnd = (int) floor(($i + 2) * $bucketSize) + 1;
$bucketEnd = min($bucketEnd, $dataLength - 1);
// Calculate average point for next bucket (used as reference)
$nextBucketStart = (int) floor(($i + 2) * $bucketSize) + 1;
$nextBucketEnd = (int) floor(($i + 3) * $bucketSize) + 1;
$nextBucketEnd = min($nextBucketEnd, $dataLength - 1);
$avgX = 0;
$avgY = 0;
$nextBucketCount = $nextBucketEnd - $nextBucketStart + 1;
if ($nextBucketCount > 0) {
for ($j = $nextBucketStart; $j <= $nextBucketEnd; $j++) {
$avgX += $data[$j][0];
$avgY += $data[$j][1];
}
$avgX /= $nextBucketCount;
$avgY /= $nextBucketCount;
}
// Find point in current bucket with largest triangle area
$maxArea = -1;
$maxAreaIndex = $bucketStart;
$pointAX = $data[$a][0];
$pointAY = $data[$a][1];
for ($j = $bucketStart; $j <= $bucketEnd; $j++) {
// Triangle area calculation
$area = abs(
($pointAX - $avgX) * ($data[$j][1] - $pointAY) -
($pointAX - $data[$j][0]) * ($avgY - $pointAY)
) * 0.5;
if ($area > $maxArea) {
$maxArea = $area;
$maxAreaIndex = $j;
}
}
$sampled[] = $data[$maxAreaIndex];
$a = $maxAreaIndex;
}
$sampled[] = $data[$dataLength - 1]; // Always keep last point
return $sampled;
}
public function getDiskUsage(): ?string
{
return instant_remote_process(['df / --output=pcent | tr -cd 0-9'], $this, false);
// return instant_remote_process(["df /| tail -1 | awk '{ print $5}' | sed 's/%//g'"], $this, false);
}
public function definedResources()
{
$applications = $this->applications();
$databases = $this->databases();
$services = $this->services();
return $applications->concat($databases)->concat($services->get());
}
public function stopUnmanaged($id)
{
return instant_remote_process(["docker stop -t 0 $id"], $this);
}
public function restartUnmanaged($id)
{
return instant_remote_process(["docker restart $id"], $this);
}
public function startUnmanaged($id)
{
return instant_remote_process(["docker start $id"], $this);
}
public function getContainers()
{
$containers = collect([]);
$containerReplicates = collect([]);
if ($this->isSwarm()) {
$containers = instant_remote_process_with_timeout(["docker service inspect $(docker service ls -q) --format '{{json .}}'"], $this, false);
$containers = format_docker_command_output_to_json($containers);
$containerReplicates = instant_remote_process_with_timeout(["docker service ls --format '{{json .}}'"], $this, false);
if ($containerReplicates) {
$containerReplicates = format_docker_command_output_to_json($containerReplicates);
foreach ($containerReplicates as $containerReplica) {
$name = data_get($containerReplica, 'Name');
$containers = $containers->map(function ($container) use ($name, $containerReplica) {
if (data_get($container, 'Spec.Name') === $name) {
$replicas = data_get($containerReplica, 'Replicas');
$running = str($replicas)->explode('/')[0];
$total = str($replicas)->explode('/')[1];
if ($running === $total) {
data_set($container, 'State.Status', 'running');
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ScheduledTask.php | app/Models/ScheduledTask.php | <?php
namespace App\Models;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
class ScheduledTask extends BaseModel
{
use HasSafeStringAttribute;
protected $guarded = [];
protected function casts(): array
{
return [
'enabled' => 'boolean',
'timeout' => 'integer',
];
}
public function service()
{
return $this->belongsTo(Service::class);
}
public function application()
{
return $this->belongsTo(Application::class);
}
public function latest_log(): HasOne
{
return $this->hasOne(ScheduledTaskExecution::class)->latest();
}
public function executions(): HasMany
{
// Last execution first
return $this->hasMany(ScheduledTaskExecution::class)->orderBy('created_at', 'desc');
}
public function server()
{
if ($this->application) {
if ($this->application->destination && $this->application->destination->server) {
return $this->application->destination->server;
}
} elseif ($this->service) {
if ($this->service->destination && $this->service->destination->server) {
return $this->service->destination->server;
}
} elseif ($this->database) {
if ($this->database->destination && $this->database->destination->server) {
return $this->database->destination->server;
}
}
return null;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/BaseModel.php | app/Models/BaseModel.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Visus\Cuid2\Cuid2;
abstract class BaseModel extends Model
{
protected static function boot()
{
parent::boot();
static::creating(function (Model $model) {
// Generate a UUID if one isn't set
if (! $model->uuid) {
$model->uuid = (string) new Cuid2;
}
});
}
public function sanitizedName(): Attribute
{
return new Attribute(
get: fn () => sanitize_string($this->getRawOriginal('name')),
);
}
public function image(): Attribute
{
return new Attribute(
get: fn () => sanitize_string($this->getRawOriginal('image')),
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/SslCertificate.php | app/Models/SslCertificate.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SslCertificate extends Model
{
protected $fillable = [
'ssl_certificate',
'ssl_private_key',
'configuration_dir',
'mount_path',
'resource_type',
'resource_id',
'server_id',
'common_name',
'subject_alternative_names',
'valid_until',
'is_ca_certificate',
];
protected $casts = [
'ssl_certificate' => 'encrypted',
'ssl_private_key' => 'encrypted',
'subject_alternative_names' => 'array',
'valid_until' => 'datetime',
];
public function application()
{
return $this->morphTo('resource');
}
public function service()
{
return $this->morphTo('resource');
}
public function database()
{
return $this->morphTo('resource');
}
public function server()
{
return $this->belongsTo(Server::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/DockerCleanupExecution.php | app/Models/DockerCleanupExecution.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class DockerCleanupExecution extends BaseModel
{
protected $guarded = [];
public function server(): BelongsTo
{
return $this->belongsTo(Server::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/SlackNotificationSettings.php | app/Models/SlackNotificationSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class SlackNotificationSettings extends Model
{
use Notifiable;
public $timestamps = false;
protected $fillable = [
'team_id',
'slack_enabled',
'slack_webhook_url',
'deployment_success_slack_notifications',
'deployment_failure_slack_notifications',
'status_change_slack_notifications',
'backup_success_slack_notifications',
'backup_failure_slack_notifications',
'scheduled_task_success_slack_notifications',
'scheduled_task_failure_slack_notifications',
'docker_cleanup_slack_notifications',
'server_disk_usage_slack_notifications',
'server_reachable_slack_notifications',
'server_unreachable_slack_notifications',
'server_patch_slack_notifications',
'traefik_outdated_slack_notifications',
];
protected $casts = [
'slack_enabled' => 'boolean',
'slack_webhook_url' => 'encrypted',
'deployment_success_slack_notifications' => 'boolean',
'deployment_failure_slack_notifications' => 'boolean',
'status_change_slack_notifications' => 'boolean',
'backup_success_slack_notifications' => 'boolean',
'backup_failure_slack_notifications' => 'boolean',
'scheduled_task_success_slack_notifications' => 'boolean',
'scheduled_task_failure_slack_notifications' => 'boolean',
'docker_cleanup_slack_notifications' => 'boolean',
'server_disk_usage_slack_notifications' => 'boolean',
'server_reachable_slack_notifications' => 'boolean',
'server_unreachable_slack_notifications' => 'boolean',
'server_patch_slack_notifications' => 'boolean',
'traefik_outdated_slack_notifications' => 'boolean',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function isEnabled()
{
return $this->slack_enabled;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/EnvironmentVariable.php | app/Models/EnvironmentVariable.php | <?php
namespace App\Models;
use App\Models\EnvironmentVariable as ModelsEnvironmentVariable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use OpenApi\Attributes as OA;
#[OA\Schema(
description: 'Environment Variable model',
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'uuid' => ['type' => 'string'],
'resourceable_type' => ['type' => 'string'],
'resourceable_id' => ['type' => 'integer'],
'is_literal' => ['type' => 'boolean'],
'is_multiline' => ['type' => 'boolean'],
'is_preview' => ['type' => 'boolean'],
'is_runtime' => ['type' => 'boolean'],
'is_buildtime' => ['type' => 'boolean'],
'is_shared' => ['type' => 'boolean'],
'is_shown_once' => ['type' => 'boolean'],
'key' => ['type' => 'string'],
'value' => ['type' => 'string'],
'real_value' => ['type' => 'string'],
'version' => ['type' => 'string'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
]
)]
class EnvironmentVariable extends BaseModel
{
protected $guarded = [];
protected $casts = [
'key' => 'string',
'value' => 'encrypted',
'is_multiline' => 'boolean',
'is_preview' => 'boolean',
'is_runtime' => 'boolean',
'is_buildtime' => 'boolean',
'version' => 'string',
'resourceable_type' => 'string',
'resourceable_id' => 'integer',
];
protected $appends = ['real_value', 'is_shared', 'is_really_required', 'is_nixpacks', 'is_coolify'];
protected static function booted()
{
static::created(function (EnvironmentVariable $environment_variable) {
if ($environment_variable->resourceable_type === Application::class && ! $environment_variable->is_preview) {
$found = ModelsEnvironmentVariable::where('key', $environment_variable->key)
->where('resourceable_type', Application::class)
->where('resourceable_id', $environment_variable->resourceable_id)
->where('is_preview', true)
->first();
if (! $found) {
$application = Application::find($environment_variable->resourceable_id);
if ($application) {
ModelsEnvironmentVariable::create([
'key' => $environment_variable->key,
'value' => $environment_variable->value,
'is_multiline' => $environment_variable->is_multiline ?? false,
'is_literal' => $environment_variable->is_literal ?? false,
'is_runtime' => $environment_variable->is_runtime ?? false,
'is_buildtime' => $environment_variable->is_buildtime ?? false,
'resourceable_type' => Application::class,
'resourceable_id' => $environment_variable->resourceable_id,
'is_preview' => true,
]);
}
}
}
$environment_variable->update([
'version' => config('constants.coolify.version'),
]);
});
static::saving(function (EnvironmentVariable $environmentVariable) {
$environmentVariable->updateIsShared();
});
}
public function service()
{
return $this->belongsTo(Service::class);
}
protected function value(): Attribute
{
return Attribute::make(
get: fn (?string $value = null) => $this->get_environment_variables($value),
set: fn (?string $value = null) => $this->set_environment_variables($value),
);
}
/**
* Get the parent resourceable model.
*/
public function resourceable()
{
return $this->morphTo();
}
public function resource()
{
return $this->resourceable;
}
public function realValue(): Attribute
{
return Attribute::make(
get: function () {
if (! $this->relationLoaded('resourceable')) {
$this->load('resourceable');
}
$resource = $this->resourceable;
if (! $resource) {
return null;
}
$real_value = $this->get_real_environment_variables($this->value, $resource);
if ($this->is_literal || $this->is_multiline) {
$real_value = '\''.$real_value.'\'';
} else {
$real_value = escapeEnvVariables($real_value);
}
return $real_value;
}
);
}
protected function isReallyRequired(): Attribute
{
return Attribute::make(
get: fn () => $this->is_required && str($this->real_value)->isEmpty(),
);
}
protected function isNixpacks(): Attribute
{
return Attribute::make(
get: function () {
if (str($this->key)->startsWith('NIXPACKS_')) {
return true;
}
return false;
}
);
}
protected function isCoolify(): Attribute
{
return Attribute::make(
get: function () {
if (str($this->key)->startsWith('SERVICE_')) {
return true;
}
return false;
}
);
}
protected function isShared(): Attribute
{
return Attribute::make(
get: function () {
$type = str($this->value)->after('{{')->before('.')->value;
if (str($this->value)->startsWith('{{'.$type) && str($this->value)->endsWith('}}')) {
return true;
}
return false;
}
);
}
private function get_real_environment_variables(?string $environment_variable = null, $resource = null)
{
if ((is_null($environment_variable) && $environment_variable === '') || is_null($resource)) {
return null;
}
$environment_variable = trim($environment_variable);
$sharedEnvsFound = str($environment_variable)->matchAll('/{{(.*?)}}/');
if ($sharedEnvsFound->isEmpty()) {
return $environment_variable;
}
foreach ($sharedEnvsFound as $sharedEnv) {
$type = str($sharedEnv)->trim()->match('/(.*?)\./');
if (! collect(SHARED_VARIABLE_TYPES)->contains($type)) {
continue;
}
$variable = str($sharedEnv)->trim()->match('/\.(.*)/');
if ($type->value() === 'environment') {
$id = $resource->environment->id;
} elseif ($type->value() === 'project') {
$id = $resource->environment->project->id;
} elseif ($type->value() === 'team') {
$id = $resource->team()->id;
}
if (is_null($id)) {
continue;
}
$environment_variable_found = SharedEnvironmentVariable::where('type', $type)->where('key', $variable)->where('team_id', $resource->team()->id)->where("{$type}_id", $id)->first();
if ($environment_variable_found) {
$environment_variable = str($environment_variable)->replace("{{{$sharedEnv}}}", $environment_variable_found->value);
}
}
return str($environment_variable)->value();
}
private function get_environment_variables(?string $environment_variable = null): ?string
{
if (! $environment_variable) {
return null;
}
return trim(decrypt($environment_variable));
}
private function set_environment_variables(?string $environment_variable = null): ?string
{
if (is_null($environment_variable) && $environment_variable === '') {
return null;
}
$environment_variable = trim($environment_variable);
$type = str($environment_variable)->after('{{')->before('.')->value;
if (str($environment_variable)->startsWith('{{'.$type) && str($environment_variable)->endsWith('}}')) {
return encrypt($environment_variable);
}
return encrypt($environment_variable);
}
protected function key(): Attribute
{
return Attribute::make(
set: fn (string $value) => str($value)->trim()->replace(' ', '_')->value,
);
}
protected function updateIsShared(): void
{
$type = str($this->value)->after('{{')->before('.')->value;
$isShared = str($this->value)->startsWith('{{'.$type) && str($this->value)->endsWith('}}');
$this->is_shared = $isShared;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneMongodb.php | app/Models/StandaloneMongodb.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneMongodb extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'mongodb-configdb-'.$database->uuid,
'mount_path' => '/data/configdb',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
LocalPersistentVolume::create([
'name' => 'mongodb-db-'.$database->uuid,
'mount_path' => '/data/db',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for MongoDB databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneMongodb::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all MongoDB databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneMongodb::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings.$this->mongo_conf;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function mongoInitdbRootPassword(): Attribute
{
return Attribute::make(
get: function ($value) {
try {
return decrypt($value);
} catch (\Throwable $th) {
$this->mongo_initdb_root_password = encrypt($value);
$this->save();
return $value;
}
}
);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-mongodb';
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$encodedUser = rawurlencode($this->mongo_initdb_root_username);
$encodedPass = rawurlencode($this->mongo_initdb_root_password);
$url = "mongodb://{$encodedUser}:{$encodedPass}@{$this->uuid}:27017/?directConnection=true";
if ($this->enable_ssl) {
$url .= '&tls=true&tlsCAFile=/etc/mongo/certs/ca.pem';
if (in_array($this->ssl_mode, ['verify-full'])) {
$url .= '&tlsCertificateKeyFile=/etc/mongo/certs/server.pem';
}
}
return $url;
},
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$encodedUser = rawurlencode($this->mongo_initdb_root_username);
$encodedPass = rawurlencode($this->mongo_initdb_root_password);
$url = "mongodb://{$encodedUser}:{$encodedPass}@{$serverIp}:{$this->public_port}/?directConnection=true";
if ($this->enable_ssl) {
$url .= '&tls=true&tlsCAFile=/etc/mongo/certs/ca.pem';
if (in_array($this->ssl_mode, ['verify-full'])) {
$url .= '&tlsCertificateKeyFile=/etc/mongo/certs/server.pem';
}
}
return $url;
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return true;
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ScheduledTaskExecution.php | app/Models/ScheduledTaskExecution.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ScheduledTaskExecution extends BaseModel
{
protected $guarded = [];
protected function casts(): array
{
return [
'started_at' => 'datetime',
'finished_at' => 'datetime',
'retry_count' => 'integer',
'duration' => 'decimal:2',
];
}
public function scheduledTask(): BelongsTo
{
return $this->belongsTo(ScheduledTask::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneDragonfly.php | app/Models/StandaloneDragonfly.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneDragonfly extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'dragonfly_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'dragonfly-data-'.$database->uuid,
'mount_path' => '/data',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for Dragonfly databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneDragonfly::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all Dragonfly databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneDragonfly::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-dragonfly';
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$scheme = $this->enable_ssl ? 'rediss' : 'redis';
$port = $this->enable_ssl ? 6380 : 6379;
$encodedPass = rawurlencode($this->dragonfly_password);
$url = "{$scheme}://:{$encodedPass}@{$this->uuid}:{$port}/0";
if ($this->enable_ssl && $this->ssl_mode === 'verify-ca') {
$url .= '?cacert=/etc/ssl/certs/coolify-ca.crt';
}
return $url;
}
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$scheme = $this->enable_ssl ? 'rediss' : 'redis';
$encodedPass = rawurlencode($this->dragonfly_password);
$url = "{$scheme}://:{$encodedPass}@{$serverIp}:{$this->public_port}/0";
if ($this->enable_ssl && $this->ssl_mode === 'verify-ca') {
$url .= '?cacert=/etc/ssl/certs/coolify-ca.crt';
}
return $url;
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return false;
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/PrivateKey.php | app/Models/PrivateKey.php | <?php
namespace App\Models;
use App\Traits\HasSafeStringAttribute;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use OpenApi\Attributes as OA;
use phpseclib3\Crypt\PublicKeyLoader;
#[OA\Schema(
description: 'Private Key model',
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'uuid' => ['type' => 'string'],
'name' => ['type' => 'string'],
'description' => ['type' => 'string'],
'private_key' => ['type' => 'string', 'format' => 'private-key'],
'public_key' => ['type' => 'string', 'description' => 'The public key of the private key.'],
'fingerprint' => ['type' => 'string', 'description' => 'The fingerprint of the private key.'],
'is_git_related' => ['type' => 'boolean'],
'team_id' => ['type' => 'integer'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
],
)]
class PrivateKey extends BaseModel
{
use HasSafeStringAttribute, WithRateLimiting;
protected $fillable = [
'name',
'description',
'private_key',
'is_git_related',
'team_id',
'fingerprint',
];
protected $casts = [
'private_key' => 'encrypted',
];
protected $appends = ['public_key'];
protected static function booted()
{
static::saving(function ($key) {
$key->private_key = formatPrivateKey($key->private_key);
if (! self::validatePrivateKey($key->private_key)) {
throw ValidationException::withMessages([
'private_key' => ['The private key is invalid.'],
]);
}
$key->fingerprint = self::generateFingerprint($key->private_key);
if (self::fingerprintExists($key->fingerprint, $key->id)) {
throw ValidationException::withMessages([
'private_key' => ['This private key already exists.'],
]);
}
});
static::deleted(function ($key) {
self::deleteFromStorage($key);
});
}
public function getPublicKeyAttribute()
{
return self::extractPublicKeyFromPrivate($this->private_key) ?? 'Error loading private key';
}
public function getPublicKey()
{
return self::extractPublicKeyFromPrivate($this->private_key) ?? 'Error loading private key';
}
/**
* Get query builder for private keys owned by current team.
* If you need all private keys without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam(array $select = ['*'])
{
$teamId = currentTeam()->id;
$selectArray = collect($select)->concat(['id']);
return self::whereTeamId($teamId)->select($selectArray->all());
}
/**
* Get all private keys owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return PrivateKey::ownedByCurrentTeam()->get();
});
}
public static function ownedAndOnlySShKeys(array $select = ['*'])
{
$teamId = currentTeam()->id;
$selectArray = collect($select)->concat(['id']);
return self::whereTeamId($teamId)
->where('is_git_related', false)
->select($selectArray->all());
}
public static function validatePrivateKey($privateKey)
{
try {
PublicKeyLoader::load($privateKey);
return true;
} catch (\Throwable $e) {
return false;
}
}
public static function createAndStore(array $data)
{
return DB::transaction(function () use ($data) {
$privateKey = new self($data);
$privateKey->save();
try {
$privateKey->storeInFileSystem();
} catch (\Exception $e) {
throw new \Exception('Failed to store SSH key: '.$e->getMessage());
}
return $privateKey;
});
}
public static function generateNewKeyPair($type = 'rsa')
{
try {
$instance = new self;
$instance->rateLimit(10);
$name = generate_random_name();
$description = 'Created by Coolify';
$keyPair = generateSSHKey($type === 'ed25519' ? 'ed25519' : 'rsa');
return [
'name' => $name,
'description' => $description,
'private_key' => $keyPair['private'],
'public_key' => $keyPair['public'],
];
} catch (\Throwable $e) {
throw new \Exception("Failed to generate new {$type} key: ".$e->getMessage());
}
}
public static function extractPublicKeyFromPrivate($privateKey)
{
try {
$key = PublicKeyLoader::load($privateKey);
return $key->getPublicKey()->toString('OpenSSH', ['comment' => '']);
} catch (\Throwable $e) {
return null;
}
}
public static function validateAndExtractPublicKey($privateKey)
{
$isValid = self::validatePrivateKey($privateKey);
$publicKey = $isValid ? self::extractPublicKeyFromPrivate($privateKey) : '';
return [
'isValid' => $isValid,
'publicKey' => $publicKey,
];
}
public function storeInFileSystem()
{
$filename = "ssh_key@{$this->uuid}";
$disk = Storage::disk('ssh-keys');
// Ensure the storage directory exists and is writable
$this->ensureStorageDirectoryExists();
// Attempt to store the private key
$success = $disk->put($filename, $this->private_key);
if (! $success) {
throw new \Exception("Failed to write SSH key to filesystem. Check disk space and permissions for: {$this->getKeyLocation()}");
}
// Verify the file was actually created and has content
if (! $disk->exists($filename)) {
throw new \Exception("SSH key file was not created: {$this->getKeyLocation()}");
}
$storedContent = $disk->get($filename);
if (empty($storedContent) || $storedContent !== $this->private_key) {
$disk->delete($filename); // Clean up the bad file
throw new \Exception("SSH key file content verification failed: {$this->getKeyLocation()}");
}
return $this->getKeyLocation();
}
public static function deleteFromStorage(self $privateKey)
{
$filename = "ssh_key@{$privateKey->uuid}";
$disk = Storage::disk('ssh-keys');
if ($disk->exists($filename)) {
$disk->delete($filename);
}
}
protected function ensureStorageDirectoryExists()
{
$disk = Storage::disk('ssh-keys');
$directoryPath = '';
if (! $disk->exists($directoryPath)) {
$success = $disk->makeDirectory($directoryPath);
if (! $success) {
throw new \Exception('Failed to create SSH keys storage directory');
}
}
// Check if directory is writable by attempting a test file
$testFilename = '.test_write_'.uniqid();
$testSuccess = $disk->put($testFilename, 'test');
if (! $testSuccess) {
throw new \Exception('SSH keys storage directory is not writable');
}
// Clean up test file
$disk->delete($testFilename);
}
public function getKeyLocation()
{
return "/var/www/html/storage/app/ssh/keys/ssh_key@{$this->uuid}";
}
public function updatePrivateKey(array $data)
{
return DB::transaction(function () use ($data) {
$this->update($data);
try {
$this->storeInFileSystem();
} catch (\Exception $e) {
throw new \Exception('Failed to update SSH key: '.$e->getMessage());
}
return $this;
});
}
public function servers()
{
return $this->hasMany(Server::class);
}
public function applications()
{
return $this->hasMany(Application::class);
}
public function githubApps()
{
return $this->hasMany(GithubApp::class);
}
public function gitlabApps()
{
return $this->hasMany(GitlabApp::class);
}
public function isInUse()
{
return $this->servers()->exists()
|| $this->applications()->exists()
|| $this->githubApps()->exists()
|| $this->gitlabApps()->exists();
}
public function safeDelete()
{
if (! $this->isInUse()) {
$this->delete();
return true;
}
return false;
}
public static function generateFingerprint($privateKey)
{
try {
$key = PublicKeyLoader::load($privateKey);
return $key->getPublicKey()->getFingerprint('sha256');
} catch (\Throwable $e) {
return null;
}
}
public static function generateMd5Fingerprint($privateKey)
{
try {
$key = PublicKeyLoader::load($privateKey);
return $key->getPublicKey()->getFingerprint('md5');
} catch (\Throwable $e) {
return null;
}
}
public static function fingerprintExists($fingerprint, $excludeId = null)
{
$query = self::query()
->where('fingerprint', $fingerprint)
->where('id', '!=', $excludeId);
if (currentTeam()) {
$query->where('team_id', currentTeam()->id);
}
return $query->exists();
}
public static function cleanupUnusedKeys()
{
self::ownedByCurrentTeam()->each(function ($privateKey) {
$privateKey->safeDelete();
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/LocalPersistentVolume.php | app/Models/LocalPersistentVolume.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\Yaml\Yaml;
class LocalPersistentVolume extends Model
{
protected $guarded = [];
public function resource()
{
return $this->morphTo('resource');
}
public function application()
{
return $this->morphTo('resource');
}
public function service()
{
return $this->morphTo('resource');
}
public function database()
{
return $this->morphTo('resource');
}
protected function customizeName($value)
{
return str($value)->trim()->value;
}
protected function mountPath(): Attribute
{
return Attribute::make(
set: fn (string $value) => str($value)->trim()->start('/')->value
);
}
protected function hostPath(): Attribute
{
return Attribute::make(
set: function (?string $value) {
if ($value) {
return str($value)->trim()->start('/')->value;
} else {
return $value;
}
}
);
}
// Check if this volume belongs to a service resource
public function isServiceResource(): bool
{
return in_array($this->resource_type, [
'App\Models\ServiceApplication',
'App\Models\ServiceDatabase',
]);
}
// Check if this volume belongs to a dockercompose application
public function isDockerComposeResource(): bool
{
if ($this->resource_type !== 'App\Models\Application') {
return false;
}
// Only access relationship if already eager loaded to avoid N+1
if (! $this->relationLoaded('resource')) {
return false;
}
$application = $this->resource;
if (! $application) {
return false;
}
return data_get($application, 'build_pack') === 'dockercompose';
}
// Determine if this volume should be read-only in the UI
// Service volumes and dockercompose application volumes are read-only
// (users should edit compose file directly)
public function shouldBeReadOnlyInUI(): bool
{
// All service volumes should be read-only in UI
if ($this->isServiceResource()) {
return true;
}
// All dockercompose application volumes should be read-only in UI
if ($this->isDockerComposeResource()) {
return true;
}
// Check for explicit :ro flag in compose (existing logic)
return $this->isReadOnlyVolume();
}
// Check if this volume is read-only by parsing the docker-compose content
public function isReadOnlyVolume(): bool
{
try {
// Get the resource (can be application, service, or database)
$resource = $this->resource;
if (! $resource) {
return false;
}
// Only check for services
if (! method_exists($resource, 'service')) {
return false;
}
$actualService = $resource->service;
if (! $actualService || ! $actualService->docker_compose_raw) {
return false;
}
// Parse the docker-compose content
$compose = Yaml::parse($actualService->docker_compose_raw);
if (! isset($compose['services'])) {
return false;
}
// Find the service that this volume belongs to
$serviceName = $resource->name;
if (! isset($compose['services'][$serviceName]['volumes'])) {
return false;
}
$volumes = $compose['services'][$serviceName]['volumes'];
// Check each volume to find a match
// Note: We match on mount_path (container path) only, since host paths get transformed
foreach ($volumes as $volume) {
// Volume can be string like "host:container:ro" or "host:container"
if (is_string($volume)) {
$parts = explode(':', $volume);
// Check if this volume matches our mount_path
if (count($parts) >= 2) {
$containerPath = $parts[1];
$options = $parts[2] ?? null;
// Match based on mount_path
// Remove leading slash from mount_path if present for comparison
$mountPath = str($this->mount_path)->ltrim('/')->toString();
$containerPathClean = str($containerPath)->ltrim('/')->toString();
if ($mountPath === $containerPathClean || $this->mount_path === $containerPath) {
return $options === 'ro';
}
}
} elseif (is_array($volume)) {
// Long-form syntax: { type: bind/volume, source: ..., target: ..., read_only: true }
$containerPath = data_get($volume, 'target');
$readOnly = data_get($volume, 'read_only', false);
// Match based on mount_path
// Remove leading slash from mount_path if present for comparison
$mountPath = str($this->mount_path)->ltrim('/')->toString();
$containerPathClean = str($containerPath)->ltrim('/')->toString();
if ($mountPath === $containerPathClean || $this->mount_path === $containerPath) {
return $readOnly === true;
}
}
}
return false;
} catch (\Throwable $e) {
ray($e->getMessage(), 'Error checking read-only persistent volume');
return false;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneRedis.php | app/Models/StandaloneRedis.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneRedis extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'redis-data-'.$database->uuid,
'mount_path' => '/data',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
static::retrieved(function ($database) {
if (! $database->redis_username) {
$database->redis_username = 'default';
}
});
}
/**
* Get query builder for Redis databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneRedis::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all Redis databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneRedis::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings.$this->redis_conf;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function type(): string
{
return 'standalone-redis';
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$redis_version = $this->getRedisVersion();
$username_part = version_compare($redis_version, '6.0', '>=') ? rawurlencode($this->redis_username).':' : '';
$encodedPass = rawurlencode($this->redis_password);
$scheme = $this->enable_ssl ? 'rediss' : 'redis';
$port = $this->enable_ssl ? 6380 : 6379;
$url = "{$scheme}://{$username_part}{$encodedPass}@{$this->uuid}:{$port}/0";
if ($this->enable_ssl && $this->ssl_mode === 'verify-ca') {
$url .= '?cacert=/etc/ssl/certs/coolify-ca.crt';
}
return $url;
}
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$redis_version = $this->getRedisVersion();
$username_part = version_compare($redis_version, '6.0', '>=') ? rawurlencode($this->redis_username).':' : '';
$encodedPass = rawurlencode($this->redis_password);
$scheme = $this->enable_ssl ? 'rediss' : 'redis';
$url = "{$scheme}://{$username_part}{$encodedPass}@{$serverIp}:{$this->public_port}/0";
if ($this->enable_ssl && $this->ssl_mode === 'verify-ca') {
$url .= '?cacert=/etc/ssl/certs/coolify-ca.crt';
}
return $url;
}
return null;
}
);
}
public function getRedisVersion()
{
$image_parts = explode(':', $this->image);
return $image_parts[1] ?? '0.0';
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return false;
}
public function redisPassword(): Attribute
{
return new Attribute(
get: function () {
$password = $this->runtime_environment_variables()->where('key', 'REDIS_PASSWORD')->first();
if (! $password) {
return null;
}
return $password->value;
},
);
}
public function redisUsername(): Attribute
{
return new Attribute(
get: function () {
$username = $this->runtime_environment_variables()->where('key', 'REDIS_USERNAME')->first();
if (! $username) {
$this->runtime_environment_variables()->create([
'key' => 'REDIS_USERNAME',
'value' => 'default',
]);
return 'default';
}
return $username->value;
}
);
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/PushoverNotificationSettings.php | app/Models/PushoverNotificationSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class PushoverNotificationSettings extends Model
{
use Notifiable;
public $timestamps = false;
protected $fillable = [
'team_id',
'pushover_enabled',
'pushover_user_key',
'pushover_api_token',
'deployment_success_pushover_notifications',
'deployment_failure_pushover_notifications',
'status_change_pushover_notifications',
'backup_success_pushover_notifications',
'backup_failure_pushover_notifications',
'scheduled_task_success_pushover_notifications',
'scheduled_task_failure_pushover_notifications',
'docker_cleanup_pushover_notifications',
'server_disk_usage_pushover_notifications',
'server_reachable_pushover_notifications',
'server_unreachable_pushover_notifications',
'server_patch_pushover_notifications',
'traefik_outdated_pushover_notifications',
];
protected $casts = [
'pushover_enabled' => 'boolean',
'pushover_user_key' => 'encrypted',
'pushover_api_token' => 'encrypted',
'deployment_success_pushover_notifications' => 'boolean',
'deployment_failure_pushover_notifications' => 'boolean',
'status_change_pushover_notifications' => 'boolean',
'backup_success_pushover_notifications' => 'boolean',
'backup_failure_pushover_notifications' => 'boolean',
'scheduled_task_success_pushover_notifications' => 'boolean',
'scheduled_task_failure_pushover_notifications' => 'boolean',
'docker_cleanup_pushover_notifications' => 'boolean',
'server_disk_usage_pushover_notifications' => 'boolean',
'server_reachable_pushover_notifications' => 'boolean',
'server_unreachable_pushover_notifications' => 'boolean',
'server_patch_pushover_notifications' => 'boolean',
'traefik_outdated_pushover_notifications' => 'boolean',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function isEnabled()
{
return $this->pushover_enabled;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ServiceDatabase.php | app/Models/ServiceDatabase.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class ServiceDatabase extends BaseModel
{
use HasFactory, SoftDeletes;
protected $guarded = [];
protected static function booted()
{
static::deleting(function ($service) {
$service->persistentStorages()->delete();
$service->fileStorages()->delete();
$service->scheduledBackups()->delete();
});
static::saving(function ($service) {
if ($service->isDirty('status')) {
$service->forceFill(['last_online_at' => now()]);
}
});
}
public static function ownedByCurrentTeamAPI(int $teamId)
{
return ServiceDatabase::whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');
}
/**
* Get query builder for service databases owned by current team.
* If you need all service databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return ServiceDatabase::whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all service databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return ServiceDatabase::ownedByCurrentTeam()->get();
});
}
public function restart()
{
$container_id = $this->name.'-'.$this->service->uuid;
remote_process(["docker restart {$container_id}"], $this->service->server);
}
public function isRunning()
{
return str($this->status)->contains('running');
}
public function isExited()
{
return str($this->status)->contains('exited');
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function isStripprefixEnabled()
{
return data_get($this, 'is_stripprefix_enabled', true);
}
public function isGzipEnabled()
{
return data_get($this, 'is_gzip_enabled', true);
}
public function type()
{
return 'service';
}
public function serviceType()
{
return null;
}
public function databaseType()
{
if (filled($this->custom_type)) {
return 'standalone-'.$this->custom_type;
}
$image = str($this->image)->before(':');
if ($image->contains('supabase/postgres')) {
$finalImage = 'supabase/postgres';
} elseif ($image->contains('timescale')) {
$finalImage = 'postgresql';
} elseif ($image->contains('pgvector')) {
$finalImage = 'postgresql';
} elseif ($image->contains('postgres') || $image->contains('postgis')) {
$finalImage = 'postgresql';
} else {
$finalImage = $image;
}
return "standalone-$finalImage";
}
public function getServiceDatabaseUrl()
{
$port = $this->public_port;
$realIp = $this->service->server->ip;
if ($this->service->server->isLocalhost() || isDev()) {
$realIp = base_ip();
}
return "{$realIp}:{$port}";
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function workdir()
{
return service_configuration_dir()."/{$this->service->uuid}";
}
public function service()
{
return $this->belongsTo(Service::class);
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function getFilesFromServer(bool $isInit = false)
{
getFilesystemVolumesFromServer($this, $isInit);
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function isBackupSolutionAvailable()
{
return str($this->databaseType())->contains('mysql') ||
str($this->databaseType())->contains('postgres') ||
str($this->databaseType())->contains('postgis') ||
str($this->databaseType())->contains('mariadb') ||
str($this->databaseType())->contains('mongo') ||
filled($this->custom_type);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/EmailNotificationSettings.php | app/Models/EmailNotificationSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class EmailNotificationSettings extends Model
{
public $timestamps = false;
protected $fillable = [
'team_id',
'smtp_enabled',
'smtp_from_address',
'smtp_from_name',
'smtp_recipients',
'smtp_host',
'smtp_port',
'smtp_encryption',
'smtp_username',
'smtp_password',
'smtp_timeout',
'resend_enabled',
'resend_api_key',
'use_instance_email_settings',
'deployment_success_email_notifications',
'deployment_failure_email_notifications',
'status_change_email_notifications',
'backup_success_email_notifications',
'backup_failure_email_notifications',
'scheduled_task_success_email_notifications',
'scheduled_task_failure_email_notifications',
'server_disk_usage_email_notifications',
'server_patch_email_notifications',
'traefik_outdated_email_notifications',
];
protected $casts = [
'smtp_enabled' => 'boolean',
'smtp_from_address' => 'encrypted',
'smtp_from_name' => 'encrypted',
'smtp_recipients' => 'encrypted',
'smtp_host' => 'encrypted',
'smtp_port' => 'integer',
'smtp_username' => 'encrypted',
'smtp_password' => 'encrypted',
'smtp_timeout' => 'integer',
'resend_enabled' => 'boolean',
'resend_api_key' => 'encrypted',
'use_instance_email_settings' => 'boolean',
'deployment_success_email_notifications' => 'boolean',
'deployment_failure_email_notifications' => 'boolean',
'status_change_email_notifications' => 'boolean',
'backup_success_email_notifications' => 'boolean',
'backup_failure_email_notifications' => 'boolean',
'scheduled_task_success_email_notifications' => 'boolean',
'scheduled_task_failure_email_notifications' => 'boolean',
'server_disk_usage_email_notifications' => 'boolean',
'server_patch_email_notifications' => 'boolean',
'traefik_outdated_email_notifications' => 'boolean',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function isEnabled()
{
return $this->smtp_enabled || $this->resend_enabled || $this->use_instance_email_settings;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneClickhouse.php | app/Models/StandaloneClickhouse.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneClickhouse extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'clickhouse_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'clickhouse-data-'.$database->uuid,
'mount_path' => '/var/lib/clickhouse',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for ClickHouse databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneClickhouse::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all ClickHouse databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneClickhouse::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-clickhouse';
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$encodedUser = rawurlencode($this->clickhouse_admin_user);
$encodedPass = rawurlencode($this->clickhouse_admin_password);
$database = $this->clickhouse_db ?? 'default';
return "clickhouse://{$encodedUser}:{$encodedPass}@{$this->uuid}:9000/{$database}";
},
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$encodedUser = rawurlencode($this->clickhouse_admin_user);
$encodedPass = rawurlencode($this->clickhouse_admin_password);
$database = $this->clickhouse_db ?? 'default';
return "clickhouse://{$encodedUser}:{$encodedPass}@{$serverIp}:{$this->public_port}/{$database}";
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return false;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/GithubApp.php | app/Models/GithubApp.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
class GithubApp extends BaseModel
{
protected $guarded = [];
protected $appends = ['type'];
protected $casts = [
'is_public' => 'boolean',
'is_system_wide' => 'boolean',
'type' => 'string',
];
protected $hidden = [
'client_secret',
'webhook_secret',
];
protected static function booted(): void
{
static::deleting(function (GithubApp $github_app) {
$applications_count = Application::where('source_id', $github_app->id)->count();
if ($applications_count > 0) {
throw new \Exception('You cannot delete this GitHub App because it is in use by '.$applications_count.' application(s). Delete them first.');
}
$privateKey = $github_app->privateKey;
if ($privateKey) {
// Check if key is used by anything EXCEPT this GitHub app
$isUsedElsewhere = $privateKey->servers()->exists()
|| $privateKey->applications()->exists()
|| $privateKey->githubApps()->where('id', '!=', $github_app->id)->exists()
|| $privateKey->gitlabApps()->exists();
if (! $isUsedElsewhere) {
$privateKey->delete();
} else {
}
}
});
}
public static function ownedByCurrentTeam()
{
return GithubApp::where(function ($query) {
$query->where('team_id', currentTeam()->id)
->orWhere('is_system_wide', true);
});
}
public static function public()
{
return GithubApp::where(function ($query) {
$query->where(function ($q) {
$q->where('team_id', currentTeam()->id)
->orWhere('is_system_wide', true);
})->where('is_public', true);
})->whereNotNull('app_id')->get();
}
public static function private()
{
return GithubApp::where(function ($query) {
$query->where(function ($q) {
$q->where('team_id', currentTeam()->id)
->orWhere('is_system_wide', true);
})->where('is_public', false);
})->whereNotNull('app_id')->get();
}
public function team()
{
return $this->belongsTo(Team::class);
}
public function applications()
{
return $this->morphMany(Application::class, 'source');
}
public function privateKey()
{
return $this->belongsTo(PrivateKey::class);
}
public function type(): Attribute
{
return Attribute::make(
get: function () {
if ($this->getMorphClass() === \App\Models\GithubApp::class) {
return 'github';
}
},
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneMysql.php | app/Models/StandaloneMysql.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneMysql extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'mysql_password' => 'encrypted',
'mysql_root_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'mysql-data-'.$database->uuid,
'mount_path' => '/var/lib/mysql',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for MySQL databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneMysql::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all MySQL databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneMysql::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings.$this->mysql_conf;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-mysql';
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$encodedUser = rawurlencode($this->mysql_user);
$encodedPass = rawurlencode($this->mysql_password);
$url = "mysql://{$encodedUser}:{$encodedPass}@{$this->uuid}:3306/{$this->mysql_database}";
if ($this->enable_ssl) {
$url .= "?ssl-mode={$this->ssl_mode}";
if (in_array($this->ssl_mode, ['VERIFY_CA', 'VERIFY_IDENTITY'])) {
$url .= '&ssl-ca=/etc/ssl/certs/coolify-ca.crt';
}
}
return $url;
},
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$encodedUser = rawurlencode($this->mysql_user);
$encodedPass = rawurlencode($this->mysql_password);
$url = "mysql://{$encodedUser}:{$encodedPass}@{$serverIp}:{$this->public_port}/{$this->mysql_database}";
if ($this->enable_ssl) {
$url .= "?ssl-mode={$this->ssl_mode}";
if (in_array($this->ssl_mode, ['VERIFY_CA', 'VERIFY_IDENTITY'])) {
$url .= '&ssl-ca=/etc/ssl/certs/coolify-ca.crt';
}
}
return $url;
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return true;
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/CloudInitScript.php | app/Models/CloudInitScript.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CloudInitScript extends Model
{
protected $fillable = [
'team_id',
'name',
'script',
];
protected function casts(): array
{
return [
'script' => 'encrypted',
];
}
public function team()
{
return $this->belongsTo(Team::class);
}
public static function ownedByCurrentTeam(array $select = ['*'])
{
$selectArray = collect($select)->concat(['id']);
return self::whereTeamId(currentTeam()->id)->select($selectArray->all());
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ApplicationDeploymentQueue.php | app/Models/ApplicationDeploymentQueue.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use OpenApi\Attributes as OA;
#[OA\Schema(
description: 'Project model',
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'application_id' => ['type' => 'string'],
'deployment_uuid' => ['type' => 'string'],
'pull_request_id' => ['type' => 'integer'],
'force_rebuild' => ['type' => 'boolean'],
'commit' => ['type' => 'string'],
'status' => ['type' => 'string'],
'is_webhook' => ['type' => 'boolean'],
'is_api' => ['type' => 'boolean'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
'logs' => ['type' => 'string'],
'current_process_id' => ['type' => 'string'],
'restart_only' => ['type' => 'boolean'],
'git_type' => ['type' => 'string'],
'server_id' => ['type' => 'integer'],
'application_name' => ['type' => 'string'],
'server_name' => ['type' => 'string'],
'deployment_url' => ['type' => 'string'],
'destination_id' => ['type' => 'string'],
'only_this_server' => ['type' => 'boolean'],
'rollback' => ['type' => 'boolean'],
'commit_message' => ['type' => 'string'],
],
)]
class ApplicationDeploymentQueue extends Model
{
protected $guarded = [];
public function application()
{
return $this->belongsTo(Application::class);
}
public function server(): Attribute
{
return Attribute::make(
get: fn () => Server::find($this->server_id),
);
}
public function setStatus(string $status)
{
$this->update([
'status' => $status,
]);
}
public function getOutput($name)
{
if (! $this->logs) {
return null;
}
return collect(json_decode($this->logs))->where('name', $name)->first()?->output ?? null;
}
public function getHorizonJobStatus()
{
return getJobStatus($this->horizon_job_id);
}
public function commitMessage()
{
if (empty($this->commit_message) || is_null($this->commit_message)) {
return null;
}
return str($this->commit_message)->value();
}
private function redactSensitiveInfo($text)
{
$text = remove_iip($text);
$app = $this->application;
if (! $app) {
return $text;
}
$lockedVars = collect([]);
if ($app->environment_variables) {
$lockedVars = $lockedVars->merge(
$app->environment_variables
->where('is_shown_once', true)
->pluck('real_value', 'key')
->filter()
);
}
if ($this->pull_request_id !== 0 && $app->environment_variables_preview) {
$lockedVars = $lockedVars->merge(
$app->environment_variables_preview
->where('is_shown_once', true)
->pluck('real_value', 'key')
->filter()
);
}
foreach ($lockedVars as $key => $value) {
$escapedValue = preg_quote($value, '/');
$text = preg_replace(
'/'.$escapedValue.'/',
REDACTED,
$text
);
}
return $text;
}
public function addLogEntry(string $message, string $type = 'stdout', bool $hidden = false)
{
if ($type === 'error') {
$type = 'stderr';
}
$message = str($message)->trim();
if ($message->startsWith('╔')) {
$message = "\n".$message;
}
$newLogEntry = [
'command' => null,
'output' => $this->redactSensitiveInfo($message),
'type' => $type,
'timestamp' => Carbon::now('UTC'),
'hidden' => $hidden,
'batch' => 1,
];
// Use a transaction to ensure atomicity
DB::transaction(function () use ($newLogEntry) {
// Reload the model to get the latest logs
$this->refresh();
if ($this->logs) {
$previousLogs = json_decode($this->logs, associative: true, flags: JSON_THROW_ON_ERROR);
$newLogEntry['order'] = count($previousLogs) + 1;
$previousLogs[] = $newLogEntry;
$this->logs = json_encode($previousLogs, flags: JSON_THROW_ON_ERROR);
} else {
$this->logs = json_encode([$newLogEntry], flags: JSON_THROW_ON_ERROR);
}
// Save without triggering events to prevent potential race conditions
$this->saveQuietly();
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandalonePostgresql.php | app/Models/StandalonePostgresql.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandalonePostgresql extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'init_scripts' => 'array',
'postgres_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'postgres-data-'.$database->uuid,
'mount_path' => '/var/lib/postgresql/data',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for PostgreSQL databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandalonePostgresql::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all PostgreSQL databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandalonePostgresql::ownedByCurrentTeam()->get();
});
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings.$this->postgres_initdb_args.$this->postgres_host_auth_method;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-postgresql';
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$encodedUser = rawurlencode($this->postgres_user);
$encodedPass = rawurlencode($this->postgres_password);
$url = "postgres://{$encodedUser}:{$encodedPass}@{$this->uuid}:5432/{$this->postgres_db}";
if ($this->enable_ssl) {
$url .= "?sslmode={$this->ssl_mode}";
if (in_array($this->ssl_mode, ['verify-ca', 'verify-full'])) {
$url .= '&sslrootcert=/etc/ssl/certs/coolify-ca.crt';
}
}
return $url;
},
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$encodedUser = rawurlencode($this->postgres_user);
$encodedPass = rawurlencode($this->postgres_password);
$url = "postgres://{$encodedUser}:{$encodedPass}@{$serverIp}:{$this->public_port}/{$this->postgres_db}";
if ($this->enable_ssl) {
$url .= "?sslmode={$this->ssl_mode}";
if (in_array($this->ssl_mode, ['verify-ca', 'verify-full'])) {
$url .= '&sslrootcert=/etc/ssl/certs/coolify-ca.crt';
}
}
return $url;
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
public function isBackupSolutionAvailable()
{
return true;
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [
(int) $metric['time'],
(float) ($metric['percent'] ?? 0.0),
];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/GitlabApp.php | app/Models/GitlabApp.php | <?php
namespace App\Models;
class GitlabApp extends BaseModel
{
protected $hidden = [
'webhook_token',
'app_secret',
];
public static function ownedByCurrentTeam()
{
return GitlabApp::whereTeamId(currentTeam()->id);
}
public function applications()
{
return $this->morphMany(Application::class, 'source');
}
public function privateKey()
{
return $this->belongsTo(PrivateKey::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneMariadb.php | app/Models/StandaloneMariadb.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneMariadb extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
protected $casts = [
'mariadb_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'mariadb-data-'.$database->uuid,
'mount_path' => '/var/lib/mysql',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for MariaDB databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneMariadb::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all MariaDB databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneMariadb::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings.$this->mariadb_conf;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-mariadb';
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$encodedUser = rawurlencode($this->mariadb_user);
$encodedPass = rawurlencode($this->mariadb_password);
return "mysql://{$encodedUser}:{$encodedPass}@{$this->uuid}:3306/{$this->mariadb_database}";
},
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$encodedUser = rawurlencode($this->mariadb_user);
$encodedPass = rawurlencode($this->mariadb_password);
return "mysql://{$encodedUser}:{$encodedPass}@{$serverIp}:{$this->public_port}/{$this->mariadb_database}";
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination(): MorphTo
{
return $this->morphTo();
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ApplicationPreview.php | app/Models/ApplicationPreview.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Url\Url;
use Visus\Cuid2\Cuid2;
class ApplicationPreview extends BaseModel
{
use SoftDeletes;
protected $guarded = [];
protected static function booted()
{
static::forceDeleting(function ($preview) {
$server = $preview->application->destination->server;
$application = $preview->application;
if (data_get($preview, 'application.build_pack') === 'dockercompose') {
// Docker Compose volume and network cleanup
$composeFile = $application->parse(pull_request_id: $preview->pull_request_id);
$volumes = data_get($composeFile, 'volumes');
$networks = data_get($composeFile, 'networks');
$networkKeys = collect($networks)->keys();
$volumeKeys = collect($volumes)->keys();
$volumeKeys->each(function ($key) use ($server) {
instant_remote_process(["docker volume rm -f $key"], $server, false);
});
$networkKeys->each(function ($key) use ($server) {
instant_remote_process(["docker network disconnect $key coolify-proxy"], $server, false);
instant_remote_process(["docker network rm $key"], $server, false);
});
} else {
// Regular application volume cleanup
$persistentStorages = $preview->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() > 0) {
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
}
// Clean up persistent storage records
$preview->persistentStorages()->delete();
});
static::saving(function ($preview) {
if ($preview->isDirty('status')) {
$preview->forceFill(['last_online_at' => now()]);
}
});
}
public static function findPreviewByApplicationAndPullId(int $application_id, int $pull_request_id)
{
return self::where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();
}
public function isRunning()
{
return (bool) str($this->status)->startsWith('running');
}
public function application()
{
return $this->belongsTo(Application::class);
}
public function persistentStorages()
{
return $this->morphMany(\App\Models\LocalPersistentVolume::class, 'resource');
}
public function generate_preview_fqdn()
{
if ($this->application->fqdn) {
if (str($this->application->fqdn)->contains(',')) {
$url = Url::fromString(str($this->application->fqdn)->explode(',')[0]);
} else {
$url = Url::fromString($this->application->fqdn);
}
$template = $this->application->preview_url_template;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$random = new Cuid2;
$preview_fqdn = str_replace('{{random}}', $random, $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $this->pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
$this->fqdn = $preview_fqdn;
$this->save();
}
return $this;
}
public function generate_preview_fqdn_compose()
{
$services = collect(json_decode($this->application->docker_compose_domains)) ?? collect();
$docker_compose_domains = data_get($this, 'docker_compose_domains');
$docker_compose_domains = json_decode($docker_compose_domains, true) ?? [];
// Get all services from the parsed compose file to ensure all services have entries
$parsedServices = $this->application->parse(pull_request_id: $this->pull_request_id);
if (isset($parsedServices['services'])) {
foreach ($parsedServices['services'] as $serviceName => $service) {
if (! isDatabaseImage(data_get($service, 'image'))) {
// Remove PR suffix from service name to get original service name
$originalServiceName = str($serviceName)->replaceLast('-pr-'.$this->pull_request_id, '')->toString();
// Ensure all services have an entry, even if empty
if (! $services->has($originalServiceName)) {
$services->put($originalServiceName, ['domain' => '']);
}
}
}
}
foreach ($services as $service_name => $service_config) {
$domain_string = data_get($service_config, 'domain');
// If domain string is empty or null, don't auto-generate domain
// Only generate domains when main app already has domains set
if (empty($domain_string)) {
// Ensure service has an empty domain entry for form binding
$docker_compose_domains[$service_name]['domain'] = '';
continue;
}
$service_domains = str($domain_string)->explode(',')->map(fn ($d) => trim($d));
$preview_domains = [];
foreach ($service_domains as $domain) {
if (empty($domain)) {
continue;
}
$url = Url::fromString($domain);
$template = $this->application->preview_url_template;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$random = new Cuid2;
$preview_fqdn = str_replace('{{random}}', $random, $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $this->pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
$preview_domains[] = $preview_fqdn;
}
if (! empty($preview_domains)) {
$docker_compose_domains[$service_name]['domain'] = implode(',', $preview_domains);
} else {
// Ensure service has an empty domain entry for form binding
$docker_compose_domains[$service_name]['domain'] = '';
}
}
$this->docker_compose_domains = json_encode($docker_compose_domains);
$this->save();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/UserChangelogRead.php | app/Models/UserChangelogRead.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class UserChangelogRead extends Model
{
protected $fillable = [
'user_id',
'release_tag',
'read_at',
];
protected $casts = [
'read_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public static function markAsRead(int $userId, string $identifier): void
{
self::firstOrCreate([
'user_id' => $userId,
'release_tag' => $identifier,
], [
'read_at' => now(),
]);
}
public static function isReadByUser(int $userId, string $identifier): bool
{
return self::where('user_id', $userId)
->where('release_tag', $identifier)
->exists();
}
public static function getReadIdentifiersForUser(int $userId): array
{
return self::where('user_id', $userId)
->pluck('release_tag')
->toArray();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Data/CoolifyTaskArgs.php | app/Data/CoolifyTaskArgs.php | <?php
namespace App\Data;
use App\Enums\ProcessStatus;
use Illuminate\Database\Eloquent\Model;
use Spatie\LaravelData\Data;
/**
* The parameters to execute a CoolifyTask, organized in a DTO.
*/
class CoolifyTaskArgs extends Data
{
public function __construct(
public string $server_uuid,
public string $command,
public string $type,
public ?string $type_uuid = null,
public ?int $process_id = null,
public ?Model $model = null,
public ?string $status = null,
public bool $ignore_errors = false,
public $call_event_on_finish = null,
public $call_event_data = null
) {
if (is_null($status)) {
$this->status = ProcessStatus::QUEUED->value;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Data/ServerMetadata.php | app/Data/ServerMetadata.php | <?php
namespace App\Data;
use App\Enums\ProxyStatus;
use App\Enums\ProxyTypes;
use Spatie\LaravelData\Data;
class ServerMetadata extends Data
{
public function __construct(
public ?ProxyTypes $type,
public ?ProxyStatus $status,
public ?string $last_saved_settings = null,
public ?string $last_applied_settings = null
) {}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Repositories/CustomJobRepository.php | app/Repositories/CustomJobRepository.php | <?php
namespace App\Repositories;
use App\Contracts\CustomJobRepositoryInterface;
use Illuminate\Support\Collection;
use Laravel\Horizon\Repositories\RedisJobRepository;
use Laravel\Horizon\Repositories\RedisMasterSupervisorRepository;
class CustomJobRepository extends RedisJobRepository implements CustomJobRepositoryInterface
{
public function getHorizonWorkers()
{
$redisMasterSupervisorRepository = app(RedisMasterSupervisorRepository::class);
return $redisMasterSupervisorRepository->all();
}
public function getReservedJobs(): Collection
{
return $this->getJobsByStatus('reserved');
}
public function getJobsByStatus(string $status): Collection
{
$jobs = new Collection;
$this->getRecent()->each(function ($job) use ($jobs, $status) {
if ($job->status === $status) {
$jobs->push($job);
}
});
return $jobs;
}
public function countJobsByStatus(string $status): int
{
return $this->getJobsByStatus($status)->count();
}
public function getQueues(): array
{
$queues = $this->connection()->keys('queue:*');
$queues = array_map(function ($queue) {
return explode(':', $queue)[2];
}, $queues);
return $queues;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/DuskServiceProvider.php | app/Providers/DuskServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class DuskServiceProvider extends ServiceProvider
{
/**
* Register Dusk's browser macros.
*/
public function boot(): void
{
\Laravel\Dusk\Browser::macro('loginWithRootUser', function () {
return $this->visit('/login')
->type('email', 'test@example.com')
->type('password', 'password')
->press('Login');
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/FortifyServiceProvider.php | app/Providers/FortifyServiceProvider.php | <?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Models\OauthSetting;
use App\Models\User;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Contracts\RegisterResponse;
use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->instance(RegisterResponse::class, new class implements RegisterResponse
{
public function toResponse($request)
{
// First user (root) will be redirected to /settings instead of / on registration.
if ($request->user()->currentTeam->id === 0) {
return redirect()->route('settings.index');
}
return redirect(RouteServiceProvider::HOME);
}
});
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::registerView(function () {
$isFirstUser = User::count() === 0;
$settings = instanceSettings();
if (! $settings->is_registration_enabled) {
return redirect()->route('login');
}
return view('auth.register', [
'isFirstUser' => $isFirstUser,
]);
});
Fortify::loginView(function () {
$settings = instanceSettings();
$enabled_oauth_providers = OauthSetting::where('enabled', true)->get();
$users = User::count();
if ($users == 0) {
// If there are no users, redirect to registration
return redirect()->route('register');
}
return view('auth.login', [
'is_registration_enabled' => $settings->is_registration_enabled,
'enabled_oauth_providers' => $enabled_oauth_providers,
]);
});
Fortify::authenticateUsing(function (Request $request) {
$email = strtolower($request->email);
$user = User::where('email', $email)->with('teams')->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
$user->updated_at = now();
$user->save();
// Check if user has a pending invitation they haven't accepted yet
$invitation = \App\Models\TeamInvitation::whereEmail($email)->first();
if ($invitation && $invitation->isValid()) {
// User is logging in for the first time after being invited
// Attach them to the invited team if not already attached
if (! $user->teams()->where('team_id', $invitation->team->id)->exists()) {
$user->teams()->attach($invitation->team->id, ['role' => $invitation->role]);
}
$user->currentTeam = $invitation->team;
$invitation->delete();
} else {
// Normal login - use personal team
$user->currentTeam = $user->teams->firstWhere('personal_team', true);
if (! $user->currentTeam) {
$user->currentTeam = $user->recreate_personal_team();
}
}
session(['currentTeam' => $user->currentTeam]);
return $user;
}
});
Fortify::requestPasswordResetLinkView(function () {
return view('auth.forgot-password');
});
Fortify::resetPasswordView(function ($request) {
return view('auth.reset-password', ['request' => $request]);
});
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::confirmPasswordView(function () {
return view('auth.confirm-password');
});
Fortify::twoFactorChallengeView(function () {
return view('auth.two-factor-challenge');
});
RateLimiter::for('force-password-reset', function (Request $request) {
return Limit::perMinute(15)->by($request->user()->id);
});
RateLimiter::for('forgot-password', function (Request $request) {
// Use real client IP (not spoofable forwarded headers)
$realIp = $request->server('REMOTE_ADDR') ?? $request->ip();
return Limit::perMinute(5)->by($realIp);
});
RateLimiter::for('login', function (Request $request) {
$email = (string) $request->email;
// Use email + real client IP (not spoofable forwarded headers)
// server('REMOTE_ADDR') gives the actual connecting IP before proxy headers
$realIp = $request->server('REMOTE_ADDR') ?? $request->ip();
return Limit::perMinute(5)->by($email.'|'.$realIp);
});
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/BroadcastServiceProvider.php | app/Providers/BroadcastServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/TelescopeServiceProvider.php | app/Providers/TelescopeServiceProvider.php | <?php
namespace App\Providers;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use Laravel\Telescope\TelescopeApplicationServiceProvider;
class TelescopeServiceProvider extends TelescopeApplicationServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// Telescope::night();
$this->hideSensitiveRequestDetails();
$isLocal = $this->app->environment('local');
Telescope::filter(function (IncomingEntry $entry) use ($isLocal) {
return $isLocal ||
$entry->isReportableException() ||
$entry->isFailedRequest() ||
$entry->isFailedJob() ||
$entry->isScheduledTask() ||
$entry->hasMonitoredTag();
});
}
/**
* Prevent sensitive request details from being logged by Telescope.
*/
protected function hideSensitiveRequestDetails(): void
{
if ($this->app->environment('local')) {
return;
}
Telescope::hideRequestParameters(['_token']);
Telescope::hideRequestHeaders([
'cookie',
'x-csrf-token',
'x-xsrf-token',
]);
}
/**
* Register the Telescope gate.
*
* This gate determines who can access Telescope in non-local environments.
*/
protected function gate(): void
{
Gate::define('viewTelescope', function ($user) {
$root_user = User::find(0);
return in_array($user->email, [
$root_user->email,
]);
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/RouteServiceProvider.php | app/Providers/RouteServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::prefix('webhooks')
->group(base_path('routes/webhooks.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*/
protected function configureRateLimiting(): void
{
RateLimiter::for('api', function (Request $request) {
if ($request->path() === 'api/health') {
return Limit::perMinute(1000)->by($request->user()?->id ?: $request->ip());
}
return Limit::perMinute((int) config('api.rate_limit'))->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('5', function (Request $request) {
return Limit::perMinute(5)->by($request->user()?->id ?: $request->ip());
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/EventServiceProvider.php | app/Providers/EventServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use SocialiteProviders\Authentik\AuthentikExtendSocialite;
use SocialiteProviders\Azure\AzureExtendSocialite;
use SocialiteProviders\Clerk\ClerkExtendSocialite;
use SocialiteProviders\Discord\DiscordExtendSocialite;
use SocialiteProviders\Google\GoogleExtendSocialite;
use SocialiteProviders\Infomaniak\InfomaniakExtendSocialite;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Zitadel\ZitadelExtendSocialite;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
SocialiteWasCalled::class => [
AzureExtendSocialite::class.'@handle',
AuthentikExtendSocialite::class.'@handle',
ClerkExtendSocialite::class.'@handle',
DiscordExtendSocialite::class.'@handle',
GoogleExtendSocialite::class.'@handle',
InfomaniakExtendSocialite::class.'@handle',
ZitadelExtendSocialite::class.'@handle',
],
];
public function boot(): void
{
//
}
public function shouldDiscoverEvents(): bool
{
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/HorizonServiceProvider.php | app/Providers/HorizonServiceProvider.php | <?php
namespace App\Providers;
use App\Contracts\CustomJobRepositoryInterface;
use App\Models\ApplicationDeploymentQueue;
use App\Models\User;
use App\Repositories\CustomJobRepository;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Laravel\Horizon\Contracts\JobRepository;
use Laravel\Horizon\Events\JobReserved;
use Laravel\Horizon\HorizonApplicationServiceProvider;
class HorizonServiceProvider extends HorizonApplicationServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
$this->app->singleton(JobRepository::class, CustomJobRepository::class);
$this->app->singleton(CustomJobRepositoryInterface::class, CustomJobRepository::class);
}
/**
* Bootstrap services.
*/
public function boot(): void
{
parent::boot();
Event::listen(function (JobReserved $event) {
$payload = $event->payload->decoded;
$jobName = $payload['displayName'];
if ($jobName === 'App\Jobs\ApplicationDeploymentJob') {
$tags = $payload['tags'];
$id = $payload['id'];
$deploymentQueueId = collect($tags)->first(function ($tag) {
return str_contains($tag, 'App\Models\ApplicationDeploymentQueue');
});
if (blank($deploymentQueueId)) {
return;
}
$deploymentQueueId = explode(':', $deploymentQueueId)[1];
$deploymentQueue = ApplicationDeploymentQueue::find($deploymentQueueId);
$deploymentQueue->update([
'horizon_job_id' => $id,
]);
}
});
}
protected function gate(): void
{
Gate::define('viewHorizon', function ($user) {
$root_user = User::find(0);
return in_array($user->email, [
$root_user->email,
]);
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/ConfigurationServiceProvider.php | app/Providers/ConfigurationServiceProvider.php | <?php
namespace App\Providers;
use App\Services\ConfigurationRepository;
use Illuminate\Support\ServiceProvider;
class ConfigurationServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(ConfigurationRepository::class, function ($app) {
return new ConfigurationRepository($app['config']);
});
}
public function boot(): void
{
//
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/AppServiceProvider.php | app/Providers/AppServiceProvider.php | <?php
namespace App\Providers;
use App\Models\PersonalAccessToken;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Sanctum\Sanctum;
use Laravel\Telescope\TelescopeServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
if (App::isLocal()) {
$this->app->register(TelescopeServiceProvider::class);
}
}
public function boot(): void
{
$this->configureCommands();
$this->configureModels();
$this->configurePasswords();
$this->configureSanctumModel();
$this->configureGitHubHttp();
}
private function configureCommands(): void
{
if (App::isProduction()) {
DB::prohibitDestructiveCommands();
}
}
private function configureModels(): void
{
// Disabled because it's causing issues with the application
// Model::shouldBeStrict();
}
private function configurePasswords(): void
{
Password::defaults(function () {
return App::isProduction()
? Password::min(8)
->mixedCase()
->letters()
->numbers()
->symbols()
->uncompromised()
: Password::min(8)->letters();
});
}
private function configureSanctumModel(): void
{
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
}
private function configureGitHubHttp(): void
{
Http::macro('GitHub', function (string $api_url, ?string $github_access_token = null) {
if ($github_access_token) {
return Http::withHeaders([
'X-GitHub-Api-Version' => '2022-11-28',
'Accept' => 'application/vnd.github.v3+json',
'Authorization' => "Bearer $github_access_token",
])->baseUrl($api_url);
} else {
return Http::withHeaders([
'Accept' => 'application/vnd.github.v3+json',
])->baseUrl($api_url);
}
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Providers/AuthServiceProvider.php | app/Providers/AuthServiceProvider.php | <?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use App\Policies\ResourceCreatePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
\App\Models\Server::class => \App\Policies\ServerPolicy::class,
\App\Models\PrivateKey::class => \App\Policies\PrivateKeyPolicy::class,
\App\Models\StandaloneDocker::class => \App\Policies\StandaloneDockerPolicy::class,
\App\Models\SwarmDocker::class => \App\Policies\SwarmDockerPolicy::class,
\App\Models\Application::class => \App\Policies\ApplicationPolicy::class,
\App\Models\ApplicationPreview::class => \App\Policies\ApplicationPreviewPolicy::class,
\App\Models\ApplicationSetting::class => \App\Policies\ApplicationSettingPolicy::class,
\App\Models\Service::class => \App\Policies\ServicePolicy::class,
\App\Models\ServiceApplication::class => \App\Policies\ServiceApplicationPolicy::class,
\App\Models\ServiceDatabase::class => \App\Policies\ServiceDatabasePolicy::class,
\App\Models\Project::class => \App\Policies\ProjectPolicy::class,
\App\Models\Environment::class => \App\Policies\EnvironmentPolicy::class,
\App\Models\EnvironmentVariable::class => \App\Policies\EnvironmentVariablePolicy::class,
\App\Models\SharedEnvironmentVariable::class => \App\Policies\SharedEnvironmentVariablePolicy::class,
// Database policies - all use the shared DatabasePolicy
\App\Models\StandalonePostgresql::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneMysql::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneMariadb::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneMongodb::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneRedis::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneKeydb::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneDragonfly::class => \App\Policies\DatabasePolicy::class,
\App\Models\StandaloneClickhouse::class => \App\Policies\DatabasePolicy::class,
// Notification policies - all use the shared NotificationPolicy
\App\Models\EmailNotificationSettings::class => \App\Policies\NotificationPolicy::class,
\App\Models\DiscordNotificationSettings::class => \App\Policies\NotificationPolicy::class,
\App\Models\TelegramNotificationSettings::class => \App\Policies\NotificationPolicy::class,
\App\Models\SlackNotificationSettings::class => \App\Policies\NotificationPolicy::class,
\App\Models\PushoverNotificationSettings::class => \App\Policies\NotificationPolicy::class,
\App\Models\WebhookNotificationSettings::class => \App\Policies\NotificationPolicy::class,
// API Token policy
\Laravel\Sanctum\PersonalAccessToken::class => \App\Policies\ApiTokenPolicy::class,
// Instance settings policy
\App\Models\InstanceSettings::class => \App\Policies\InstanceSettingsPolicy::class,
// Team policy
\App\Models\Team::class => \App\Policies\TeamPolicy::class,
// Git source policies
\App\Models\GithubApp::class => \App\Policies\GithubAppPolicy::class,
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
// Register gates for resource creation policy
Gate::define('createAnyResource', [ResourceCreatePolicy::class, 'createAny']);
// Register gate for terminal access
Gate::define('canAccessTerminal', function ($user) {
return $user->isAdmin() || $user->isOwner();
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ProxyStatusChanged.php | app/Events/ProxyStatusChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ProxyStatusChanged
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(public $data) {}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/CloudflareTunnelConfigured.php | app/Events/CloudflareTunnelConfigured.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CloudflareTunnelConfigured implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ServiceChecked.php | app/Events/ServiceChecked.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Laravel\Horizon\Contracts\Silenced;
class ServiceChecked implements ShouldBroadcast, Silenced
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ServerValidated.php | app/Events/ServerValidated.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ServerValidated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public ?string $serverUuid = null;
public function __construct(?int $teamId = null, ?string $serverUuid = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
$this->serverUuid = $serverUuid;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
public function broadcastAs(): string
{
return 'ServerValidated';
}
public function broadcastWith(): array
{
return [
'teamId' => $this->teamId,
'serverUuid' => $this->serverUuid,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/SentinelRestarted.php | app/Events/SentinelRestarted.php | <?php
namespace App\Events;
use App\Models\Server;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class SentinelRestarted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public ?string $version = null;
public string $serverUuid;
public function __construct(Server $server, ?string $version = null)
{
$this->teamId = $server->team_id;
$this->serverUuid = $server->uuid;
$this->version = $version;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ScheduledTaskDone.php | app/Events/ScheduledTaskDone.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ScheduledTaskDone implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/CloudflareTunnelChanged.php | app/Events/CloudflareTunnelChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CloudflareTunnelChanged
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(public $data) {}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ServiceStatusChanged.php | app/Events/ServiceStatusChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Auth;
class ServiceStatusChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public ?int $teamId = null
) {
if (is_null($this->teamId) && Auth::check() && Auth::user()->currentTeam()) {
$this->teamId = Auth::user()->currentTeam()->id;
}
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/DockerCleanupDone.php | app/Events/DockerCleanupDone.php | <?php
namespace App\Events;
use App\Models\DockerCleanupExecution;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class DockerCleanupDone implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(public DockerCleanupExecution $execution) {}
public function broadcastOn(): array
{
return [
new PrivateChannel('team.'.$this->execution->server->team->id),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/BackupCreated.php | app/Events/BackupCreated.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Laravel\Horizon\Contracts\Silenced;
class BackupCreated implements ShouldBroadcast, Silenced
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ServerReachabilityChanged.php | app/Events/ServerReachabilityChanged.php | <?php
namespace App\Events;
use App\Models\Server;
use Illuminate\Foundation\Events\Dispatchable;
class ServerReachabilityChanged
{
use Dispatchable;
public function __construct(
public readonly Server $server
) {
$this->server->isReachableChanged();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ApplicationStatusChanged.php | app/Events/ApplicationStatusChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ApplicationStatusChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ApplicationConfigurationChanged.php | app/Events/ApplicationConfigurationChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ApplicationConfigurationChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/S3RestoreJobFinished.php | app/Events/S3RestoreJobFinished.php | <?php
namespace App\Events;
use App\Models\Server;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class S3RestoreJobFinished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct($data)
{
$containerName = data_get($data, 'containerName');
$serverTmpPath = data_get($data, 'serverTmpPath');
$scriptPath = data_get($data, 'scriptPath');
$containerTmpPath = data_get($data, 'containerTmpPath');
$container = data_get($data, 'container');
$serverId = data_get($data, 'serverId');
// Most cleanup now happens inline during restore process
// This acts as a safety net for edge cases (errors, interruptions)
if (filled($serverId)) {
$commands = [];
// Ensure helper container is removed (may already be gone from inline cleanup)
if (filled($containerName)) {
$commands[] = 'docker rm -f '.escapeshellarg($containerName).' 2>/dev/null || true';
}
// Clean up server temp file if still exists (should already be cleaned)
if (isSafeTmpPath($serverTmpPath)) {
$commands[] = 'rm -f '.escapeshellarg($serverTmpPath).' 2>/dev/null || true';
}
// Clean up any remaining files in database container (may already be cleaned)
if (filled($container)) {
if (isSafeTmpPath($containerTmpPath)) {
$commands[] = 'docker exec '.escapeshellarg($container).' rm -f '.escapeshellarg($containerTmpPath).' 2>/dev/null || true';
}
if (isSafeTmpPath($scriptPath)) {
$commands[] = 'docker exec '.escapeshellarg($container).' rm -f '.escapeshellarg($scriptPath).' 2>/dev/null || true';
}
}
if (! empty($commands)) {
$server = Server::find($serverId);
if ($server) {
instant_remote_process($commands, $server, throwError: false);
}
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/RestoreJobFinished.php | app/Events/RestoreJobFinished.php | <?php
namespace App\Events;
use App\Models\Server;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class RestoreJobFinished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct($data)
{
$scriptPath = data_get($data, 'scriptPath');
$tmpPath = data_get($data, 'tmpPath');
$container = data_get($data, 'container');
$serverId = data_get($data, 'serverId');
if (filled($container) && filled($serverId)) {
$commands = [];
if (isSafeTmpPath($scriptPath)) {
$commands[] = 'docker exec '.escapeshellarg($container)." sh -c 'rm ".escapeshellarg($scriptPath)." 2>/dev/null || true'";
}
if (isSafeTmpPath($tmpPath)) {
$commands[] = 'docker exec '.escapeshellarg($container)." sh -c 'rm ".escapeshellarg($tmpPath)." 2>/dev/null || true'";
}
if (! empty($commands)) {
$server = Server::find($serverId);
if ($server) {
instant_remote_process($commands, $server, throwError: false);
}
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/TestEvent.php | app/Events/TestEvent.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class TestEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct()
{
if (auth()->check() && auth()->user()->currentTeam()) {
$this->teamId = auth()->user()->currentTeam()->id;
}
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/DatabaseStatusChanged.php | app/Events/DatabaseStatusChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Auth;
class DatabaseStatusChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public int|string|null $userId = null;
public function __construct($userId = null)
{
if (is_null($userId)) {
$userId = Auth::id() ?? null;
}
$this->userId = $userId;
}
public function broadcastOn(): ?array
{
if (is_null($this->userId)) {
return [];
}
return [
new PrivateChannel("user.{$this->userId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/FileStorageChanged.php | app/Events/FileStorageChanged.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class FileStorageChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ProxyStatusChangedUI.php | app/Events/ProxyStatusChangedUI.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ProxyStatusChangedUI implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public ?int $activityId = null;
public function __construct(?int $teamId = null, ?int $activityId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
$this->activityId = $activityId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/DatabaseProxyStopped.php | app/Events/DatabaseProxyStopped.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class DatabaseProxyStopped implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Events/ServerPackageUpdated.php | app/Events/ServerPackageUpdated.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ServerPackageUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ?int $teamId = null;
public function __construct($teamId = null)
{
if (is_null($teamId) && auth()->check() && auth()->user()->currentTeam()) {
$teamId = auth()->user()->currentTeam()->id;
}
$this->teamId = $teamId;
}
public function broadcastOn(): array
{
if (is_null($this->teamId)) {
return [];
}
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ApplicationSettingPolicy.php | app/Policies/ApplicationSettingPolicy.php | <?php
namespace App\Policies;
use App\Models\ApplicationSetting;
use App\Models\User;
class ApplicationSettingPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, ApplicationSetting $applicationSetting): bool
{
// return $user->teams->contains('id', $applicationSetting->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, ApplicationSetting $applicationSetting): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationSetting->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, ApplicationSetting $applicationSetting): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationSetting->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, ApplicationSetting $applicationSetting): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationSetting->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, ApplicationSetting $applicationSetting): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationSetting->application->team()->first()->id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/EnvironmentPolicy.php | app/Policies/EnvironmentPolicy.php | <?php
namespace App\Policies;
use App\Models\Environment;
use App\Models\User;
class EnvironmentPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Environment $environment): bool
{
// return $user->teams->contains('id', $environment->project->team_id);
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Environment $environment): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $environment->project->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Environment $environment): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $environment->project->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Environment $environment): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $environment->project->team_id);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Environment $environment): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $environment->project->team_id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/CloudInitScriptPolicy.php | app/Policies/CloudInitScriptPolicy.php | <?php
namespace App\Policies;
use App\Models\CloudInitScript;
use App\Models\User;
class CloudInitScriptPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, CloudInitScript $cloudInitScript): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, CloudInitScript $cloudInitScript): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, CloudInitScript $cloudInitScript): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, CloudInitScript $cloudInitScript): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, CloudInitScript $cloudInitScript): bool
{
return $user->isAdmin();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ProjectPolicy.php | app/Policies/ProjectPolicy.php | <?php
namespace App\Policies;
use App\Models\Project;
use App\Models\User;
class ProjectPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Project $project): bool
{
// return $user->teams->contains('id', $project->team_id);
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Project $project): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $project->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Project $project): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $project->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Project $project): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $project->team_id);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Project $project): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $project->team_id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ResourceCreatePolicy.php | app/Policies/ResourceCreatePolicy.php | <?php
namespace App\Policies;
use App\Models\Application;
use App\Models\Service;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\User;
class ResourceCreatePolicy
{
/**
* List of resource classes that can be created
*/
public const CREATABLE_RESOURCES = [
StandalonePostgresql::class,
StandaloneRedis::class,
StandaloneMongodb::class,
StandaloneMysql::class,
StandaloneMariadb::class,
StandaloneKeydb::class,
StandaloneDragonfly::class,
StandaloneClickhouse::class,
Service::class,
Application::class,
GithubApp::class,
];
/**
* Determine whether the user can create any resource.
*/
public function createAny(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can create a specific resource type.
*/
public function create(User $user, string $resourceClass): bool
{
if (! in_array($resourceClass, self::CREATABLE_RESOURCES)) {
return false;
}
// return $user->isAdmin();
return true;
}
/**
* Authorize creation of all supported resource types.
*/
public function authorizeAllResourceCreation(User $user): bool
{
return $this->createAny($user);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/StandaloneDockerPolicy.php | app/Policies/StandaloneDockerPolicy.php | <?php
namespace App\Policies;
use App\Models\StandaloneDocker;
use App\Models\User;
class StandaloneDockerPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, StandaloneDocker $standaloneDocker): bool
{
return $user->teams->contains('id', $standaloneDocker->server->team_id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, StandaloneDocker $standaloneDocker): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $standaloneDocker->server->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, StandaloneDocker $standaloneDocker): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $standaloneDocker->server->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, StandaloneDocker $standaloneDocker): bool
{
// return false;
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, StandaloneDocker $standaloneDocker): bool
{
// return false;
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/CloudProviderTokenPolicy.php | app/Policies/CloudProviderTokenPolicy.php | <?php
namespace App\Policies;
use App\Models\CloudProviderToken;
use App\Models\User;
class CloudProviderTokenPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, CloudProviderToken $cloudProviderToken): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, CloudProviderToken $cloudProviderToken): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, CloudProviderToken $cloudProviderToken): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, CloudProviderToken $cloudProviderToken): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, CloudProviderToken $cloudProviderToken): bool
{
return $user->isAdmin();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/PrivateKeyPolicy.php | app/Policies/PrivateKeyPolicy.php | <?php
namespace App\Policies;
use App\Models\PrivateKey;
use App\Models\User;
class PrivateKeyPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, PrivateKey $privateKey): bool
{
// Handle null team_id
if ($privateKey->team_id === null) {
return false;
}
// System resource (team_id=0): Only root team admins/owners can access
if ($privateKey->team_id === 0) {
return $user->canAccessSystemResources();
}
// Regular resource: Check team membership
return $user->teams->contains('id', $privateKey->team_id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// Only admins/owners can create private keys
// Members should not be able to create SSH keys that could be used for deployments
return $user->isAdmin();
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, PrivateKey $privateKey): bool
{
// Handle null team_id
if ($privateKey->team_id === null) {
return false;
}
// System resource (team_id=0): Only root team admins/owners can update
if ($privateKey->team_id === 0) {
return $user->canAccessSystemResources();
}
// Regular resource: Must be admin/owner of the team
return $user->isAdminOfTeam($privateKey->team_id)
&& $user->teams->contains('id', $privateKey->team_id);
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, PrivateKey $privateKey): bool
{
// Handle null team_id
if ($privateKey->team_id === null) {
return false;
}
// System resource (team_id=0): Only root team admins/owners can delete
if ($privateKey->team_id === 0) {
return $user->canAccessSystemResources();
}
// Regular resource: Must be admin/owner of the team
return $user->isAdminOfTeam($privateKey->team_id)
&& $user->teams->contains('id', $privateKey->team_id);
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, PrivateKey $privateKey): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, PrivateKey $privateKey): bool
{
return false;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ServicePolicy.php | app/Policies/ServicePolicy.php | <?php
namespace App\Policies;
use App\Models\Service;
use App\Models\User;
class ServicePolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Service $service): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Service $service): bool
{
$team = $service->team();
if (! $team) {
return false;
}
// return $user->isAdmin() && $user->teams->contains('id', $team->id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Service $service): bool
{
// if ($user->isAdmin()) {
// return true;
// }
// return false;
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Service $service): bool
{
// return true;
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Service $service): bool
{
// if ($user->isAdmin()) {
// return true;
// }
// return false;
return true;
}
public function stop(User $user, Service $service): bool
{
$team = $service->team();
if (! $team) {
return false;
}
// return $user->teams->contains('id', $team->id);
return true;
}
/**
* Determine whether the user can manage environment variables.
*/
public function manageEnvironment(User $user, Service $service): bool
{
$team = $service->team();
if (! $team) {
return false;
}
// return $user->isAdmin() && $user->teams->contains('id', $team->id);
return true;
}
/**
* Determine whether the user can deploy the service.
*/
public function deploy(User $user, Service $service): bool
{
$team = $service->team();
if (! $team) {
return false;
}
// return $user->teams->contains('id', $team->id);
return true;
}
public function accessTerminal(User $user, Service $service): bool
{
// return $user->isAdmin() || $user->teams->contains('id', $service->team()->id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/EnvironmentVariablePolicy.php | app/Policies/EnvironmentVariablePolicy.php | <?php
namespace App\Policies;
use App\Models\EnvironmentVariable;
use App\Models\User;
class EnvironmentVariablePolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, EnvironmentVariable $environmentVariable): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, EnvironmentVariable $environmentVariable): bool
{
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, EnvironmentVariable $environmentVariable): bool
{
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, EnvironmentVariable $environmentVariable): bool
{
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, EnvironmentVariable $environmentVariable): bool
{
return true;
}
/**
* Determine whether the user can manage environment variables.
*/
public function manageEnvironment(User $user, EnvironmentVariable $environmentVariable): bool
{
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/SharedEnvironmentVariablePolicy.php | app/Policies/SharedEnvironmentVariablePolicy.php | <?php
namespace App\Policies;
use App\Models\SharedEnvironmentVariable;
use App\Models\User;
class SharedEnvironmentVariablePolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, SharedEnvironmentVariable $sharedEnvironmentVariable): bool
{
return $user->teams->contains('id', $sharedEnvironmentVariable->team_id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, SharedEnvironmentVariable $sharedEnvironmentVariable): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $sharedEnvironmentVariable->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, SharedEnvironmentVariable $sharedEnvironmentVariable): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $sharedEnvironmentVariable->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, SharedEnvironmentVariable $sharedEnvironmentVariable): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $sharedEnvironmentVariable->team_id);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, SharedEnvironmentVariable $sharedEnvironmentVariable): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $sharedEnvironmentVariable->team_id);
return true;
}
/**
* Determine whether the user can manage environment variables.
*/
public function manageEnvironment(User $user, SharedEnvironmentVariable $sharedEnvironmentVariable): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $sharedEnvironmentVariable->team_id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/NotificationPolicy.php | app/Policies/NotificationPolicy.php | <?php
namespace App\Policies;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
class NotificationPolicy
{
/**
* Determine whether the user can view the notification settings.
*/
public function view(User $user, Model $notificationSettings): bool
{
// Check if the notification settings belong to the user's current team
if (! $notificationSettings->team) {
return false;
}
// return $user->teams()->where('teams.id', $notificationSettings->team->id)->exists();
return true;
}
/**
* Determine whether the user can update the notification settings.
*/
public function update(User $user, Model $notificationSettings): bool
{
// Check if the notification settings belong to the user's current team
if (! $notificationSettings->team) {
return false;
}
// Only owners and admins can update notification settings
// return $user->isAdmin() || $user->isOwner();
return true;
}
/**
* Determine whether the user can manage (create, update, delete) notification settings.
*/
public function manage(User $user, Model $notificationSettings): bool
{
// return $this->update($user, $notificationSettings);
return true;
}
/**
* Determine whether the user can send test notifications.
*/
public function sendTest(User $user, Model $notificationSettings): bool
{
// return $this->update($user, $notificationSettings);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ApplicationPolicy.php | app/Policies/ApplicationPolicy.php | <?php
namespace App\Policies;
use App\Models\Application;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class ApplicationPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
// Authorization temporarily disabled
/*
return true;
*/
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
return true;
*/
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// Authorization temporarily disabled
/*
if ($user->isAdmin()) {
return true;
}
return false;
*/
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Application $application): Response
{
// Authorization temporarily disabled
/*
if ($user->isAdmin()) {
return Response::allow();
}
return Response::deny('As a member, you cannot update this application.<br/><br/>You need at least admin or owner permissions.');
*/
return Response::allow();
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
if ($user->isAdmin()) {
return true;
}
return false;
*/
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
return true;
*/
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
return $user->isAdmin() && $user->teams->contains('id', $application->team()->first()->id);
*/
return true;
}
/**
* Determine whether the user can deploy the application.
*/
public function deploy(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
return $user->teams->contains('id', $application->team()->first()->id);
*/
return true;
}
/**
* Determine whether the user can manage deployments.
*/
public function manageDeployments(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
return $user->isAdmin() && $user->teams->contains('id', $application->team()->first()->id);
*/
return true;
}
/**
* Determine whether the user can manage environment variables.
*/
public function manageEnvironment(User $user, Application $application): bool
{
// Authorization temporarily disabled
/*
return $user->isAdmin() && $user->teams->contains('id', $application->team()->first()->id);
*/
return true;
}
/**
* Determine whether the user can cleanup deployment queue.
*/
public function cleanupDeploymentQueue(User $user): bool
{
// Authorization temporarily disabled
/*
return $user->isAdmin();
*/
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ApplicationPreviewPolicy.php | app/Policies/ApplicationPreviewPolicy.php | <?php
namespace App\Policies;
use App\Models\ApplicationPreview;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class ApplicationPreviewPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, ApplicationPreview $applicationPreview): bool
{
// return $user->teams->contains('id', $applicationPreview->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, ApplicationPreview $applicationPreview)
{
// if ($user->isAdmin()) {
// return Response::allow();
// }
// return Response::deny('As a member, you cannot update this preview.<br/><br/>You need at least admin or owner permissions.');
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, ApplicationPreview $applicationPreview): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationPreview->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, ApplicationPreview $applicationPreview): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationPreview->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, ApplicationPreview $applicationPreview): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationPreview->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can deploy the preview.
*/
public function deploy(User $user, ApplicationPreview $applicationPreview): bool
{
// return $user->teams->contains('id', $applicationPreview->application->team()->first()->id);
return true;
}
/**
* Determine whether the user can manage preview deployments.
*/
public function manageDeployments(User $user, ApplicationPreview $applicationPreview): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $applicationPreview->application->team()->first()->id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/TeamPolicy.php | app/Policies/TeamPolicy.php | <?php
namespace App\Policies;
use App\Models\Team;
use App\Models\User;
class TeamPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Team $team): bool
{
return $user->teams->contains('id', $team->id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// All authenticated users can create teams
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Team $team): bool
{
// Only admins and owners can update team settings
if (! $user->teams->contains('id', $team->id)) {
return false;
}
return $user->isAdmin() || $user->isOwner();
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Team $team): bool
{
// Only admins and owners can delete teams
if (! $user->teams->contains('id', $team->id)) {
return false;
}
return $user->isAdmin() || $user->isOwner();
}
/**
* Determine whether the user can manage team members.
*/
public function manageMembers(User $user, Team $team): bool
{
// Only admins and owners can manage team members
if (! $user->teams->contains('id', $team->id)) {
return false;
}
return $user->isAdmin() || $user->isOwner();
}
/**
* Determine whether the user can view admin panel.
*/
public function viewAdmin(User $user, Team $team): bool
{
// Only admins and owners can view admin panel
if (! $user->teams->contains('id', $team->id)) {
return false;
}
return $user->isAdmin() || $user->isOwner();
}
/**
* Determine whether the user can manage invitations.
*/
public function manageInvitations(User $user, Team $team): bool
{
// Only admins and owners can manage invitations
if (! $user->teams->contains('id', $team->id)) {
return false;
}
return $user->isAdmin() || $user->isOwner();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/DatabasePolicy.php | app/Policies/DatabasePolicy.php | <?php
namespace App\Policies;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class DatabasePolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, $database): bool
{
// return $user->teams->contains('id', $database->team()->first()->id);
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, $database)
{
// if ($user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id)) {
// return Response::allow();
// }
// return Response::deny('As a member, you cannot update this database.<br/><br/>You need at least admin or owner permissions.');
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, $database): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, $database): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, $database): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id);
return true;
}
/**
* Determine whether the user can start/stop the database.
*/
public function manage(User $user, $database): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id);
return true;
}
/**
* Determine whether the user can manage database backups.
*/
public function manageBackups(User $user, $database): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id);
return true;
}
/**
* Determine whether the user can manage environment variables.
*/
public function manageEnvironment(User $user, $database): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $database->team()->first()->id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ApiTokenPolicy.php | app/Policies/ApiTokenPolicy.php | <?php
namespace App\Policies;
use App\Models\User;
use Laravel\Sanctum\PersonalAccessToken;
class ApiTokenPolicy
{
/**
* Determine whether the user can view any API tokens.
*/
public function viewAny(User $user): bool
{
// Authorization temporarily disabled
/*
// Users can view their own API tokens
return true;
*/
return true;
}
/**
* Determine whether the user can view the API token.
*/
public function view(User $user, PersonalAccessToken $token): bool
{
// Authorization temporarily disabled
/*
// Users can only view their own tokens
return $user->id === $token->tokenable_id && $token->tokenable_type === User::class;
*/
return true;
}
/**
* Determine whether the user can create API tokens.
*/
public function create(User $user): bool
{
// Authorization temporarily disabled
/*
// All authenticated users can create their own API tokens
return true;
*/
return true;
}
/**
* Determine whether the user can update the API token.
*/
public function update(User $user, PersonalAccessToken $token): bool
{
// Authorization temporarily disabled
/*
// Users can only update their own tokens
return $user->id === $token->tokenable_id && $token->tokenable_type === User::class;
*/
return true;
}
/**
* Determine whether the user can delete the API token.
*/
public function delete(User $user, PersonalAccessToken $token): bool
{
// Authorization temporarily disabled
/*
// Users can only delete their own tokens
return $user->id === $token->tokenable_id && $token->tokenable_type === User::class;
*/
return true;
}
/**
* Determine whether the user can manage their own API tokens.
*/
public function manage(User $user): bool
{
// Authorization temporarily disabled
/*
// All authenticated users can manage their own API tokens
return true;
*/
return true;
}
/**
* Determine whether the user can use root permissions for API tokens.
*/
public function useRootPermissions(User $user): bool
{
// Only admins and owners can use root permissions
return $user->isAdmin() || $user->isOwner();
}
/**
* Determine whether the user can use write permissions for API tokens.
*/
public function useWritePermissions(User $user): bool
{
// Authorization temporarily disabled
/*
// Only admins and owners can use write permissions
return $user->isAdmin() || $user->isOwner();
*/
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/SwarmDockerPolicy.php | app/Policies/SwarmDockerPolicy.php | <?php
namespace App\Policies;
use App\Models\SwarmDocker;
use App\Models\User;
class SwarmDockerPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, SwarmDocker $swarmDocker): bool
{
return $user->teams->contains('id', $swarmDocker->server->team_id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, SwarmDocker $swarmDocker): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $swarmDocker->server->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, SwarmDocker $swarmDocker): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $swarmDocker->server->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, SwarmDocker $swarmDocker): bool
{
// return false;
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, SwarmDocker $swarmDocker): bool
{
// return false;
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ServerPolicy.php | app/Policies/ServerPolicy.php | <?php
namespace App\Policies;
use App\Models\Server;
use App\Models\User;
class ServerPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Server $server): bool
{
return $user->teams->contains('id', $server->team_id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Server $server): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $server->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Server $server): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $server->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Server $server): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Server $server): bool
{
return false;
}
/**
* Determine whether the user can manage proxy (start/stop/restart).
*/
public function manageProxy(User $user, Server $server): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $server->team_id);
return true;
}
/**
* Determine whether the user can manage sentinel (start/stop).
*/
public function manageSentinel(User $user, Server $server): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $server->team_id);
return true;
}
/**
* Determine whether the user can manage CA certificates.
*/
public function manageCaCertificate(User $user, Server $server): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $server->team_id);
return true;
}
/**
* Determine whether the user can view security views.
*/
public function viewSecurity(User $user, Server $server): bool
{
// return $user->isAdmin() && $user->teams->contains('id', $server->team_id);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ServiceDatabasePolicy.php | app/Policies/ServiceDatabasePolicy.php | <?php
namespace App\Policies;
use App\Models\ServiceDatabase;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
class ServiceDatabasePolicy
{
/**
* Determine whether the user can view the model.
*/
public function view(User $user, ServiceDatabase $serviceDatabase): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, ServiceDatabase $serviceDatabase): bool
{
// return Gate::allows('update', $serviceDatabase->service);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, ServiceDatabase $serviceDatabase): bool
{
// return Gate::allows('delete', $serviceDatabase->service);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, ServiceDatabase $serviceDatabase): bool
{
// return Gate::allows('update', $serviceDatabase->service);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, ServiceDatabase $serviceDatabase): bool
{
// return Gate::allows('delete', $serviceDatabase->service);
return true;
}
public function manageBackups(User $user, ServiceDatabase $serviceDatabase): bool
{
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/S3StoragePolicy.php | app/Policies/S3StoragePolicy.php | <?php
namespace App\Policies;
use App\Models\S3Storage;
use App\Models\User;
class S3StoragePolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, S3Storage $storage): bool
{
return $user->teams->contains('id', $storage->team_id);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return $user->isAdmin();
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, S3Storage $storage): bool
{
// return $user->teams->contains('id', $storage->team_id) && $user->isAdmin();
return $user->teams->contains('id', $storage->team_id);
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, S3Storage $storage): bool
{
// return $user->teams->contains('id', $storage->team_id) && $user->isAdmin();
return $user->teams->contains('id', $storage->team_id);
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, S3Storage $storage): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, S3Storage $storage): bool
{
return false;
}
/**
* Determine whether the user can validate the connection of the model.
*/
public function validateConnection(User $user, S3Storage $storage): bool
{
return $user->teams->contains('id', $storage->team_id);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/ServiceApplicationPolicy.php | app/Policies/ServiceApplicationPolicy.php | <?php
namespace App\Policies;
use App\Models\ServiceApplication;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
class ServiceApplicationPolicy
{
/**
* Determine whether the user can view the model.
*/
public function view(User $user, ServiceApplication $serviceApplication): bool
{
return Gate::allows('view', $serviceApplication->service);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, ServiceApplication $serviceApplication): bool
{
// return Gate::allows('update', $serviceApplication->service);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, ServiceApplication $serviceApplication): bool
{
// return Gate::allows('delete', $serviceApplication->service);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, ServiceApplication $serviceApplication): bool
{
// return Gate::allows('update', $serviceApplication->service);
return true;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, ServiceApplication $serviceApplication): bool
{
// return Gate::allows('delete', $serviceApplication->service);
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/InstanceSettingsPolicy.php | app/Policies/InstanceSettingsPolicy.php | <?php
namespace App\Policies;
use App\Models\InstanceSettings;
use App\Models\User;
class InstanceSettingsPolicy
{
/**
* Determine whether the user can view the instance settings.
*/
public function view(User $user, InstanceSettings $settings): bool
{
return isInstanceAdmin();
}
/**
* Determine whether the user can update the instance settings.
*/
public function update(User $user, InstanceSettings $settings): bool
{
return isInstanceAdmin();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Policies/GithubAppPolicy.php | app/Policies/GithubAppPolicy.php | <?php
namespace App\Policies;
use App\Models\GithubApp;
use App\Models\User;
class GithubAppPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, GithubApp $githubApp): bool
{
// return $user->teams->contains('id', $githubApp->team_id) || $githubApp->is_system_wide;
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
// return $user->isAdmin();
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, GithubApp $githubApp): bool
{
if ($githubApp->is_system_wide) {
// return $user->isAdmin();
return true;
}
// return $user->isAdmin() && $user->teams->contains('id', $githubApp->team_id);
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, GithubApp $githubApp): bool
{
if ($githubApp->is_system_wide) {
// return $user->isAdmin();
return true;
}
// return $user->isAdmin() && $user->teams->contains('id', $githubApp->team_id);
return true;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, GithubApp $githubApp): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, GithubApp $githubApp): bool
{
return false;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/ResourceView.php | app/View/Components/ResourceView.php | <?php
namespace App\View\Components;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class ResourceView extends Component
{
/**
* Create a new component instance.
*/
public function __construct(
public ?string $wire = null,
public ?string $logo = null,
public ?string $documentation = null,
public bool $upgrade = false,
) {}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.resource-view');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.