public override async Task <CategoryItemDto> GetAsync(Guid id) { var categoryItems = await Repository.GetQueryableAsync(); var query = (from categoryItem in categoryItems join category in _categoryRepository on categoryItem.CategoryId equals category.Id join item in _itemRepository on categoryItem.ItemId equals item.Id where categoryItem.Id == id select new { categoryItem, category, item }); var queryResult = await AsyncExecuter.FirstOrDefaultAsync(query); if (!CurrentTenant.Id.HasValue) { using (_dataFilter.Disable <IMultiTenant>()) { queryResult = await AsyncExecuter.FirstOrDefaultAsync(query); } } if (queryResult == null) { throw new EntityNotFoundException(typeof(CategoryItem), id); } var categoryItDto = ObjectMapper.Map <CategoryItem, CategoryItemDto>(queryResult.categoryItem); categoryItDto.CategoryName = queryResult.category.Name; categoryItDto.ItemName = queryResult.item.Name; return(categoryItDto); }
public async Task Proccess(Update update, [CallerMemberName] string botServiceName = "") { try { if (update.Type != UpdateType.Message || botServiceName == null) { return; } var botIndex = Convert.ToInt32(botServiceName.Replace("Service", string.Empty)); if (botIndex == 0) { return; } var message = update.Message; Bot bot = null; using (_dataFilter.Disable <IMultiTenant>()) bot = await _botRepository.GetAsync(b => b.ServerPathId.CompareTo(botServiceName) == 0); if (bot == null) { return; } var telegramBotClient = new TelegramBotClient(bot.Token); await DoProccess(message, telegramBotClient, bot); _logger.LogInformation("Received Message from {0}", message.Chat.Id); } catch (Exception exp) { _logger.LogError(exp.StackTrace); throw; } }
public virtual async Task <long> CountAsync(Guid userId) { using (_dataFilter.Disable <ISoftDelete>()) { return(await _repository.CountSendingAsync(userId)); } }
public async Task Should_HardDelete_Soft_Deleted_Entities() { var douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); await PersonRepository.DeleteAsync(douglas); douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldBeNull(); using (DataFilter.Disable <ISoftDelete>()) { douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldNotBeNull(); douglas.IsDeleted.ShouldBeTrue(); douglas.DeletionTime.ShouldNotBeNull(); } using (var uow = UnitOfWorkManager.Begin()) { using (DataFilter.Disable <ISoftDelete>()) { douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); } await PersonRepository.HardDeleteAsync(douglas); await uow.CompleteAsync(); } douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldBeNull(); }
public async Task <JsonResult> Test() { var optionsBuilder = new DbContextOptionsBuilder <TestDbContext>(); optionsBuilder.UseSqlServer("Server=DESKTOP-HIO90M8\\SQLEXPRESS;Database=MiniDemo;Trusted_Connection=True;MultipleActiveResultSets=true;"); using (var test = new TestDbContext(optionsBuilder.Options, _serviceProvider)) { var t = new Test() { Id = Guid.NewGuid(), Content = DateTime.Now.ToString() }; test.Tests.Add(t); await test.SaveChangesAsync(); t.Content = DateTime.Now.ToString(); test.Tests.Update(t); await test.SaveChangesAsync(); using (_dataFilter.Disable <ISoftDelete>()) { return(Json(await test.Tests.Where(m => m.Content != null).ToListAsync())); } } }
public void Should_Get_Deleted_Entities_When_Filter_Is_Disabled() { //Soft delete is enabled by default var people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); using (_dataFilter.Disable <ISoftDelete>()) { //Soft delete is disabled people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeTrue(); using (_dataFilter.Enable <ISoftDelete>()) { //Soft delete is enabled again people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); } //Soft delete is disabled (restored previous state) people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeTrue(); } //Soft delete is enabled (restored previous state) people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); }
public async Task Should_Set_Deletion_Properties(string currentUserId) { if (currentUserId != null) { CurrentUserId = Guid.Parse(currentUserId); } var douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); await PersonRepository.DeleteAsync(douglas); douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldBeNull(); using (DataFilter.Disable <ISoftDelete>()) { douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldNotBeNull(); douglas.DeletionTime.ShouldNotBeNull(); douglas.DeletionTime.Value.ShouldBeLessThanOrEqualTo(Clock.Now); douglas.DeleterId.ShouldBe(CurrentUserId); } }
public virtual async Task HandleAsync(WeChatPayHandlerContext context) { var dict = context.WeChatRequestXmlData.SelectSingleNode("xml").ToDictionary() ?? throw new NullReferenceException(); if (dict.GetOrDefault("return_code") != "SUCCESS" || dict.GetOrDefault("device_info") != PaymentServiceWeChatPayConsts.DeviceInfo) { return; } using var disabledDataFilter = _dataFilter.Disable <IMultiTenant>(); var paymentId = Guid.Parse(dict.GetOrDefault("out_trade_no") ?? throw new XmlDocumentMissingRequiredElementException("out_trade_no")); var payment = await _paymentRepository.GetAsync(paymentId); payment.SetExternalTradingCode(dict.GetOrDefault("transaction_id") ?? throw new XmlDocumentMissingRequiredElementException("transaction_id")); await _paymentRepository.UpdateAsync(payment, true); await RecordPaymentResultAsync(dict, payment.Id); if (dict.GetOrDefault("result_code") == "SUCCESS") { await _paymentManager.CompletePaymentAsync(payment); } else { await _paymentManager.StartCancelAsync(payment); } }
public async Task <long> GetItemCountAsync(Guid?tenantId) { if (tenantId.HasValue) { using (CurrentTenant.Change(tenantId)) { return(await GetCountAsync()); } } else { using (_dataFilter.Disable <IMultiTenant>()) { return(await GetCountAsync()); } } }
public async Task <List <Book> > GetAllBooksIncludingDeletedAsync() { //Temporary disable the ISoftDelete filter using (_dataFilter.Disable <ISoftDelete>()) { return(await _bookRepository.GetListAsync()); } }
public async Task Should_Cancel_Deletion_For_Soft_Delete_Entities() { var douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); await PersonRepository.DeleteAsync(douglas); douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldBeNull(); using (DataFilter.Disable <ISoftDelete>()) { douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldNotBeNull(); douglas.IsDeleted.ShouldBeTrue(); douglas.DeletionTime.ShouldNotBeNull(); } }
public virtual async Task <PrivateMessageDto> GetAsync(Guid id) { using (_dataFilter.Disable <ISoftDelete>()) { var message = await _privateMessageRepository.GetAsync(id); await AuthorizationService.CheckAsync(message, PrivateMessagingPermissions.PrivateMessages.Default); return(await MapToDtoAndLoadMoreInfosAsync(message)); } }
public async Task Should_HardDelete_Entities() { var douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); await PersonRepository.HardDeleteAsync(douglas); using (DataFilter.Disable <ISoftDelete>()) { douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); douglas.ShouldBeNull(); } }
public virtual async Task CheckActiveAsync(string appId) { using (_dataFilter.Disable <IActivation>()) { var routeGroup = await _routeGroupRepository.GetByAppIdAsync(appId); if (!routeGroup.IsActive) { throw new UserFriendlyException($"查询的路由应用:{routeGroup.AppName} 未启用!"); } } }
protected virtual async Task <TenantConfigurationCacheItem> GetCacheItemByIdAsync(Guid id) { var cacheKey = TenantConfigurationCacheItem.CalculateCacheKey(id.ToString()); Logger.LogDebug($"TenantStore.GetCacheItemByIdAsync: {cacheKey}"); var cacheItem = await _cache.GetAsync(cacheKey); if (cacheItem != null) { Logger.LogDebug($"Found in the cache: {cacheKey}"); return(cacheItem); } Logger.LogDebug($"Not found in the cache, getting from the repository: {cacheKey}"); // 禁用租户过滤器 using (_dataFilter.Disable <IMultiTenant>()) { var tenant = await _tenantRepository.FindAsync(id, true); if (tenant == null) { Logger.LogWarning($"Can not found tenant by id: {id}"); throw new AbpException($"Can not found tenant by id: {id}"); } var connectionStrings = new ConnectionStrings(); foreach (var tenantConnectionString in tenant.ConnectionStrings) { connectionStrings[tenantConnectionString.Name] = tenantConnectionString.Value; } cacheItem = new TenantConfigurationCacheItem(tenant.Id, tenant.Name, connectionStrings); Logger.LogDebug($"Setting the cache item: {cacheKey}"); await _cache.SetAsync(cacheKey, cacheItem); Logger.LogDebug($"Finished setting the cache item: {cacheKey}"); return(cacheItem); } }
public virtual async Task HandleAsync(WeChatPayHandlerContext context) { var dict = context.WeChatRequestXmlData.SelectSingleNode("xml").ToDictionary() ?? throw new NullReferenceException(); if (dict.GetOrDefault("return_code") != "SUCCESS") { return; } using var disabledDataFilter = _dataFilter.Disable <IMultiTenant>(); var record = await _refundRecordRepository.FindAsync(x => x.Id == Guid.Parse(dict.GetOrDefault("out_refund_no"))); if (record == null) { return; } var payment = await _paymentRepository.FindAsync(record.PaymentId); var refund = await _refundRepository.FindByPaymentIdAsync(record.PaymentId); if (payment == null || refund == null) { context.IsSuccess = false; return; } record.SetInformationInNotify( refundStatus: dict.GetOrDefault("refund_status"), successTime: dict.GetOrDefault("success_time"), refundRecvAccout: dict.GetOrDefault("refund_recv_accout"), refundAccount: dict.GetOrDefault("refund_account"), refundRequestSource: dict.GetOrDefault("refund_request_source"), settlementRefundFee: Convert.ToInt32(dict.GetOrDefault("settlement_refund_fee"))); await _refundRecordRepository.UpdateAsync(record, true); if (dict.GetOrDefault("refund_status") == "SUCCESS") { await _paymentManager.CompleteRefundAsync(payment, refund); } else { await _paymentManager.RollbackRefundAsync(payment, refund); } context.IsSuccess = true; }
public void Should_Get_All_People_When_MultiTenant_Filter_Is_Disabled() { List <Person> people; using (_multiTenantFilter.Disable()) { //Filter disabled manually people = _personRepository.ToList(); people.Count.ShouldBe(3); } //Filter re-enabled automatically people = _personRepository.ToList(); people.Count.ShouldBe(1); }
public async Task Should_Get_All_People_When_MultiTenant_Filter_Is_Disabled() { await WithUnitOfWorkAsync(() => { List <Person> people; using (_multiTenantFilter.Disable()) { //Filter disabled manually people = _personRepository.ToList(); people.Count.ShouldBe(3); } //Filter re-enabled automatically people = _personRepository.ToList(); people.Count.ShouldBe(1); return(Task.CompletedTask); }).ConfigureAwait(false); }
public virtual async Task HandleEventAsync(EntityUpdatedEto <TenantEto> eventData) { // 禁用租户过滤器 using (_dataFilter.Disable <IMultiTenant>()) { var tenant = await _tenantRepository.FindAsync(eventData.Entity.Id, true); if (tenant == null) { return; } var connectionStrings = new ConnectionStrings(); foreach (var tenantConnectionString in tenant.ConnectionStrings) { connectionStrings[tenantConnectionString.Name] = tenantConnectionString.Value; } var cacheItem = new TenantConfigurationCacheItem(tenant.Id, tenant.Name, connectionStrings); var cacheKey = TenantConfigurationCacheItem.CalculateCacheKey(eventData.Entity.Id.ToString()); await _cache.SetAsync(cacheKey, cacheItem); } }
/// <summary> /// (数据库内容本地化demo) 获取所有语言副本 /// </summary> /// <returns></returns> public async Task <ListResultDto <ProductWithAllEntriesDto> > GetListWithAllEntriesAsync() { using (_dataFilter.Disable <IHasLocalizableContent>()) { var entities = await AsyncExecuter.ToListAsync(_ProductRepository.WithDetails(s => s.Entries)); return(new ListResultDto <ProductWithAllEntriesDto> { Items = entities.Select(e => new ProductWithAllEntriesDto { ProductCode = e.ProductCode, Entries = e.Entries.Select(ee => new ProductLocalizableEntryDto { CultureName = ee.CultureName, Description = ee.Description, Name = ee.Name, Title = ee.Title }).ToList() }).ToList() }); } }
public async Task Should_Get_Deleted_Entities_When_Filter_Is_Disabled() { await WithUnitOfWorkAsync(() => { //Soft delete is enabled by default var people = PersonRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); using (DataFilter.Disable <ISoftDelete>()) { //Soft delete is disabled people = PersonRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeTrue(); using (DataFilter.Enable <ISoftDelete>()) { //Soft delete is enabled again people = PersonRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); } //Soft delete is disabled (restored previous state) people = PersonRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeTrue(); } //Soft delete is enabled (restored previous state) people = PersonRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); return(Task.CompletedTask); }).ConfigureAwait(false); }
public Task <string> NextReferenceNo(int year) { using (_softDeleteFilter.Disable()) { string last = Repository.Where(c => c.InvoiceDate.Year == year) .OrderBy(c => c.ReferenceNo).LastOrDefault()?.ReferenceNo; int count = 1; string RefNo = string.Format("{0:00000}/CIGO/{1}", count, year); if (last != null) { int.TryParse(last.Split("/")[0], out count); } if (Repository.Count() != 0) { while (Repository.Any(c => c.ReferenceNo == RefNo)) { count += 1; RefNo = string.Format("{0:00000}/CIGO/{1}", count, year); } } return(Task.FromResult(RefNo)); } }
private async Task <ItemDto> GetAsyncFromDatabase(Guid id) { var items = await _itemRepository.GetIQueryableItems(); var query = from item in items join unit in _unitRepository on item.UnitId equals unit.Id where item.Id == id select new { Item = item, Unit = unit }; var categoriesItems = await _categoryItemsRepository.GetQueryableAsync(); var query1 = from categoryItem in categoriesItems join category in _categoryRepository on categoryItem.CategoryId equals category.Id join item in _itemRepository on categoryItem.ItemId equals item.Id where categoryItem.ItemId == id select new CategoryItemDto { Id = categoryItem.Id, ItemId = item.Id, ItemName = item.Name, CategoryId = category.Id, CategoryName = category.Name, CreationTime = categoryItem.CreationTime, CreatorId = categoryItem.CreatorId }; var itemDto = new ItemDto(); if (!CurrentTenant.Id.HasValue) { using (_dataFilter.Disable <IMultiTenant>()) { var queryResult = await AsyncExecuter.FirstOrDefaultAsync(query); if (queryResult == null) { throw new EntityNotFoundException(typeof(Item), id); } itemDto = ObjectMapper.Map <Item, ItemDto>(queryResult.Item); itemDto.UnitName = queryResult.Unit.Name; var queryResult1 = await AsyncExecuter.ToListAsync(query1); itemDto.ItemCategories = queryResult1; } } else { var queryResult = await AsyncExecuter.FirstOrDefaultAsync(query); if (queryResult == null) { throw new EntityNotFoundException(typeof(Item), id); } itemDto = ObjectMapper.Map <Item, ItemDto>(queryResult.Item); itemDto.UnitName = queryResult.Unit.Name; var queryResult1 = await AsyncExecuter.ToListAsync(query1); itemDto.ItemCategories = queryResult1; } return(itemDto); }
public async Task FindByNameAsync_Test() { var tenantId = new Guid("446a5211-3d72-4339-9adc-845151f8ada0"); var container = new FileStoringContainer( _guidGenerator.Create(), tenantId, true, "Minio", "default", "test-container", true); container.Items.Add(new FileStoringContainerItem( _guidGenerator.Create(), "Minio.BucketName", "bucket1", container.Id)); container.Items.Add(new FileStoringContainerItem( _guidGenerator.Create(), "Minio.EndPoint", "http://127.0.0.1:9094", container.Id)); container.Items.Add(new FileStoringContainerItem( _guidGenerator.Create(), "Minio.AccessKey", "minioadmin", container.Id)); container.Items.Add(new FileStoringContainerItem( _guidGenerator.Create(), "Minio.SecretKey", "minioadmin", container.Id)); container.Items.Add(new FileStoringContainerItem( _guidGenerator.Create(), "Minio.WithSSL", "true", container.Id)); container.Items.Add(new FileStoringContainerItem( _guidGenerator.Create(), "Minio.CreateBucketIfNotExists", "true", container.Id)); using (_currentTenant.Change(tenantId)) { await _fileStoringContainerRepository.InsertAsync(container, true); } using (_currentTenant.Change(null)) { var queryContainer1 = await _fileStoringContainerRepository.FindAsync("default"); Assert.Null(queryContainer1); } using (_currentTenant.Change(tenantId)) { var queryContainer1 = await _fileStoringContainerRepository.FindAsync("default"); Assert.Equal(container.Id, queryContainer1.Id); Assert.Equal(container.Name, queryContainer1.Name); Assert.Equal(container.Items.Count, queryContainer1.Items.Count); var queryContainer2 = await _fileStoringContainerRepository.GetAsync(container.Id, includeDetails : true); Assert.NotNull(queryContainer2); Assert.Equal(container.Items.Count, queryContainer2.Items.Count); } using (_dataFilter.Disable()) { var queryContainer1 = await _fileStoringContainerRepository.FindAsync("default"); Assert.Equal(container.Id, queryContainer1.Id); Assert.Equal(container.Name, queryContainer1.Name); Assert.Equal(container.Items.Count, queryContainer1.Items.Count); } }
protected virtual async Task <LoginResultInfoModel> GetLoginResultAsync(LoginInput input) { var tenantId = CurrentTenant.Id; var tenantChanged = false; MiniProgram miniProgram; if (input.LookupUseRecentlyTenant) { using (_dataFilter.Disable <IMultiTenant>()) { miniProgram = await _miniProgramRepository.FirstOrDefaultAsync(x => x.AppId == input.AppId); } } else { miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); } var code2SessionResponse = await _loginService.Code2SessionAsync(miniProgram.AppId, miniProgram.AppSecret, input.Code); _signatureChecker.Check(input.RawData, code2SessionResponse.SessionKey, input.Signature); var openId = code2SessionResponse.OpenId; var unionId = code2SessionResponse.UnionId; if (input.LookupUseRecentlyTenant) { using (_dataFilter.Disable <IMultiTenant>()) { tenantId = await _miniProgramUserRepository.FindRecentlyTenantIdAsync(input.AppId, openId, true); } if (tenantId != CurrentTenant.Id) { tenantChanged = true; } } using var tenantChange = CurrentTenant.Change(tenantId); if (tenantChanged) { miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); } // 如果 auth.code2Session 没有返回用户的 UnionId if (unionId.IsNullOrWhiteSpace()) { if (!input.EncryptedData.IsNullOrWhiteSpace() && !input.Iv.IsNullOrWhiteSpace()) { // 方法1:通过 EncryptedData 和 Iv 解密获得用户的 UnionId var decryptedData = _jsonSerializer.Deserialize <Dictionary <string, object> >( AesHelper.AesDecrypt(input.EncryptedData, input.Iv, code2SessionResponse.SessionKey)); unionId = decryptedData.GetOrDefault("unionId") as string; } else { // 方法2:尝试通过 OpenId 在 MiniProgramUser 实体中查找用户的 UnionId // Todo: should use IMiniProgramUserStore unionId = await _miniProgramUserRepository.FindUnionIdByOpenIdAsync(miniProgram.Id, openId); } } string loginProvider; string providerKey; if (unionId.IsNullOrWhiteSpace()) { loginProvider = await _miniProgramLoginProviderProvider.GetAppLoginProviderAsync(miniProgram); providerKey = openId; } else { loginProvider = await _miniProgramLoginProviderProvider.GetOpenLoginProviderAsync(miniProgram); providerKey = unionId; } return(new LoginResultInfoModel { MiniProgram = miniProgram, LoginProvider = loginProvider, ProviderKey = providerKey, UnionId = unionId, Code2SessionResponse = code2SessionResponse }); }
public async Task CreateAsync_UpdateAsync_Test() { var tenantId = new Guid("42645233-3d72-4339-9adc-845321f8ada3"); var tenantId2 = new Guid("d0ad04d5-2839-2c2a-1078-6b253678dceb"); Guid id; using (_currentTenant.Change(tenantId)) { id = await _containerAppService.CreateAsync(new CreateContainerDto() { Provider = MinioFileProviderConfigurationNames.ProviderName, Name = "default1", IsMultiTenant = true, HttpAccess = true, Title = "test-container1", Items = new List <CreateContainerItemDto>() { new CreateContainerItemDto(MinioFileProviderConfigurationNames.BucketName, "bucket1"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.EndPoint, "http://192.168.0.4:9000"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.AccessKey, "minioadmin"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.SecretKey, "minioadmin"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.WithSSL, "false"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.CreateBucketIfNotExists, "false") } }); } Guid id2; using (_currentTenant.Change(tenantId2)) { id2 = await _containerAppService.CreateAsync(new CreateContainerDto() { Provider = MinioFileProviderConfigurationNames.ProviderName, Name = "default2", IsMultiTenant = true, HttpAccess = true, Title = "test-container2", Items = new List <CreateContainerItemDto>() { new CreateContainerItemDto(MinioFileProviderConfigurationNames.BucketName, "bucket2"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.EndPoint, "http://192.168.0.4:9000"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.AccessKey, "minioadmin"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.SecretKey, "minioadmin"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.WithSSL, "false"), new CreateContainerItemDto(MinioFileProviderConfigurationNames.CreateBucketIfNotExists, "false") } }); } using (_dataFilter.Disable()) { var pagedContainers = await _containerAppService.GetPagedListAsync(new FileStoringContainerPagedRequestDto() { SkipCount = 0, MaxResultCount = 10 }); Assert.Equal(2, pagedContainers.TotalCount); } using (_currentTenant.Change(tenantId)) { var pagedContainers = await _containerAppService.GetPagedListAsync(new FileStoringContainerPagedRequestDto() { SkipCount = 0, MaxResultCount = 10 }); Assert.Equal(1, pagedContainers.TotalCount); var container2 = await _containerAppService.GetAsync(id, true); Assert.Equal("default1", container2.Name); Assert.Equal("Minio", container2.Provider); Assert.Equal(tenantId, container2.TenantId); Assert.True(container2.IsMultiTenant); Assert.True(container2.HttpAccess); Assert.Equal("test-container1", container2.Title); Assert.Equal(6, container2.Items.Count); await _containerAppService.UpdateAsync(id, new UpdateContainerDto() { Provider = "FileSystem", Name = "default2", IsMultiTenant = false, HttpAccess = false, Title = "test-container2", Items = new List <UpdateContainerItemDto>() { new UpdateContainerItemDto(FileSystemFileProviderConfigurationNames.BasePath, "D:\\files"), new UpdateContainerItemDto(FileSystemFileProviderConfigurationNames.AppendContainerNameToBasePath, "true"), new UpdateContainerItemDto(FileSystemFileProviderConfigurationNames.HttpServer, "") } }); var container3 = await _containerAppService.GetAsync(id, true); Assert.Equal("default2", container3.Name); Assert.Equal("FileSystem", container3.Provider); Assert.Equal(tenantId, container3.TenantId); Assert.False(container3.IsMultiTenant); Assert.False(container3.HttpAccess); Assert.Equal("test-container2", container3.Title); Assert.Equal(3, container3.Items.Count); } }
protected virtual async Task <LoginResultInfoModel> GetLoginResultAsync(LoginInput input) { var tenantId = CurrentTenant.Id; var tenantChanged = false; MiniProgram miniProgram; if (input.LookupUseRecentlyTenant) { using (_dataFilter.Disable <IMultiTenant>()) { miniProgram = await _miniProgramRepository.FirstOrDefaultAsync(x => x.AppId == input.AppId); } } else { miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); } var code2SessionResponse = await _loginService.Code2SessionAsync(miniProgram.AppId, miniProgram.AppSecret, input.Code); var openId = code2SessionResponse.OpenId; var unionId = code2SessionResponse.UnionId; if (input.LookupUseRecentlyTenant) { using (_dataFilter.Disable <IMultiTenant>()) { tenantId = await _miniProgramUserRepository.FindRecentlyTenantIdAsync(input.AppId, openId, true); } if (tenantId != CurrentTenant.Id) { tenantChanged = true; } } using var tenantChange = CurrentTenant.Change(tenantId); if (tenantChanged) { miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); } string loginProvider; string providerKey; if (!unionId.IsNullOrWhiteSpace()) { loginProvider = await _miniProgramLoginProviderProvider.GetOpenLoginProviderAsync(miniProgram); providerKey = unionId; } else { loginProvider = await _miniProgramLoginProviderProvider.GetAppLoginProviderAsync(miniProgram); providerKey = openId; } return(new LoginResultInfoModel { MiniProgram = miniProgram, LoginProvider = loginProvider, ProviderKey = providerKey, UnionId = unionId, Code2SessionResponse = code2SessionResponse }); }
private async Task CreateBlogs() { long existingBlogCount = 0; using (_dataFilter.Disable <ISoftDelete>()) { existingBlogCount = await _blogRepository.GetCountAsync(); } //List<Guid> // blogIds = new() // { // new Guid("C8A39C37-8F2A-4D9B-AC18-959C8F9B95FC"), // new Guid("E5FB2114-4FE6-46F1-A415-4B1312B50A31"), // }, // postIds = new() // { // new Guid("794BA2C5-8A6B-478D-808B-3D5CA1D722B6"), // new Guid("7B81423B-AF5F-4363-A82C-538C1FF1650D"), // new Guid("468350CB-FB03-4891-8A2A-CC0A2EF0D5A9"), // new Guid("5D1EE3A6-4A53-4DA6-940B-C62040C7D89F"), // }; //if (existingBlogCount >= blogIds.Count) return; //var blogsToInsert = new List<Blog>(); //for (int i = 0; i < blogIds.Count; i++) //{ // if (existingBlogs.Any(x => x.Id == blogIds[i])) continue; // blogsToInsert.Add(new(blogIds[i], $"Blog {i + 1}")); // blogsToInsert[^1].Posts = new List<Post> // { // new(postIds[i * 2], $"{blogsToInsert[^1].Name} - Post {i * 2 + 1}", blogsToInsert[^1]), // new(postIds[i * 2 + 1], $"{blogsToInsert[^1].Name} - Post {i * 2 + 2}", blogsToInsert[^1]), // }; //} //await _blogRepository.InsertManyAsync(blogsToInsert); List <Blog> blogsToCreate = new() { new(new Guid("C8A39C37-8F2A-4D9B-AC18-959C8F9B95FC"), "Blog 1"), new(new Guid("E5FB2114-4FE6-46F1-A415-4B1312B50A31"), "[DELETED] Blog 2") { IsDeleted = true, DeletionTime = DateTime.Now } }; if (existingBlogCount >= blogsToCreate.Count) { return; } // Blog 1 posts blogsToCreate[0].Posts.Add( new(new Guid("794BA2C5-8A6B-478D-808B-3D5CA1D722B6"), $"[DELETED] Post 1 ({blogsToCreate[0].Name})", blogsToCreate[0]) { IsDeleted = true, DeletionTime = DateTime.Now }
public virtual async Task <string> LoginAsync(LoginInput input) { var miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); var code2SessionResponse = await _loginService.Code2SessionAsync(miniProgram.AppId, miniProgram.AppSecret, input.Code); _signatureChecker.Check(input.RawData, code2SessionResponse.SessionKey, input.Signature); var openId = code2SessionResponse.OpenId; var unionId = code2SessionResponse.UnionId; if (input.LookupUseRecentlyTenant) { Guid?tenantId; using (_dataFilter.Disable <IMultiTenant>()) { tenantId = await _miniProgramUserRepository.FindRecentlyTenantIdAsync(miniProgram.Id, openId); } using var tenantChange = CurrentTenant.Change(tenantId); } string loginProvider; string providerKey; // 如果 auth.code2Session 没有返回用户的 UnionId if (unionId.IsNullOrWhiteSpace()) { if (!input.EncryptedData.IsNullOrWhiteSpace() && !input.Iv.IsNullOrWhiteSpace()) { // 方法1:通过 EncryptedData 和 Iv 解密获得用户的 UnionId var decryptedData = _jsonSerializer.Deserialize <Dictionary <string, object> >( AesHelper.AesDecrypt(input.EncryptedData, input.Iv, code2SessionResponse.SessionKey)); unionId = decryptedData.GetOrDefault("unionId") as string; } else { // 方法2:尝试通过 OpenId 在 MiniProgramUser 实体中查找用户的 UnionId // Todo: should use IMiniProgramUserStore unionId = await _miniProgramUserRepository.FindUnionIdByOpenIdAsync(miniProgram.Id, openId); } } if (unionId.IsNullOrWhiteSpace()) { loginProvider = await _miniProgramLoginProviderProvider.GetAppLoginProviderAsync(miniProgram); providerKey = openId; } else { loginProvider = await _miniProgramLoginProviderProvider.GetOpenLoginProviderAsync(miniProgram); providerKey = unionId; } var identityUser = await _identityUserManager.FindByLoginAsync(loginProvider, providerKey) ?? await _miniProgramLoginNewUserCreator.CreateAsync(input.UserInfo, loginProvider, providerKey); await UpdateMiniProgramUserAsync(identityUser, miniProgram, unionId, openId, code2SessionResponse.SessionKey); await UpdateUserInfoAsync(identityUser, input.UserInfo); return((await RequestIds4LoginAsync(input.AppId, unionId, openId))?.Raw); }