コード例 #1
0
        public override async Task <TenantDto> CreateAsync(CreateTenantDto input)
        {
            CheckCreatePermission();

            // Create tenant
            var tenant = ObjectMapper.Map <Tenant>(input);
            // tenant.ConnectionString = input.ConnectionString.IsNullOrEmpty()
            //     ? null
            //     : SimpleStringCipher.Instance.Encrypt(input.ConnectionString);

            var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName);

            if (defaultEdition != null)
            {
                tenant.EditionId = defaultEdition.Id;
            }

            await _tenantManager.CreateAsync(tenant);

            await CurrentUnitOfWork.SaveChangesAsync(); // To get new tenant's id.

            // Create tenant database
            _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);

            // We are working entities of new tenant, so changing tenant filter
            using (CurrentUnitOfWork.SetTenantId(tenant.Id))
            {
                // Create static roles for new tenant
                CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));

                await CurrentUnitOfWork.SaveChangesAsync(); // To get static role ids

                // Grant all permissions to admin role
                var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin);
                await _roleManager.GrantAllPermissionsAsync(adminRole);

                // Create admin Organization Unit
                string           code    = _ouManager.GetNextChildCode(null);
                OrganizationUnit adminOu = new OrganizationUnit()
                {
                    TenantId    = tenant.Id,
                    ParentId    = null,
                    DisplayName = "AdminGroup",
                    Code        = code
                };
                adminOu.Id = await _ouRepository.InsertAndGetIdAsync(adminOu);

                await _roleManager.SetOrganizationUnitsAsync(adminRole, new[] { adminOu.Id });

                // Create admin user for the tenant
                var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress);
                await _userManager.InitializeOptionsAsync(tenant.Id);

                CheckErrors(await _userManager.CreateAsync(adminUser, User.DefaultPassword));
                await CurrentUnitOfWork.SaveChangesAsync(); // To get admin user's id

                // Assign admin user to AdminGroup ou.
                await _userManager.AddToOrganizationUnitAsync(adminUser, adminOu);

                // Assign admin user to role!
                CheckErrors(await _userManager.AddToRoleAsync(adminUser, adminRole.Name));
                await CurrentUnitOfWork.SaveChangesAsync();
            }

            return(MapToEntityDto(tenant));
        }