@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\SystemRole;
|
||||
use App\Models\DeploymentInstallation;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantDevicePolicy;
|
||||
use App\Models\User;
|
||||
use App\Services\Encryption\TenantEnvelopeEncryption;
|
||||
use App\Support\SystemRolePermissions;
|
||||
use App\Support\TenantContext;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Spatie\Permission\Models\Role;
|
||||
|
||||
class TenantProvisioningService
|
||||
{
|
||||
public function __construct(private readonly TenantContext $context) {}
|
||||
|
||||
/** @param array{name:string,slug:string,is_active?:bool,owner_name:string,owner_email:string,owner_password:string} $data */
|
||||
public function createWithOwner(array $data): Tenant
|
||||
{
|
||||
return DB::transaction(function () use ($data): Tenant {
|
||||
$tenant = Tenant::create([
|
||||
'name' => $data['name'],
|
||||
'slug' => $data['slug'],
|
||||
'is_active' => $data['is_active'] ?? true,
|
||||
]);
|
||||
TenantDevicePolicy::create(['tenant_id' => $tenant->id]);
|
||||
app(TenantEnvelopeEncryption::class)->ensureKey($tenant->id);
|
||||
$deploymentType = $data['deployment_type'] ?? 'managed_cloud';
|
||||
DeploymentInstallation::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $deploymentType === 'self_hosted' ? 'Server Tenant' : 'RADIQ Managed Cloud',
|
||||
'deployment_type' => $deploymentType,
|
||||
'domain' => $data['deployment_domain'] ?? null,
|
||||
'instance_key_hash' => hash('sha256', random_bytes(32)),
|
||||
'status' => $deploymentType === 'managed_cloud' ? 'active' : 'pending',
|
||||
'activated_at' => $deploymentType === 'managed_cloud' ? now() : null,
|
||||
]);
|
||||
|
||||
$this->context->set($tenant->id);
|
||||
setPermissionsTeamId($tenant->id);
|
||||
|
||||
try {
|
||||
$roles = $this->createDefaultRoles($tenant);
|
||||
|
||||
$owner = User::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $data['owner_name'],
|
||||
'email' => $data['owner_email'],
|
||||
'password' => $data['owner_password'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
$owner->forceFill(['email_verified_at' => now()])->save();
|
||||
$owner->assignRole($roles[SystemRole::TenantAdmin->value]);
|
||||
} finally {
|
||||
$this->context->clear();
|
||||
setPermissionsTeamId(null);
|
||||
}
|
||||
|
||||
return $tenant;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string, Role> */
|
||||
private function createDefaultRoles(Tenant $tenant): array
|
||||
{
|
||||
$definitions = SystemRolePermissions::tenantRoles();
|
||||
|
||||
$roles = [];
|
||||
|
||||
foreach ($definitions as $name => $permissions) {
|
||||
$role = Role::create(['tenant_id' => $tenant->id, 'name' => $name, 'guard_name' => 'web']);
|
||||
$role->syncPermissions($permissions);
|
||||
$roles[$name] = $role;
|
||||
}
|
||||
|
||||
return $roles;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user