Пример #1
0
        public async Task <PermissionGrantResult> CheckPermissionAsync(IPermissionActor actor, string permission)
        {
            var grantedPermissions = new List <string>();
            var deniedPermissions  = new List <string>();

            foreach (var permissionSource in m_PermissionChecker.PermissionStores)
            {
                grantedPermissions.AddRange(await permissionSource.GetGrantedPermissionsAsync(actor));
                deniedPermissions.AddRange(await permissionSource.GetDeniedPermissionsAsync(actor));
            }

            var permissionTree = BuildPermissionTree(permission);

            foreach (var permissionNode in permissionTree)
            {
                if (deniedPermissions.Any(c => CheckPermissionEquals(permissionNode, c)))
                {
                    return(PermissionGrantResult.Deny);
                }

                if (grantedPermissions.Any(c => CheckPermissionEquals(permissionNode, c)))
                {
                    return(PermissionGrantResult.Grant);
                }
            }

            return(PermissionGrantResult.Default);
        }
Пример #2
0
        private async Task <decimal> UpdateBalance(IPermissionActor actor, decimal amount)
        {
            try
            {
                return(await m_EconomyProvider.UpdateBalanceAsync(actor.Id, actor.Type, amount, m_Reason));
            }
            catch (NotEnoughBalanceException ex)
            {
                if (!m_IsAmountNegative)
                {
                    throw;
                }

                if (m_SetNegative)
                {
                    await m_EconomyProvider.SetBalanceAsync(actor.Id, actor.Type, 0);

                    return(0);
                }

                if (m_IsSelf)
                {
                    throw;
                }

                throw new NotEnoughBalanceException(
                          m_StringLocalizer["economy:fail:not_enough_balance_negative",
                                            new { Amount = amount, EconomyProvider = m_EconomyProvider, Target = actor }], ex.Balance !.Value);
            }
        }
Пример #3
0
        public virtual async Task <bool> AddGrantedPermissionAsync(IPermissionActor actor, string permission)
        {
            if (actor is IPermissionRole)
            {
                var roleData = m_PermissionRolesDataStore.Roles.First(d => d.Id?.Equals(actor.Id, StringComparison.OrdinalIgnoreCase) ?? false);
                if (roleData == null)
                {
                    return(false);
                }

                roleData.Permissions ??= new ();
                roleData.Permissions.Add(permission);
                await m_PermissionRolesDataStore.SaveChangesAsync();

                return(true);
            }

            var userData = await m_UserDataStore.GetUserDataAsync(actor.Id, actor.Type);

            if (userData == null)
            {
                return(false);
            }

            userData.Permissions ??= new();
            userData.Permissions.Add(permission);
            await m_UserDataStore.SetUserDataAsync(userData);

            return(true);
        }
Пример #4
0
        public virtual async Task <bool> RemoveGrantedPermissionAsync(IPermissionActor actor, string permission)
        {
            if (actor is IPermissionRole)
            {
                var roleData = m_PermissionRolesDataStore.Roles.First(d => d.Id.Equals(actor.Id, StringComparison.OrdinalIgnoreCase));
                if (roleData == null)
                {
                    return(false);
                }

                if (!roleData.Permissions.Remove(permission))
                {
                    return(false);
                }

                await m_PermissionRolesDataStore.SaveChangesAsync();

                return(true);
            }

            var userData = await m_UserDataStore.GetUserDataAsync(actor.Id, actor.Type);

            if (!userData.Permissions.Remove(permission))
            {
                return(false);
            }

            await m_UserDataStore.SaveUserDataAsync(userData);

            return(true);
        }
        public Task <bool> AddDeniedPermissionAsync(IPermissionActor target, string permission)
        {
            GuardPermission(ref permission);
            GuardTarget(target);

            return(AddPermissionAsync(target, "!" + permission));
        }
Пример #6
0
        public async Task <PermissionGrantResult> CheckPermissionAsync(IPermissionActor actor, string permission)
        {
            var registration = m_PermissionRegistry.FindPermission(permission);

            if (registration == null)
            {
                throw new Exception($"Permission is not registered: {permission}");
            }

            foreach (var provider in m_PermissionCheckProviders.Where(c => c.SupportsActor(actor)))
            {
                var result = await provider.CheckPermissionAsync(actor, permission);

                m_Logger.LogDebug("{ActorName} permission check result for \"{ProviderName}\" ({Permission}): {Result}",
                                  actor.FullActorName, provider.GetType().Name, permission, result);

                if (result != PermissionGrantResult.Default)
                {
                    return(result);
                }
            }

            m_Logger.LogDebug("{ActorName} permission check \"{Permission}\" returning default",
                              actor.FullActorName, permission);
            return(registration.DefaultGrant);
        }
        public async Task <bool> RemoveDeniedPermissionAsync(IPermissionActor target, string permission)
        {
            GuardPermission(ref permission);
            GuardTarget(target);

            return(await RemovePermissionAsync(target, "!" + permission));
        }
Пример #8
0
        public virtual async Task <bool> AddRoleToActorAsync(IPermissionActor actor, string roleId)
        {
            if (actor == null)
            {
                throw new ArgumentNullException(nameof(actor));
            }

            if (string.IsNullOrEmpty(roleId))
            {
                throw new ArgumentNullException(nameof(roleId));
            }

            var userData = await m_UserDataStore.GetUserDataAsync(actor.Id, actor.Type);

            if (userData == null)
            {
                return(false);
            }

            userData.Roles ??= new HashSet <string>();
            if (userData.Roles.Contains(roleId))
            {
                return(true);
            }

            userData.Roles.Add(roleId);

            await m_UserDataStore.SetUserDataAsync(userData);

            await m_EventBus.EmitAsync(m_Runtime, this, new PermissionActorRoleAddedEvent(actor, roleId));

            return(true);
        }
Пример #9
0
        public virtual async Task <bool> RemoveRoleFromActorAsync(IPermissionActor actor, string roleId)
        {
            if (actor == null)
            {
                throw new ArgumentNullException(nameof(actor));
            }

            if (string.IsNullOrEmpty(roleId))
            {
                throw new ArgumentNullException(nameof(roleId));
            }

            var userData = await m_UserDataStore.GetUserDataAsync(actor.Id, actor.Type);

            if (userData?.Roles == null)
            {
                return(false);
            }

            userData.Roles.Remove(roleId);

            await m_UserDataStore.SetUserDataAsync(userData);

            await m_EventBus.EmitAsync(m_Runtime, this, new PermissionActorRoleRemovedEvent(actor, roleId));

            return(true);
        }
Пример #10
0
        public Task <bool> AddRoleToActorAsync(IPermissionActor actor, string roleId)
        {
            if (actor == null)
            {
                throw new ArgumentNullException(nameof(actor));
            }

            if (string.IsNullOrEmpty(roleId))
            {
                throw new ArgumentException(nameof(roleId));
            }

            if (RocketModIntegrationEnabled() && IsRocketModRole(roleId))
            {
                if (!IsPlayerActor(actor.Type))
                {
                    throw new NotSupportedException($"Cannot add non-player actor {actor.Type} to a RocketMod group.");
                }

                var result = R.Permissions.AddPlayerToGroup(roleId, ToRocketPlayer(actor));
                return(Task.FromResult(result == RocketPermissionsProviderResult.Success));
            }

            return(m_BasePermissionRoleStore.AddRoleToActorAsync(actor, roleId));
        }
 private void GuardTarget(IPermissionActor target)
 {
     if (!SupportsTarget(target))
     {
         throw new NotSupportedException(target.GetType().FullName + " is not supported!");
     }
 }
        public async Task <IEnumerable <string> > GetDeniedPermissionsAsync(IPermissionActor target, bool inherit = true)
        {
            PermissionSection section = target is IPermissionGroup
                ? (PermissionSection) await GetConfigSectionAsync <GroupPermissionSection>(target, false)
                : await GetConfigSectionAsync <PlayerPermissionSection>(target, false);

            List <string> permissions;

            if (section != null)
            {
                permissions = section.Permissions
                              .Where(c => c.StartsWith("!"))
                              .Select(c => c.Substring(1).ToLower())
                              .ToList();
            }
            else
            {
                permissions = new List <string>();
            }

            if (inherit)
            {
                foreach (var parent in await GetGroupsAsync(target))
                {
                    permissions
                    .AddRange(await GetDeniedPermissionsAsync(parent, true));
                }
            }

            return(permissions.Distinct());
        }
Пример #13
0
        public async Task <bool> RemoveRoleFromActorAsync(IPermissionActor actor, string roleId)
        {
            if (IsRocketModRole(roleId))
            {
                throw new System.NotSupportedException();
            }

            return(await m_BasePermissionRoleStore.RemoveRoleFromActorAsync(actor, roleId));
        }
        public async Task <PermissionResult> CheckPermissionAsync(IPermissionActor target, string permission)
        {
            GuardLoaded();
            GuardPermission(ref permission);
            GuardTarget(target);

            permission = permission.Replace("!!", ""); //remove double negations

            if (!permission.StartsWith("!") && await CheckPermissionAsync(target, "!" + permission) == PermissionResult.Grant)
            {
                return(PermissionResult.Deny);
            }

            IEnumerable <string> permissionTree = BuildPermissionTree(permission);

            PermissionSection section = target is IPermissionGroup
                ? (PermissionSection) await GetConfigSectionAsync <GroupPermissionSection>(target, false)
                : await GetConfigSectionAsync <PlayerPermissionSection>(target, false);

            string[] permissions = section?.Permissions ?? new string[0];

            foreach (string permissionNode in permissionTree)
            {
                foreach (string c in permissions)
                {
                    if (c.Contains("*") && !c.StartsWith("!") && permission.StartsWith("!"))
                    {
                        continue;
                    }

                    if (c.Trim().Equals(permissionNode, StringComparison.OrdinalIgnoreCase))
                    {
                        return(PermissionResult.Grant);
                    }
                }
            }

            // check parent group permissions / player group permissions
            IEnumerable <IPermissionGroup> groups = await GetGroupsAsync(target);

            foreach (IPermissionGroup group in groups)
            {
                PermissionResult result = await CheckPermissionAsync(group, permission);

                if (result == PermissionResult.Grant)
                {
                    return(PermissionResult.Grant);
                }

                if (result == PermissionResult.Deny)
                {
                    return(PermissionResult.Deny);
                }
            }

            return(PermissionResult.Default);
        }
Пример #15
0
        public static string GetDisplayName(this IPermissionActor target)
        {
            if (target is IUser user)
            {
                return(user.DisplayName);
            }

            return(target.Id);
        }
Пример #16
0
        public Task <bool> RemoveDeniedPermissionAsync(IPermissionActor actor, string permission)
        {
            if (!(actor is IPermissionRole role))
            {
                return(Task.FromException <bool>(new NotSupportedException("Cannot remove permissions from RocketMod players.")));
            }

            return(Task.FromResult(UpdateGroupPermission(role, $"!{permission}", add: false)));
        }
        public virtual async Task <bool> RemoveRoleFromActorAsync(IPermissionActor actor, string roleId)
        {
            var userData = await m_UserDataStore.GetUserDataAsync(actor.Id, actor.Type);

            userData.Roles.Remove(roleId);
            await m_UserDataStore.SaveUserDataAsync(userData);

            return(true);
        }
        public bool SupportsTarget(IPermissionActor target)
        {
            if (target is UnturnedUser user)
            {
                return(user.Player.IsAdmin);
            }

            return(false);
        }
Пример #19
0
        public Task <bool> AddGrantedPermissionAsync(IPermissionActor actor, string permission)
        {
            if (!(actor is IPermissionRole role))
            {
                return(Task.FromException <bool>(new NotSupportedException("Cannot add permissions to RocketMod players.")));
            }

            return(Task.FromResult(UpdateGroupPermission(role, permission, add: true)));
        }
Пример #20
0
        public Task <IReadOnlyCollection <string> > GetDeniedPermissionsAsync(IPermissionActor actor, bool inherit = true)
        {
            if (!RocketModIntegrationEnabled() || !IsPlayerActor(actor.Type))
            {
                return(Task.FromResult <IReadOnlyCollection <string> >(new List <string>()));
            }

            return(Task.FromResult <IReadOnlyCollection <string> >(GetRocketModPermissions(actor, inherit, isDenied: true)));
        }
Пример #21
0
        public Task <PermissionGrantResult> CheckPermissionAsync(IPermissionActor actor, string permission)
        {
            // permission is already prefixed
            if (permission.Contains(":"))
            {
                return(m_Parent.CheckPermissionAsync(actor, permission));
            }

            return(m_Parent.CheckPermissionAsync(actor, m_Component.Value.OpenModComponentId + ":" + permission));
        }
        public async Task <IPermissionGroup> GetPrimaryGroupAsync(IPermissionActor permissionActor)
        {
            GuardLoaded();
            if (!(permissionActor is IUser))
            {
                throw new NotSupportedException();
            }

            return((await GetGroupsAsync(permissionActor)).OrderByDescending(c => c.Priority).FirstOrDefault());
        }
Пример #23
0
        protected override async Task ExecuteUpdateAsync(IPermissionActor target, string groupId)
        {
            var permissionGroup = await m_PermissionGroupStore.GetGroupAsync(groupId);

            if (permissionGroup == null)
            {
                throw new UserFriendlyException($"Permission group not found: {groupId}");
            }

            await ExecuteUpdateAsync(target, permissionGroup);
        }
 protected override async Task ExecuteUpdateAsync(IPermissionActor target, IPermissionGroup permissionGroup)
 {
     if (await m_PermissionGroupStore.RemoveGroupFromActorAsync(target, permissionGroup.Id))
     {
         await Context.Actor.PrintMessageAsync($"Removed \"{target.DisplayName}\" from \"{permissionGroup.DisplayName}\".", Color.DarkGreen);
     }
     else
     {
         await Context.Actor.PrintMessageAsync($"Failed to remove \"{target.DisplayName}\" from \"{permissionGroup.DisplayName}\".", Color.DarkRed);
     }
 }
Пример #25
0
        protected override async Task ExecuteUpdateAsync(IPermissionActor target, string roleId)
        {
            var role = await m_PermissionRoleStore.GetRoleAsync(roleId);

            if (role == null)
            {
                throw new UserFriendlyException($"Permission role not found: {roleId}");
            }

            await ExecuteUpdateAsync(target, role);
        }
Пример #26
0
 protected override async Task ExecuteUpdateAsync(IPermissionActor target, IPermissionRole permissionRole)
 {
     if (await m_PermissionRoleStore.AddRoleToActorAsync(target, permissionRole.Id))
     {
         await Context.Actor.PrintMessageAsync($"Added \"{target.DisplayName}\" to \"{permissionRole.DisplayName}\".", Color.DarkGreen);
     }
     else
     {
         await Context.Actor.PrintMessageAsync($"Failed to add \"{target.DisplayName}\" to \"{permissionRole.DisplayName}\".", Color.DarkRed);
     }
 }
        private bool DeleteConfigSection(IPermissionActor target)
        {
            IConfigurationElement config = target is IPermissionGroup
                ? GroupsConfig["Groups"]
                : PlayersConfig[((IUser)target).UserType];

            List <PermissionSection> values = config.Get <PermissionSection[]>().ToList();
            int i = values.RemoveAll(c => c.Id.Equals(target.Id, StringComparison.OrdinalIgnoreCase));

            config.Set(values);
            return(i > 0);
        }
Пример #28
0
 protected override async Task UpdatePermissionAsync(IUser user, IPermissionProvider permissions,
                                                     IPermissionActor target, string permissionToUpdate)
 {
     if (await permissions.AddPermissionAsync(target, permissionToUpdate))
     {
         await user.SendMessageAsync($"Successfully added \"{permissionToUpdate}\" to \"{target.GetDisplayName()}\"!",
                                     Color.DarkGreen);
     }
     else
     {
         await user.SendMessageAsync($"Failed to add \"{permissionToUpdate}\" to \"{target.GetDisplayName()}\"!", Color.Red);
     }
 }
        public Task <PermissionGrantResult> CheckPermissionAsync(IPermissionActor actor, string permission)
        {
            if (string.IsNullOrEmpty(permission))
            {
                return(Task.FromResult(PermissionGrantResult.Default));
            }

            permission = permission.Trim();

            var rocketPlayer = new RocketPlayer(actor.Id, actor.DisplayName);
            var permissions  = R.Permissions.GetPermissions(rocketPlayer);

            if (m_Cooldowns.TryGetValue(actor.Id, out var permissionCooldown))
            {
                if (permissionCooldown.TryGetValue(permission, out var finishDate))
                {
                    var timeLeft = (finishDate - DateTime.UtcNow).TotalSeconds;
                    if (timeLeft > 0)
                    {
                        AsyncHelper.RunSync(() =>
                                            ((IPlayerUser)actor).PrintMessageAsync(
                                                m_StringLocalizer["rocket:permissions:command_cooldown", new { TimeLeft = timeLeft }],
                                                Color.Red));
                        return(Task.FromResult(PermissionGrantResult.Deny));
                    }

                    permissionCooldown.Remove(permission);
                }
            }
            else
            {
                permissionCooldown = new Dictionary <string, DateTime>();
            }

            if (permissions.All(pm => !string.Equals(pm.Name?.Trim(), permission, StringComparison.OrdinalIgnoreCase)))
            {
                return(Task.FromResult(PermissionGrantResult.Default));
            }

            var rocketPermission = permissions.Find(knownPermission =>
                                                    string.Equals(knownPermission.Name?.Trim(), permission, StringComparison.OrdinalIgnoreCase));

            if (rocketPermission == null)
            {
                return(Task.FromResult(PermissionGrantResult.Default));
            }

            permissionCooldown[permission] = DateTime.UtcNow.AddSeconds(rocketPermission.Cooldown);
            m_Cooldowns[actor.Id]          = permissionCooldown;
            return(Task.FromResult(PermissionGrantResult.Default));
        }
Пример #30
0
        public async Task <PermissionGrantResult> CheckPermissionAsync(IPermissionActor actor, string permission)
        {
            foreach (var provider in m_PermissionCheckProviders.Where(c => c.SupportsActor(actor)))
            {
                var result = await provider.CheckPermissionAsync(actor, permission);

                if (result != PermissionGrantResult.Default)
                {
                    return(result);
                }
            }

            return(PermissionGrantResult.Default);
        }