public async Task<List<UserNotification>> GetUserNotificationsAsync(UserIdentifier user, UserNotificationState? state = null, int skipCount = 0, int maxResultCount = int.MaxValue)
 {
     var userNotifications = await _store.GetUserNotificationsWithNotificationsAsync(user, state, skipCount, maxResultCount);
     return userNotifications
         .Select(un => un.ToUserNotification())
         .ToList();
 }
        /// <summary>
        /// Checks if given user is granted for given permission.
        /// </summary>
        /// <param name="permissionChecker">Permission checker</param>
        /// <param name="user">User</param>
        /// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param>
        /// <param name="permissionNames">Name of the permissions</param>
        public static async Task<bool> IsGrantedAsync(this IPermissionChecker permissionChecker, UserIdentifier user, bool requiresAll, params string[] permissionNames)
        {
            if (permissionNames.IsNullOrEmpty())
            {
                return true;
            }

            if (requiresAll)
            {
                foreach (var permissionName in permissionNames)
                {
                    if (!(await permissionChecker.IsGrantedAsync(user, permissionName)))
                    {
                        return false;
                    }
                }

                return true;
            }
            else
            {
                foreach (var permissionName in permissionNames)
                {
                    if (await permissionChecker.IsGrantedAsync(user, permissionName))
                    {
                        return true;
                    }
                }

                return false;
            }
        }
 public async Task UnsubscribeAsync(UserIdentifier user, string notificationName, EntityIdentifier entityIdentifier = null)
 {
     await _store.DeleteSubscriptionAsync(
         user,
         notificationName,
         entityIdentifier == null ? null : entityIdentifier.Type.FullName,
         entityIdentifier == null ? null : entityIdentifier.Id.ToJsonString()
         );
 }
        public virtual async Task PublishAsync(
            string notificationName,
            NotificationData data = null,
            EntityIdentifier entityIdentifier = null,
            NotificationSeverity severity = NotificationSeverity.Info,
            UserIdentifier[] userIds = null,
            UserIdentifier[] excludedUserIds = null,
            int?[] tenantIds = null)
        {
            if (notificationName.IsNullOrEmpty())
            {
                throw new ArgumentException("NotificationName can not be null or whitespace!", "notificationName");
            }

            if (!tenantIds.IsNullOrEmpty() && !userIds.IsNullOrEmpty())
            {
                throw new ArgumentException("tenantIds can be set only if userIds is not set!", "tenantIds");
            }

            if (tenantIds.IsNullOrEmpty() && userIds.IsNullOrEmpty())
            {
                tenantIds = new[] {AbpSession.TenantId};
            }

            var notificationInfo = new NotificationInfo
            {
                NotificationName = notificationName,
                EntityTypeName = entityIdentifier == null ? null : entityIdentifier.Type.FullName,
                EntityTypeAssemblyQualifiedName = entityIdentifier == null ? null : entityIdentifier.Type.AssemblyQualifiedName,
                EntityId = entityIdentifier == null ? null : entityIdentifier.Id.ToJsonString(),
                Severity = severity,
                UserIds = userIds.IsNullOrEmpty() ? null : userIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","),
                ExcludedUserIds = excludedUserIds.IsNullOrEmpty() ? null : excludedUserIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","),
                TenantIds = tenantIds.IsNullOrEmpty() ? null : tenantIds.JoinAsString(","),
                Data = data == null ? null : data.ToJsonString(),
                DataTypeName = data == null ? null : data.GetType().AssemblyQualifiedName
            };

            await _store.InsertNotificationAsync(notificationInfo);

            await CurrentUnitOfWork.SaveChangesAsync(); //To get Id of the notification

            if (userIds != null && userIds.Length <= MaxUserCountToDirectlyDistributeANotification)
            {
                //We can directly distribute the notification since there are not much receivers
                await _notificationDistributer.DistributeAsync(notificationInfo.Id);
            }
            else
            {
                //We enqueue a background job since distributing may get a long time
                await _backgroundJobManager.EnqueueAsync<NotificationDistributionJob, NotificationDistributionJobArgs>(
                    new NotificationDistributionJobArgs(
                        notificationInfo.Id
                        )
                    );
            }
        }
        public async Task<IReadOnlyList<UserMenu>> GetMenusAsync(UserIdentifier user)
        {
            var userMenus = new List<UserMenu>();

            foreach (var menu in _navigationManager.Menus.Values)
            {
                userMenus.Add(await GetMenuAsync(menu.Name, user));
            }

            return userMenus;
        }
예제 #6
0
 /// <summary>
 /// Returns true if the profile exists.
 /// </summary>
 /// <returns><c>true</c>, if the profile exists for the given username, <c>false</c> otherwise.</returns>
 /// <param name="username">Username.</param>
 public bool ProfileExists(UserIdentifier username)
 {
     bool exists = false;
     using (var ctx = new DatabaseContexts.MainContext())
     {
         var query = from profile in ctx.UsersProfile
                     where profile.Username.Equals(username.Value)
                     select profile;
         exists = query.Count() != 0;
     }
     return exists;
 }
        public async Task<UserMenu> GetMenuAsync(string menuName, UserIdentifier user)
        {
            var menuDefinition = _navigationManager.Menus.GetOrDefault(menuName);
            if (menuDefinition == null)
            {
                throw new AbpException("There is no menu with given name: " + menuName);
            }

            var userMenu = new UserMenu(menuDefinition, _localizationContext);
            await FillUserMenuItems(user, menuDefinition.Items, userMenu.Items);
            return userMenu;
        }
        public async Task SubscribeToAllAvailableNotificationsAsync(UserIdentifier user)
        {
            var notificationDefinitions = (await _notificationDefinitionManager
                .GetAllAvailableAsync(user))
                .Where(nd => nd.EntityType == null)
                .ToList();

            foreach (var notificationDefinition in notificationDefinitions)
            {
                await SubscribeAsync(user, notificationDefinition.Name);
            }
        }
 public virtual async Task DeleteSubscriptionAsync(UserIdentifier user, string notificationName, string entityTypeName, string entityId)
 {
     using (_unitOfWorkManager.Current.SetTenantId(user.TenantId))
     {
         await _notificationSubscriptionRepository.DeleteAsync(s =>
             s.UserId == user.UserId &&
             s.NotificationName == notificationName &&
             s.EntityTypeName == entityTypeName &&
             s.EntityId == entityId
             );
         await _unitOfWorkManager.Current.SaveChangesAsync();
     }
 }
 /// <summary>
 /// Authenticate the User with specified username and password.
 /// </summary>
 /// <param name="username">Username.</param>
 /// <param name="password">Password.</param>
 public bool Authenticate(UserIdentifier username, string password)
 {
     bool isOk = false;
     password = Tools.Security.Hash(password);
     // sha1.ComputeHash();
     using (var ctx = new AuthenticationContext())
     {
         var query = from user in ctx.Users
                     where user.Username.Equals(username.Value) && user.Password.Equals(password)
                     select user.Username;
         isOk = query.Count() != 0;
     }
     return isOk;
 }
예제 #11
0
        /// <summary>
        /// Gets the SiteIdentifier corresponding to this user location.
        /// </summary>
        /// <value>The location.</value>
        public SiteIdentifier GetLocation(UserIdentifier username)
        {
            ValidateProfile(username);

            SiteIdentifier val;
            using (var ctx = new DatabaseContexts.MainContext())
            {
                var query = from profile in ctx.UsersProfile
                            where profile.Username.Equals(username.Value)
                            select profile.SiteID;

                val = new SiteIdentifier(query.First().ToString());
            }
            return val;
        }
예제 #12
0
        /// <summary>
        /// Gets a value indicating if the given user is an administator.
        /// </summary>
        /// <param name="username">Username.</param>
        public bool IsAdmin(UserIdentifier username)
        {
            ValidateProfile(username);

            bool isAdmin;
            using (var ctx = new DatabaseContexts.MainContext())
            {
                var query = from profile in ctx.UsersProfile
                            where profile.Username.Equals(username.Value)
                            select profile.IsAdmin;

                isAdmin = query.First();
            }
            return isAdmin;
        }
예제 #13
0
        /// <summary>
        /// Sets the given user location.
        /// When setting, if the user does not yet exist in the underlaying storage system, it is created.
        /// </summary>
        /// <param name="username">Username.</param>
        /// <param name="siteId">Site identifier.</param>
        public void SetLocation(UserIdentifier username, SiteIdentifier siteId)
        {
            ValidateProfile(username);

            using (var ctx = new DatabaseContexts.MainContext())
            {
                var query = from profile in ctx.UsersProfile
                            where profile.Username.Equals(username.Value)
                            select profile;

                DatabaseContexts.MCUserProfile prof = query.First();
                prof.SiteID = Int32.Parse(siteId.Value);
                ctx.SaveChanges();
            }
        }
        public async Task SubscribeAsync(UserIdentifier user, string notificationName, EntityIdentifier entityIdentifier = null)
        {
            if (await IsSubscribedAsync(user, notificationName, entityIdentifier))
            {
                return;
            }

            await _store.InsertSubscriptionAsync(
                new NotificationSubscriptionInfo(
                    user.TenantId,
                    user.UserId,
                    notificationName,
                    entityIdentifier
                    )
                );
        }
        private async Task<int> FillUserMenuItems(UserIdentifier user, IList<MenuItemDefinition> menuItemDefinitions, IList<UserMenuItem> userMenuItems)
        {
            //TODO: Can be optimized by re-using FeatureDependencyContext.

            var addedMenuItemCount = 0;

            using (var featureDependencyContext = _iocResolver.ResolveAsDisposable<FeatureDependencyContext>())
            {
                featureDependencyContext.Object.TenantId = user == null ? null : user.TenantId;

                foreach (var menuItemDefinition in menuItemDefinitions)
                {
                    if (menuItemDefinition.RequiresAuthentication && user == null)
                    {
                        continue;
                    }

                    if (!string.IsNullOrEmpty(menuItemDefinition.RequiredPermissionName) && (user == null || !(await PermissionChecker.IsGrantedAsync(user, menuItemDefinition.RequiredPermissionName))))
                    {
                        continue;
                    }

                    if (menuItemDefinition.FeatureDependency != null &&
                        (AbpSession.MultiTenancySide == MultiTenancySides.Tenant || (user != null && user.TenantId != null)) &&
                        !(await menuItemDefinition.FeatureDependency.IsSatisfiedAsync(featureDependencyContext.Object)))
                    {
                        continue;
                    }

                    var userMenuItem = new UserMenuItem(menuItemDefinition, _localizationContext);
                    if (menuItemDefinition.IsLeaf || (await FillUserMenuItems(user, menuItemDefinition.Items, userMenuItem.Items)) > 0)
                    {
                        userMenuItems.Add(userMenuItem);
                        ++addedMenuItemCount;
                    }
                }
            }

            return addedMenuItemCount;
        }
        public async Task<bool> IsAvailableAsync(string name, UserIdentifier user)
        {
            var notificationDefinition = GetOrNull(name);
            if (notificationDefinition == null)
            {
                return true;
            }

            if (notificationDefinition.FeatureDependency != null)
            {
                using (var featureDependencyContext = _iocManager.ResolveAsDisposable<FeatureDependencyContext>())
                {
                    featureDependencyContext.Object.TenantId = user.TenantId;

                    if (!await notificationDefinition.FeatureDependency.IsSatisfiedAsync(featureDependencyContext.Object))
                    {
                        return false;
                    }
                }
            }

            if (notificationDefinition.PermissionDependency != null)
            {
                using (var permissionDependencyContext = _iocManager.ResolveAsDisposable<PermissionDependencyContext>())
                {
                    permissionDependencyContext.Object.User = user;

                    if (!await notificationDefinition.PermissionDependency.IsSatisfiedAsync(permissionDependencyContext.Object))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
 public OnlineUserEventArgs(UserIdentifier user, IOnlineClient client)
     : base(client)
 {
     User = user;
 }
예제 #18
0
 /// <summary>
 /// Gets current value of a setting for a user level.
 /// It gets the setting value, overwritten by given tenant and user.
 /// </summary>
 /// <param name="settingManager">Setting manager</param>
 /// <param name="name">Unique name of the setting</param>
 /// <param name="user">User</param>
 /// <returns>Current value of the setting for the user</returns>
 public static async Task <T> GetSettingValueForUserAsync <T>(this ISettingManager settingManager, string name, UserIdentifier user)
     where T : struct
 {
     return((await settingManager.GetSettingValueForUserAsync(name, user)).To <T>());
 }
예제 #19
0
 /// <summary>
 /// Gets a list of all setting values specified for a user.
 /// It returns only settings those are explicitly set for the user.
 /// If a setting's value is not set for the user (for example if user uses the default value), it's not included the result list.
 /// If you want to get current values of all settings, use <see cref="GetAllSettingValues"/> method.
 /// </summary>
 /// <param name="settingManager">Setting manager</param>
 /// <param name="user">User to get settings</param>
 /// <returns>All settings of the user</returns>
 public static IReadOnlyList <ISettingValue> GetAllSettingValuesForUser(this ISettingManager settingManager, UserIdentifier user)
 {
     return(AsyncHelper.RunSync(() => settingManager.GetAllSettingValuesForUserAsync(user)));
 }
예제 #20
0
 public async Task SendUserConnectionChangeToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user, bool isConnected)
 {
     await Task.CompletedTask;
 }
예제 #21
0
 public void SendUserStateChangeToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user, FriendshipState newState)
 {
 }
예제 #22
0
 public User GetUserOrNull(UserIdentifier userIdentifier)
 {
     return(AsyncHelper.RunSync(() => GetUserOrNullAsync(userIdentifier)));
 }
예제 #23
0
 public async Task SendAllUnreadMessagesOfUserReadToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user)
 {
     await Task.CompletedTask;
 }
 /// <summary>
 /// Determines whether the specified user is online or not.
 /// </summary>
 /// <param name="onlineClientManager">The online client manager.</param>
 /// <param name="user">User.</param>
 public static bool IsOnline(IOnlineClientManager onlineClientManager, UserIdentifier user)
 {
     return onlineClientManager.GetByUserIdOrNull(user) != null;
 }
 /// <summary>
 /// Checks if given user is granted for given permission.
 /// </summary>
 /// <param name="permissionChecker">Permission checker</param>
 /// <param name="user">User</param>
 /// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param>
 /// <param name="permissionNames">Name of the permissions</param>
 public static bool IsGranted(this IPermissionChecker permissionChecker, UserIdentifier user, bool requiresAll, params string[] permissionNames)
 {
     return AsyncHelper.RunSync(() => IsGrantedAsync(permissionChecker, user, requiresAll, permissionNames));
 }
예제 #26
0
 public virtual async Task <UserAccount> GetUserAccountAsync(UserIdentifier userIdentifier)
 {
     return(await _userAccountRepository.FirstOrDefaultAsync(ua => ua.TenantId == userIdentifier.TenantId && ua.UserId == userIdentifier.UserId));
 }
예제 #27
0
 public Task UpdateUserUiManagementSettingsAsync(UserIdentifier user, ThemeSettingsDto settings)
 {
     throw new System.NotImplementedException();
 }
예제 #28
0
        public virtual async Task <bool> AreUsersLinked(UserIdentifier firstUserIdentifier, UserIdentifier secondUserIdentifier)
        {
            var firstUserAccount = await GetUserAccountAsync(firstUserIdentifier);

            var secondUserAccount = await GetUserAccountAsync(secondUserIdentifier);

            if (!firstUserAccount.UserLinkId.HasValue || !secondUserAccount.UserLinkId.HasValue)
            {
                return(false);
            }

            return(firstUserAccount.UserLinkId == secondUserAccount.UserLinkId);
        }
예제 #29
0
        private async Task HandleReceiverToSenderAsync(UserIdentifier senderIdentifier, UserIdentifier receiverIdentifier, string message, Guid sharedMessageId)
        {
            var friendshipState = (await _friendshipManager.GetFriendshipOrNullAsync(receiverIdentifier, senderIdentifier))?.State;

            if (friendshipState == null)
            {
                var senderTenancyName = senderIdentifier.TenantId.HasValue ?
                                        _tenantCache.Get(senderIdentifier.TenantId.Value).TenancyName :
                                        null;

                var senderUser = _userManager.GetUser(senderIdentifier);
                await _friendshipManager.CreateFriendshipAsync(
                    new Friendship(
                        receiverIdentifier,
                        senderIdentifier,
                        senderTenancyName,
                        senderUser.UserName,
                        senderUser.ProfilePictureId,
                        FriendshipState.Accepted
                        )
                    );
            }

            if (friendshipState == FriendshipState.Blocked)
            {
                //Do not send message if receiver banned the sender
                return;
            }

            var sentMessage = new ChatMessage(
                receiverIdentifier,
                senderIdentifier,
                ChatSide.Receiver,
                message,
                ChatMessageReadState.Unread,
                sharedMessageId,
                ChatMessageReadState.Read
                );

            Save(sentMessage);

            var clients = _onlineClientManager.GetAllByUserId(receiverIdentifier);

            if (clients.Any())
            {
                await _chatCommunicator.SendMessageToClient(clients, sentMessage);
            }
            else if (GetUnreadMessageCount(senderIdentifier, receiverIdentifier) == 1)
            {
                var senderTenancyName = senderIdentifier.TenantId.HasValue ?
                                        _tenantCache.Get(senderIdentifier.TenantId.Value).TenancyName :
                                        null;

                await _userEmailer.TryToSendChatMessageMail(
                    _userManager.GetUser(receiverIdentifier),
                    _userManager.GetUser(senderIdentifier).UserName,
                    senderTenancyName,
                    sentMessage
                    );
            }
        }
예제 #30
0
        private async Task HandleSenderToReceiverAsync(UserIdentifier senderIdentifier, UserIdentifier receiverIdentifier, string message, Guid sharedMessageId)
        {
            var friendshipState = (await _friendshipManager.GetFriendshipOrNullAsync(senderIdentifier, receiverIdentifier))?.State;

            if (friendshipState == null)
            {
                friendshipState = FriendshipState.Accepted;

                var receiverTenancyName = receiverIdentifier.TenantId.HasValue
                    ? _tenantCache.Get(receiverIdentifier.TenantId.Value).TenancyName
                    : null;

                var receiverUser = _userManager.GetUser(receiverIdentifier);
                await _friendshipManager.CreateFriendshipAsync(
                    new Friendship(
                        senderIdentifier,
                        receiverIdentifier,
                        receiverTenancyName,
                        receiverUser.UserName,
                        receiverUser.ProfilePictureId,
                        friendshipState.Value)
                    );
            }

            if (friendshipState.Value == FriendshipState.Blocked)
            {
                //Do not send message if receiver banned the sender
                return;
            }

            var sentMessage = new ChatMessage(
                senderIdentifier,
                receiverIdentifier,
                ChatSide.Sender,
                message,
                ChatMessageReadState.Read,
                sharedMessageId,
                ChatMessageReadState.Unread
                );

            Save(sentMessage);

            await _chatCommunicator.SendMessageToClient(
                _onlineClientManager.GetAllByUserId(senderIdentifier),
                sentMessage
                );
        }
 /// <summary>
 /// Subscribes to a notification.
 /// </summary>
 /// <param name="notificationSubscriptionManager">Notification subscription manager</param>
 /// <param name="user">User.</param>
 /// <param name="notificationName">Name of the notification.</param>
 /// <param name="entityIdentifier">entity identifier</param>
 public static void Subscribe(this INotificationSubscriptionManager notificationSubscriptionManager, UserIdentifier user, string notificationName, EntityIdentifier entityIdentifier = null)
 {
     AsyncHelper.RunSync(() => notificationSubscriptionManager.SubscribeAsync(user, notificationName, entityIdentifier));
 }
 public Task<bool> IsGrantedAsync(UserIdentifier user, string permissionName)
 {
     return Task.FromResult(true);
 }
 /// <summary>
 /// Subscribes to all available notifications for given user.
 /// It does not subscribe entity related notifications.
 /// </summary>
 /// <param name="notificationSubscriptionManager">Notification subscription manager</param>
 /// <param name="user">User.</param>
 public static void SubscribeToAllAvailableNotifications(this INotificationSubscriptionManager notificationSubscriptionManager, UserIdentifier user)
 {
     AsyncHelper.RunSync(() => notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user));
 }
 /// <summary>
 /// Gets notifications for a user.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">User.</param>
 /// <param name="state">State</param>
 /// <param name="skipCount">Skip count.</param>
 /// <param name="maxResultCount">Maximum result count.</param>
 public static List<UserNotification> GetUserNotifications(this IUserNotificationManager userNotificationManager, UserIdentifier user, UserNotificationState? state = null, int skipCount = 0, int maxResultCount = int.MaxValue)
 {
     return AsyncHelper.RunSync(() => userNotificationManager.GetUserNotificationsAsync(user, state, skipCount: skipCount, maxResultCount: maxResultCount));
 }
예제 #35
0
 public async Task SendReadStateChangeToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user)
 {
     await Task.CompletedTask;
 }
 /// <summary>
 /// Updates all notification states for a user.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">User.</param>
 /// <param name="state">New state.</param>
 public static void UpdateAllUserNotificationStates(this IUserNotificationManager userNotificationManager, UserIdentifier user, UserNotificationState state)
 {
     AsyncHelper.RunSync(() => userNotificationManager.UpdateAllUserNotificationStatesAsync(user, state));
 }
예제 #37
0
 public async Task SendUserStateChangeToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user, FriendshipState newState)
 {
     await Task.CompletedTask;
 }
 /// <summary>
 /// Subscribes to all available notifications for given user.
 /// It does not subscribe entity related notifications.
 /// </summary>
 /// <param name="notificationSubscriptionManager">Notification subscription manager</param>
 /// <param name="user">User.</param>
 public static void SubscribeToAllAvailableNotifications(this INotificationSubscriptionManager notificationSubscriptionManager, UserIdentifier user)
 {
     AsyncHelper.RunSync(() => notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user));            
 }
예제 #39
0
 public void SendAllUnreadMessagesOfUserReadToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user)
 {
 }
 /// <summary>
 /// Gets subscribed notifications for a user.
 /// </summary>
 /// <param name="notificationSubscriptionManager">Notification subscription manager</param>
 /// <param name="user">User.</param>
 public static List<NotificationSubscription> GetSubscribedNotifications(this INotificationSubscriptionManager notificationSubscriptionManager, UserIdentifier user)
 {
     return AsyncHelper.RunSync(() => notificationSubscriptionManager.GetSubscribedNotificationsAsync(user));
 }
예제 #41
0
 public void SendUserConnectionChangeToClients(IReadOnlyList <IOnlineClient> clients, UserIdentifier user, bool isConnected)
 {
 }
예제 #42
0
        public async Task<JsonResult> Authenticate([FromBody] AuthenticateModel model)
        { 
            //AuthenticateResultModel 返回的字典类型
            SortedDictionary<string, object> DgDict = new SortedDictionary<string, object>();
            //返回登录结果
            var loginResult = await GetLoginResultAsync(
                model.UserNameOrEmailAddress,
                model.Password,
                GetTenancyNameOrNull()
            );
            AbpClaimTypes.UserId = loginResult.User.Id.ToString();
            #region 角色列表版本  暂时没用
            DgDict.Add("permissionsToRolesVersion", 1001);
            #endregion
           
            #region 获取所有权限列表
            var Permissions = PermissionManager.GetAllPermissions();
            Treelist = new List<TreeClass>();
            TreeClass treeClass1 = new TreeClass();
            treeClass1.id = 1;
            treeClass1.parentId = 0;
            treeClass1.label = Mapper.Map<PermissionDto>(Permissions.Where(x => x.Name == PermissionNames.Pages_Staff).FirstOrDefault()).DisplayName;
            treeClass1.Permission = Mapper.Map<PermissionDto>(Permissions.Where(x => x.Name == PermissionNames.Pages_Staff).FirstOrDefault());           
            Treelist = Recursion(Permissions.Where(x => x.Name == PermissionNames.Pages_Staff).FirstOrDefault(), 1);
            Treelist.Add(treeClass1);
            DgDict.Add("allPermissions", new ListResultDto<PermissionDto>(
                ObjectMapper.Map<List<PermissionDto>>(Permissions)
            ));
            try
            { 
                DgDict.Add("allPermissionsForTree", Treelist);
            }
            catch (Exception ex)
            {

            }
            num = 1;
            //权限列表
            List<Permission> allPermissions = new List<Permission>();
            foreach (var item in Permissions)
            {
                allPermissions.Add(item);
            }
            #endregion
           
            #region 角色列表
            //var allRoles = await _roleRepository.GetAllListAsync();
            var allRoleIReadOnlyList = await _roleRepository.GetAllListAsync();
            List<Role> allRoles = new List<Role>();
            foreach (var item in allRoleIReadOnlyList.Where(x=>x.IsDeleted==false).ToList())
            {
                allRoles.Add(item);
            }
            DgDict.Add("allRoles", Mapper.Map<List<RoleListDto>>(allRoles));
            //DgDict.Add("allRoles", new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles)));

            //new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles));

            #endregion
            //获取登录用户的所拥有的所有权限
            var grantedPermissionNames = new List<string>();
            if (loginResult.User.Id>0)
            {
                foreach (var permissionName in allPermissions)
                {
                   Abp.UserIdentifier Identifier=UserIdentifier.Parse(loginResult.User.Id.ToString());
                    if (await PermissionChecker.IsGrantedAsync(Identifier, permissionName.Name))
                    {
                        grantedPermissionNames.Add(permissionName.Name);  // 获取当前用户的权限
                    }
                }
            }
          
            #region  是否有审核权 canAssignInspectionToOther
            bool canAssignInspectionToOther = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_Inspection);
            if (!canAssignInspectionToOther)
            {
                DgDict.Add("canAssignInspectionToOther", "没有Pages_Inspection");
                DgDict.Add("canAssignInspectionToOtherValue", false);
            }
            else
            {
                DgDict.Add("canAssignInspectionToOther", "拥有Pages_Inspection");
                DgDict.Add("canAssignInspectionToOtherValue", true);
            }
            #endregion

            bool canAssignRolesFromAdmin = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_Tenants);
            bool canAssignRolesFromRQAdmin = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_Admin);
            bool canAssignRolesFromRQAssitant = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_RQAssitant);
 
            #region 可分配角色列表--针对员工管理

            List<Role> RolescanAssigned = allRoles;
            List<string> RolescanAssignedString = new List<string>();//角色名数组初始化
            foreach (var item in allRoleIReadOnlyList.Where(x => x.IsDeleted == false).ToList())
            {
                RolescanAssignedString.Add(item.Name);
            }
            //如果任务已经分配且未分配给自己,且不具有分配任务权限,则抛出异常
            if (canAssignRolesFromAdmin) 
            {
                List<Role> allmyRoles = new List<Role>();//当前用户可分配的角色 初始化
                string[] outAdmin = { "Admin"};
                foreach (var item in outAdmin)
                {
                    if (RolescanAssignedString.Contains(item))
                    {
                        RolescanAssignedString.Remove(item);
                    }  //item.SetNormalizedName in
                }
                foreach (var itemStr in RolescanAssignedString)
                {
                    foreach (var item in allRoles)
                    {
                        if (item.Name == itemStr)
                        {
                            allmyRoles.Add(item);
                        }
                    }
                }
                DgDict.Add("RolescanAssigned", Mapper.Map<List<RoleDto>>(allmyRoles));
            }
            else if (canAssignRolesFromRQAdmin)
            {
                List<Role> allmyRoles = new List<Role>();//当前用户可分配的角色 初始化
                string[] outAdmin = { "Admin","RQAdmin","RQAdminPermissions"};
                foreach (var item in outAdmin)
                {
                    if (RolescanAssignedString.Contains(item))
                    {
                        RolescanAssignedString.Remove(item);
                    }  //item.SetNormalizedName in
                }
                foreach (var itemStr in RolescanAssignedString)
                {
                    foreach (var item in allRoles)
                    {
                        if (item.Name == itemStr)
                        {
                            allmyRoles.Add(item);
                        }
                    }
                }
                DgDict.Add("RolescanAssigned", Mapper.Map<List<RoleDto>>(allmyRoles));

            }
            else if (canAssignRolesFromRQAssitant)
            {
                string[] outAdmin = { "Admin", "RQAssitantPermissions",
                    "RQAdmin" , "RQAssitant" ,"RQAdminPermissions"};
                List<Role> allmyRoles = new List<Role>();//当前用户可分配的角色 初始化
                foreach (var item in outAdmin)
                {
                    if (RolescanAssignedString.Contains(item))
                    {
                        RolescanAssignedString.Remove(item);
                    }  //item.SetNormalizedName in
                }
                foreach (var itemStr in RolescanAssignedString)
                {
                    foreach (var item in allRoles)
                    {
                        if (item.Name == itemStr)
                        {
                            allmyRoles.Add(item);
                        }
                    }
                }
                DgDict.Add("RolescanAssigned", Mapper.Map<List<RoleDto>>(allmyRoles));

            }
            else
            { 
                DgDict.Add("RolescanAssigned", null);
            }
            #endregion
            
            #region 可分配权限列表【角色管理-分配权限】
            var PermissionscanAssigned = allPermissions;
            List<string> PermissionscanAssignedString = new List<string>();
            foreach (var item in PermissionscanAssigned)
            {
                PermissionscanAssignedString.Add(item.Name);
            }

            if (canAssignRolesFromAdmin) 
            {
                DgDict.Add("PermissionscanAssigned", Mapper.Map<List<PermissionDto>>(PermissionscanAssigned));
            }
            else if (canAssignRolesFromRQAdmin)
            {
                List<Permission> allMyPermission = new List<Permission>();//当前用户可分配的权限 初始化
                string[] outAdmin = {"Pages","Pages.Tenants",
                    "Pages.Users", "Pages.Roles", "Pages.Admin",
                    "Pages.Admin.Users","Pages.Admin.Roles"
                };
                foreach (var item in outAdmin)
                {
                    if (PermissionscanAssignedString.Contains(item))
                    {
                        PermissionscanAssignedString.Remove(item);
                    }  
                }
                foreach (var itemStr in PermissionscanAssignedString)
                {
                    foreach (var item in PermissionscanAssigned)
                    {
                        if (item.Name == itemStr)
                        {
                            allMyPermission.Add(item);
                        }
                    }
                }
                DgDict.Add("PermissionscanAssigned", Mapper.Map<List<PermissionDto>>(allMyPermission));

            }
            else if (canAssignRolesFromRQAssitant)
            {
                List<Permission> allMyPermission = new List<Permission>();//当前用户可分配的权限 初始化
                string[] outAdmin = {"Pages","Pages.Tenants",
                    "Pages.Users", "Pages.Roles", "Pages.Admin",
                    "Pages.Admin.Users","Pages.Admin.Roles",
                    "Pages.RQAssitant.Roles", "Pages.RQAssitant.Users",
                    "Pages.RQAssitant"
                };
                foreach (var item in outAdmin)
                {
                    if (PermissionscanAssignedString.Contains(item))
                    {
                        PermissionscanAssignedString.Remove(item);
                    }
                }
                foreach (var itemStr in PermissionscanAssignedString)
                {
                    foreach (var item in PermissionscanAssigned)
                    {
                        if (item.Name == itemStr)
                        {
                            allMyPermission.Add(item);
                        }
                    }
                }
                DgDict.Add("PermissionscanAssigned", Mapper.Map<List<PermissionDto>>(allMyPermission));

            }
            else
            {
                DgDict.Add("PermissionscanAssigned", null);
            }

            #endregion
            
            #region 登录返回UserId-accessToken--EncryptedAccessToken-ExpireInSeconds
            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
            DgDict.Add("AuthenticateResultModel",
                   new AuthenticateResultModel
                   {
                       AccessToken = accessToken,
                       EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                       ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                       UserId = loginResult.User.Id
                   }
                );
            #endregion

            return Json(DgDict);
        }
예제 #43
0
 /// <summary>
 /// Changes setting for a user.
 /// </summary>
 /// <param name="settingManager">Setting manager</param>
 /// <param name="user">User</param>
 /// <param name="name">Unique name of the setting</param>
 /// <param name="value">Value of the setting</param>
 public static void ChangeSettingForUser(this ISettingManager settingManager, UserIdentifier user, string name, string value)
 {
     AsyncHelper.RunSync(() => settingManager.ChangeSettingForUserAsync(user, name, value));
 }
 /// <summary>
 /// Deletes all notifications of a user.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">The user id.</param>
 public static void DeleteAllUserNotifications(this IUserNotificationManager userNotificationManager, UserIdentifier user)
 {
     AsyncHelper.RunSync(() => userNotificationManager.DeleteAllUserNotificationsAsync(user));
 }
 private void UpdateUserOnCache(UserIdentifier userIdentifier, UserWithFriendsCacheItem user)
 {
     _cacheManager.GetCache(FriendCacheItem.CacheName).Set(userIdentifier.ToUserIdentifierString(), user);
 }
 public Task <bool> IsGrantedAsync(UserIdentifier user, string permissionName)
 {
     return(IsGrantedAsync(permissionName));
 }
 /// <summary>
 /// Checks if a user is granted for a permission.
 /// </summary>
 /// <param name="permissionChecker">Permission checker</param>
 /// <param name="user">User to check</param>
 /// <param name="permissionName">Name of the permission</param>
 public static bool IsGranted(this IPermissionChecker permissionChecker, UserIdentifier user, string permissionName)
 {
     return AsyncHelper.RunSync(() => permissionChecker.IsGrantedAsync(user, permissionName));
 }
 public virtual UserWithFriendsCacheItem GetCacheItem(UserIdentifier userIdentifier)
 {
     return(_cacheManager
            .GetCache(FriendCacheItem.CacheName)
            .Get <string, UserWithFriendsCacheItem>(userIdentifier.ToUserIdentifierString(), f => GetUserFriendsCacheItemInternal(userIdentifier)));
 }
        protected virtual async Task<List<UserNotification>> SaveUserNotifications(UserIdentifier[] users, NotificationInfo notificationInfo)
        {
            var userNotifications = new List<UserNotification>();

            var tenantGroups = users.GroupBy(user => user.TenantId);
            foreach (var tenantGroup in tenantGroups)
            {
                using (_unitOfWorkManager.Current.SetTenantId(tenantGroup.Key))
                {
                    var tenantNotificationInfo = new TenantNotificationInfo(tenantGroup.Key, notificationInfo);
                    await _notificationStore.InsertTenantNotificationAsync(tenantNotificationInfo);
                    await _unitOfWorkManager.Current.SaveChangesAsync(); //To get tenantNotification.Id.

                    var tenantNotification = tenantNotificationInfo.ToTenantNotification();

                    foreach (var user in tenantGroup)
                    {
                        var userNotification = new UserNotificationInfo
                        {
                            TenantId = tenantGroup.Key,
                            UserId = user.UserId,
                            TenantNotificationId = tenantNotificationInfo.Id
                        };

                        await _notificationStore.InsertUserNotificationAsync(userNotification);
                        userNotifications.Add(userNotification.ToUserNotification(tenantNotification));
                    }

                    await CurrentUnitOfWork.SaveChangesAsync(); //To get Ids of the notifications
                }
            }

            return userNotifications;
        }
 public virtual UserWithFriendsCacheItem GetCacheItemOrNull(UserIdentifier userIdentifier)
 {
     return(_cacheManager
            .GetCache(FriendCacheItem.CacheName)
            .GetOrDefault <string, UserWithFriendsCacheItem>(userIdentifier.ToUserIdentifierString()));
 }
 /// <summary>
 /// Publishes a new notification.
 /// </summary>
 /// <param name="notificationPublisher">Notification publisher</param>
 /// <param name="notificationName">Unique notification name</param>
 /// <param name="data">Notification data (optional)</param>
 /// <param name="entityIdentifier">The entity identifier if this notification is related to an entity</param>
 /// <param name="severity">Notification severity</param>
 /// <param name="userIds">Target user id(s). Used to send notification to specific user(s). If this is null/empty, the notification is sent to all subscribed users</param>
 public static void Publish(this INotificationPublisher notificationPublisher, string notificationName, NotificationData data = null, EntityIdentifier entityIdentifier = null, NotificationSeverity severity = NotificationSeverity.Info, UserIdentifier[] userIds = null)
 {
     AsyncHelper.RunSync(() => notificationPublisher.PublishAsync(notificationName, data, entityIdentifier, severity, userIds));
 }
        public virtual void IncreaseUnreadMessageCount(UserIdentifier userIdentifier, UserIdentifier friendIdentifier, int change)
        {
            var user = GetCacheItemOrNull(userIdentifier);

            if (user == null)
            {
                return;
            }

            lock (_syncObj)
            {
                var friend = user.Friends.FirstOrDefault(
                    f => f.FriendUserId == friendIdentifier.UserId &&
                    f.FriendTenantId == friendIdentifier.TenantId
                    );

                if (friend == null)
                {
                    return;
                }

                friend.UnreadMessageCount += change;
                UpdateUserOnCache(userIdentifier, user);
            }
        }
 /// <summary>
 /// Gets user notification count.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">User.</param>
 /// <param name="state">State.</param>
 public static int GetUserNotificationCount(this IUserNotificationManager userNotificationManager, UserIdentifier user, UserNotificationState? state = null)
 {
     return AsyncHelper.RunSync(() => userNotificationManager.GetUserNotificationCountAsync(user, state));
 }
예제 #54
0
        public async Task AcceptFriendshipRequestAsync(UserIdentifier userIdentifier, UserIdentifier probableFriend)
        {
            var friendship = (await GetFriendshipOrNullAsync(userIdentifier, probableFriend));

            if (friendship == null)
            {
                throw new Exception("Friendship does not exist between " + userIdentifier + " and " + probableFriend);
            }

            friendship.State = FriendshipState.Accepted;
            await UpdateFriendshipAsync(friendship);
        }
 /// <summary>
 /// Deletes all notifications of a user.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">The user id.</param>
 public static void DeleteAllUserNotifications(this IUserNotificationManager userNotificationManager, UserIdentifier user)
 {
     AsyncHelper.RunSync(() => userNotificationManager.DeleteAllUserNotificationsAsync(user));
 }
 /// <summary>
 /// Gets notifications for a user.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">User.</param>
 /// <param name="state">State</param>
 /// <param name="skipCount">Skip count.</param>
 /// <param name="maxResultCount">Maximum result count.</param>
 public static List <UserNotification> GetUserNotifications(this IUserNotificationManager userNotificationManager, UserIdentifier user, UserNotificationState?state = null, int skipCount = 0, int maxResultCount = int.MaxValue)
 {
     return(AsyncHelper.RunSync(() => userNotificationManager.GetUserNotificationsAsync(user, state, skipCount, maxResultCount)));
 }
 /// <summary>
 /// Unsubscribes from a notification.
 /// </summary>
 /// <param name="notificationSubscriptionManager">Notification subscription manager</param>
 /// <param name="user">User.</param>
 /// <param name="notificationName">Name of the notification.</param>
 /// <param name="entityIdentifier">entity identifier</param>
 public static void Unsubscribe(this INotificationSubscriptionManager notificationSubscriptionManager, UserIdentifier user, string notificationName, EntityIdentifier entityIdentifier = null)
 {
     AsyncHelper.RunSync(() => notificationSubscriptionManager.UnsubscribeAsync(user, notificationName, entityIdentifier));
 }
 /// <summary>
 /// Gets user notification count.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">User.</param>
 /// <param name="state">State.</param>
 public static int GetUserNotificationCount(this IUserNotificationManager userNotificationManager, UserIdentifier user, UserNotificationState?state = null)
 {
     return(AsyncHelper.RunSync(() => userNotificationManager.GetUserNotificationCountAsync(user, state)));
 }
 /// <summary>
 /// Checks if a user subscribed for a notification.
 /// </summary>
 /// <param name="notificationSubscriptionManager">Notification subscription manager</param>
 /// <param name="user">User.</param>
 /// <param name="notificationName">Name of the notification.</param>
 /// <param name="entityIdentifier">entity identifier</param>
 public static bool IsSubscribed(this INotificationSubscriptionManager notificationSubscriptionManager, UserIdentifier user, string notificationName, EntityIdentifier entityIdentifier = null)
 {
     return AsyncHelper.RunSync(() => notificationSubscriptionManager.IsSubscribedAsync(user, notificationName, entityIdentifier));
 }
 /// <summary>
 /// Updates all notification states for a user.
 /// </summary>
 /// <param name="userNotificationManager">User notificaiton manager</param>
 /// <param name="user">User.</param>
 /// <param name="state">New state.</param>
 public static void UpdateAllUserNotificationStates(this IUserNotificationManager userNotificationManager, UserIdentifier user, UserNotificationState state)
 {
     AsyncHelper.RunSync(() => userNotificationManager.UpdateAllUserNotificationStatesAsync(user, state));
 }