public virtual async Task <TenantDto> CreateAsync(TenantCreateDto input) { var tenant = await TenantManager.CreateAsync(input.Name); input.MapExtraPropertiesTo(tenant); await TenantRepository.InsertAsync(tenant); await CurrentUnitOfWork.SaveChangesAsync(); await DistributedEventBus.PublishAsync( new TenantCreatedEto { Id = tenant.Id, Name = tenant.Name, Properties = { { "AdminEmail", input.AdminEmailAddress }, { "AdminPassword", input.AdminPassword } } }); using (CurrentTenant.Change(tenant.Id, tenant.Name)) { //TODO: Handle database creation? // TODO: Seeder might be triggered via event handler. await DataSeeder.SeedAsync( new DataSeedContext(tenant.Id) .WithProperty("AdminEmail", input.AdminEmailAddress) .WithProperty("AdminPassword", input.AdminPassword) ); } return(ObjectMapper.Map <Tenant, TenantDto>(tenant)); }
public virtual async Task SetAsync(string permissionName, string providerName, string providerScope, string providerKey) { var permission = PermissionDefinitionManager.Get(permissionName); if (permission.Providers.Any() && !permission.Providers.Contains(providerName)) { throw new RocketException($"The permission named '{permission.Name}' has not compatible with the provider named '{providerName}'"); } if (!permission.MultiTenancySide.HasFlag(CurrentTenant.GetMultiTenancySide())) { throw new RocketException($"The permission named '{permission.Name}' has multitenancy side '{permission.MultiTenancySide}' which is not compatible with the current multitenancy side '{CurrentTenant.GetMultiTenancySide()}'"); } var currentGrantInfo = await GetInternalAsync(permission, providerName, providerKey); if (currentGrantInfo.Scope == providerScope) { return; } var provider = Providers.FirstOrDefault(m => m.Name == providerName); if (provider == null) { throw new RocketException("Unknown permission management provider: " + providerName); } await provider.SetAsync(permissionName, providerKey, providerScope); }
public async Task <int> GetGroupUsersCountAsync(Guid?tenantId, long groupId, string filter = "") { using (CurrentTenant.Change(tenantId)) { return(await UserChatGroupRepository.GetGroupUsersCountAsync(groupId, filter)); } }
protected virtual async Task <TenantCacheItem> GetCacheItemAsync(Guid?id, string name) { var cacheKey = CalculateCacheKey(id, name); var cacheItem = await Cache.GetAsync(cacheKey, considerUow : true); if (cacheItem != null) { return(cacheItem); } if (id.HasValue) { using (CurrentTenant.Change(null)) //TODO: No need this if we can implement to define host side (or tenant-independent) entities! { var tenant = await TenantRepository.FindAsync(id.Value); return(await SetCacheAsync(cacheKey, tenant)); } } if (!name.IsNullOrWhiteSpace()) { using (CurrentTenant.Change(null)) //TODO: No need this if we can implement to define host side (or tenant-independent) entities! { var tenant = await TenantRepository.FindByNameAsync(name); return(await SetCacheAsync(cacheKey, tenant)); } } throw new AbpException("Both id and name can't be invalid."); }
protected override Task RevokeAsync(string name, string providerKey) { using (CurrentTenant.Change(null)) { return(base.RevokeAsync(name, providerKey)); } }
public virtual async Task SeedAsync(DataSeedContext context) { using (CurrentTenant.Change(context.TenantId)) { var data = await SeedDefaultDataDictionaryAsync(context.TenantId); // 预置 var layout = await SeedDefaultLayoutAsync(data); // 首页 await SeedHomeMenuAsync(layout, data); // 管理菜单预置菜单数据 await SeedAdminMenuAsync(layout, data); // saas菜单数据 await SeedSaasMenuAsync(layout, data); // 身份资源菜单数据 await SeedIdentityServerMenuAsync(layout, data); // 审计日志菜单数据 await SeedAuditingMenuAsync(layout, data); // 布局容器预置菜单数据 await SeedContainerMenuAsync(layout, data); // 网关管理菜单数据 await SeedApiGatewayMenuAsync(layout, data); // Oss对象管理菜单数据 await SeedOssManagementMenuAsync(layout, data); } }
public override Task SetAsync(string name, string providerKey, bool isGranted) { using (CurrentTenant.Change(null)) { return(base.SetAsync(name, providerKey, isGranted)); } }
protected override async Task <PermissionWithGrantedProviders> GetInternalAsync(PermissionDefinition permission, string providerName, string providerKey) { var result = new PermissionWithGrantedProviders(permission.Name, false); if (!permission.IsEnabled) { return(result); } if (!await PermissionStateManager.IsEnabledAsync(permission)) { return(result); } if (!permission.MultiTenancySide.HasFlag(CurrentTenant.GetMultiTenancySide())) { return(result); } if (permission.Providers.Any() && !permission.Providers.Contains(providerName)) { return(result); } // 这么做的坏处就是没法给特定的Provider设定是否授权字段 // result.Providers 会出现假数据 UserPermissionProvider未授权, 而所属的 result.IsGranted = await IsGrantedAsync(permission.Name, providerName, providerKey); return(result); }
public override Task <PermissionValueProviderGrantInfo> CheckAsync(string name, string providerName, string providerKey) { using (CurrentTenant.Change(null)) { return(base.CheckAsync(name, providerName, providerKey)); } }
public async Task <List <UserGroup> > GetGroupUsersAsync(Guid?tenantId, long groupId, string filter = "", string sorting = "UserId", int skipCount = 1, int maxResultCount = 10) { using (CurrentTenant.Change(tenantId)) { return(await UserChatGroupRepository.GetGroupUsersAsync(groupId, filter, sorting, skipCount, maxResultCount)); } }
public async Task HandleEventAsync(EntityDeletedEto <TenantEto> eventData) { using var unitOfWork = UnitOfWorkManager.Begin(); // 订阅租户删除事件,删除管理员角色所有权限 // TODO: 租户貌似不存在了,删除应该会失败 // 有缓存存在的话,可以获取到租户连接字符串 using (CurrentTenant.Change(eventData.Entity.Id)) { // var grantPermissions = await PermissionGrantRepository.GetListAsync("R", "admin"); // EfCore MySql 批量删除还是一条一条的语句? // PermissionGrantRepository.GetDbSet().RemoveRange(grantPermissions); var permissionEntityType = PermissionGrantRepository.GetDbContext().Model.FindEntityType(typeof(PermissionGrant)); var permissionTableName = permissionEntityType.GetTableName(); var batchRmovePermissionSql = string.Empty; if (PermissionGrantRepository.GetDbContext().Database.IsMySql()) { batchRmovePermissionSql = BuildMySqlBatchDeleteScript(permissionTableName, eventData.Entity.Id); } else { batchRmovePermissionSql = BuildSqlServerBatchDeleteScript(permissionTableName, eventData.Entity.Id); } await PermissionGrantRepository.GetDbContext().Database .ExecuteSqlRawAsync(batchRmovePermissionSql); await unitOfWork.SaveChangesAsync(); } }
/// <summary> /// 获取当前租户产品总数 /// </summary> /// <param name="tenantId">指定租户</param> /// <returns></returns> public async Task <long> GetProductCountAsync(Guid?tenantId) { // 使用using 可以在代码块结束后恢复原本租户值 using (CurrentTenant.Change(tenantId)) { return(await ProductRepository.GetCountAsync()); } }
public async override Task <IActionResult> OnGetAsync() { LoginInput = new LoginInputModel(); var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl); if (context != null) { ShowCancelButton = true; LoginInput.UserNameOrEmailAddress = context.LoginHint; //TODO: Reference AspNetCore MultiTenancy module and use options to get the tenant key! var tenant = context.Parameters[TenantResolverConsts.DefaultTenantKey]; if (!string.IsNullOrEmpty(tenant)) { CurrentTenant.Change(Guid.Parse(tenant)); Response.Cookies.Append(TenantResolverConsts.DefaultTenantKey, tenant); } } if (context?.IdP != null) { LoginInput.UserNameOrEmailAddress = context.LoginHint; ExternalProviders = new[] { new ExternalProviderModel { AuthenticationScheme = context.IdP } }; return(Page()); } var providers = await GetExternalProviders(); ExternalProviders = providers.ToList(); EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin); if (context?.Client?.ClientId != null) { var client = await ClientStore.FindEnabledClientByIdAsync(context?.Client?.ClientId); if (client != null) { EnableLocalLogin = client.EnableLocalLogin; if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) { providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList(); } } } if (IsExternalLoginOnly) { return(await base.OnPostExternalLogin(providers.First().AuthenticationScheme)); } return(Page()); }
public override async Task <IActionResult> OnPostAsync(string action) { var user = await FindUserAsync(LoginInput.UserNameOrEmailAddress); using (CurrentTenant.Change(user?.TenantId)) { return(await base.OnPostAsync(action)); } }
public override async Task <IActionResult> OnGetExternalLoginCallbackAsync(string returnUrl = "", string returnUrlHash = "", string remoteError = null) { var user = await FindUserAsync(LoginInput.UserNameOrEmailAddress); using (CurrentTenant.Change(user?.TenantId)) { return(await base.OnGetExternalLoginCallbackAsync(returnUrl, returnUrlHash, remoteError)); } }
public async Task <IEnumerable <Group> > GetUserGroupsAsync(Guid?tenantId, Guid userId) { using (CurrentTenant.Change(tenantId)) { var groups = await UserChatGroupRepository.GetUserGroupsAsync(userId); return(groups); } }
public async Task <IEnumerable <UserGroup> > GetGroupUsersAsync(Guid?tenantId, long groupId) { using (CurrentTenant.Change(tenantId)) { var userGroups = await UserChatGroupRepository.GetGroupUsersAsync(groupId); return(userGroups); } }
public async Task <GroupUserCard> GetUserGroupCardAsync(Guid?tenantId, long groupId, Guid userId) { using (CurrentTenant.Change(tenantId)) { var groupUserCard = await UserChatGroupRepository.GetGroupUserCardAsync(groupId, userId); return(groupUserCard); } }
public virtual async Task <PermissionGrantResult> GetResultAsync( ClaimsPrincipal claimsPrincipal, string name) { Check.NotNull(name, nameof(name)); var permission = PermissionDefinitionManager.Get(name); if (!permission.IsEnabled) { return(PermissionGrantResult.Prohibited); } var multiTenancySide = claimsPrincipal?.GetMultiTenancySide() ?? CurrentTenant.GetMultiTenancySide(); if (!permission.MultiTenancySide.HasFlag(multiTenancySide)) { return(PermissionGrantResult.Prohibited); } var context = new PermissionValueCheckContext(permission, claimsPrincipal); // 可选权限策略:一、获取最大权限;二、以用户权限为主 // 当前权限策略:用户权限为主(用户权限 > 角色权限 > 客户端权限) // 对权限提供程序排序,用户权限放到第一位 var providers = PermissionValueProviderManager.ValueProviders.OrderByDescending(m => m.Name).ToList(); var permissionGrantResult = PermissionGrantResult.Undefined; foreach (var provider in providers) { if (context.Permission.Providers.Any() && !context.Permission.Providers.Contains(provider.Name)) { continue; } var result = await provider.GetResultAsync(context); // 用户权限为主(用户权限 > 角色权限 > 客户端权限) if (Options.PermissionPolicy == PermissionPolicy.User) { permissionGrantResult = result; break; } else { // 最大权限为主 if (result?.GrantType == PermissionGrantType.Granted && result?.ScopeType > permissionGrantResult.ScopeType) { permissionGrantResult = result; } } } return(permissionGrantResult); }
public async Task <List <NotificationInfo> > GetUserNotificationsAsync(Guid?tenantId, Guid userId, NotificationReadState readState = NotificationReadState.UnRead, int maxResultCount = 10) { using (CurrentTenant.Change(tenantId)) { var notifications = await UserNotificationRepository.GetNotificationsAsync(userId, readState, maxResultCount); return(_objectMapper.Map <List <Notification>, List <NotificationInfo> >(notifications)); } }
public async Task <List <NotificationSubscriptionInfo> > GetSubscriptionsAsync(Guid?tenantId, string notificationName) { using (CurrentTenant.Change(tenantId)) { var userSubscriptions = await UserSubscribeRepository.GetSubscribesAsync(notificationName); return(_objectMapper.Map <List <UserSubscribe>, List <NotificationSubscriptionInfo> >(userSubscriptions)); } }
public async Task <NotificationInfo> GetNotificationOrNullAsync(Guid?tenantId, long notificationId) { using (CurrentTenant.Change(tenantId)) { var notification = await NotificationRepository.GetByIdAsync(notificationId); return(_objectMapper.Map <Notification, NotificationInfo>(notification)); } }
protected virtual async Task <PermissionWithGrantedProviders> GetInternalAsync(PermissionDefinition permission, string providerName, string providerKey) { var result = new PermissionWithGrantedProviders(permission.Name, false); if (!permission.MultiTenancySide.HasFlag(CurrentTenant.GetMultiTenancySide())) { return(result); } if (permission.Providers.Any() && !permission.Providers.Contains(providerName)) { return(result); } // 可选权限策略:一、获取最大权限;二、以用户权限为主 // 当前权限策略:以用户权限为主(用户权限 > 角色权限 > 客户端权限) // 对权限提供程序排序,用户权限放到最后赋值,覆盖前者权限 foreach (var provider in Providers) { var providerResult = await provider.CheckAsync(permission.Name, providerName, providerKey); if (providerResult.IsGranted) { result.IsGranted = true; // 以用户权限为主,将用户权限解析程序放到最后赋值,覆盖前者权限(用户权限 > 角色权限 > 客户端权限) if (PermissionOptions.PermissionPolicy == PermissionPolicy.User) { result.Scope = providerResult.ProviderScope; } else { // 以最大权限为主 var providerScope = PermissionScopeType.Prohibited; if (Enum.TryParse(providerResult.ProviderScope, out PermissionScopeType ps)) { providerScope = ps; } var resultScope = PermissionScopeType.Prohibited; if (Enum.TryParse(result.Scope, out PermissionScopeType rs)) { resultScope = rs; } if (providerScope > resultScope) { result.Scope = providerResult.ProviderScope; } } result.Providers.Add(new PermissionValueProviderInfo(provider.Name, providerResult.ProviderScope, providerResult.ProviderKey)); } } return(result); }
public async Task RunAsync() { using (CurrentTenant.Change(Guid.NewGuid())) { using (PluzIdentityClientSwitcher.Use("Internal")) { await Assert("Call SampleAppService with no auth.", async() => await _sampleAppService.GetAsync()); } } }
public async Task UserHasInMenuAsync_Test() { (await Repository.UserHasInMenuAsync(PlatformTestsConsts.User1Id, "saas")).ShouldBeTrue(); (await Repository.UserHasInMenuAsync(PlatformTestsConsts.User2Id, "admin")).ShouldBeFalse(); using (CurrentTenant.Change(PlatformTestsConsts.TenantId)) { (await Repository.UserHasInMenuAsync(PlatformTestsConsts.User2Id, "admin")).ShouldBeTrue(); } }
public async Task DeleteAllUserSubscriptionAsync(Guid?tenantId, string notificationName) { using (var unitOfWork = _unitOfWorkManager.Begin()) using (CurrentTenant.Change(tenantId)) { await UserSubscribeRepository.DeleteUserSubscriptionAsync(notificationName); await unitOfWork.SaveChangesAsync(); } }
public async Task ChangeUserNotificationReadStateAsync(Guid?tenantId, Guid userId, long notificationId, NotificationReadState readState) { using (var unitOfWork = _unitOfWorkManager.Begin()) using (CurrentTenant.Change(tenantId)) { await UserNotificationRepository.ChangeUserNotificationReadStateAsync(userId, notificationId, readState); await unitOfWork.SaveChangesAsync(); } }
protected virtual async Task TriggerHandlerAsync(IEventHandlerFactory asyncHandlerFactory, Type eventType, object eventData, List <Exception> exceptions, InboxConfig inboxConfig = null) { using (var eventHandlerWrapper = asyncHandlerFactory.GetHandler()) { try { var handlerType = eventHandlerWrapper.EventHandler.GetType(); if (inboxConfig?.HandlerSelector != null && !inboxConfig.HandlerSelector(handlerType)) { return; } using (CurrentTenant.Change(GetEventDataTenantId(eventData))) { if (ReflectionHelper.IsAssignableToGenericType(handlerType, typeof(ILocalEventHandler <>))) { var method = typeof(ILocalEventHandler <>) .MakeGenericType(eventType) .GetMethod( nameof(ILocalEventHandler <object> .HandleEventAsync), new[] { eventType } ); await((Task)method.Invoke(eventHandlerWrapper.EventHandler, new[] { eventData })); } else if (ReflectionHelper.IsAssignableToGenericType(handlerType, typeof(IDistributedEventHandler <>))) { var method = typeof(IDistributedEventHandler <>) .MakeGenericType(eventType) .GetMethod( nameof(IDistributedEventHandler <object> .HandleEventAsync), new[] { eventType } ); await((Task)method.Invoke(eventHandlerWrapper.EventHandler, new[] { eventData })); } else { throw new AbpException("The object instance is not an event handler. Object type: " + handlerType.AssemblyQualifiedName); } } } catch (TargetInvocationException ex) { exceptions.Add(ex.InnerException); } catch (Exception ex) { exceptions.Add(ex); } } }
public async Task OnGetAsync() { Input = new TenantInfoModel(); if (CurrentTenant.IsAvailable) { var tenant = await TenantStore.FindAsync(CurrentTenant.GetId()); Input.Name = tenant?.Name; } }
public async Task InsertUserNotificationAsync(NotificationInfo notification, Guid userId) { using (var unitOfWork = _unitOfWorkManager.Begin()) using (CurrentTenant.Change(notification.TenantId)) { var userNotification = new UserNotification(notification.GetId(), userId, notification.TenantId); await UserNotificationRepository.InsertAsync(userNotification); await unitOfWork.SaveChangesAsync(); } }