Exemple #1
0
        public virtual async Task TestPlayerPermissions()
        {
            IPermissionChecker checker = LoadChecker();

            Assert.AreEqual(PermissionResult.Grant, await checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.Test"));
            Assert.AreEqual(PermissionResult.Deny, await checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.Test3"));
            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.NonExistantPermission"));
        }
Exemple #2
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));
        }
Exemple #3
0
        public virtual async Task TestAddPermissionToGroup()
        {
            IPermissionChecker  checker  = LoadChecker();
            IPermissionProvider provider = LoadProvider();

            IPermissionGroup group = await provider.GetGroupAsync("TestGroup2");

            await provider.AddPermissionAsync(group, "DynamicGroupPermission");

            Assert.AreEqual(PermissionResult.Grant, await checker.CheckPermissionAsync(group, "DynamicGroupPermission"));
            Assert.AreEqual(PermissionResult.Grant, await checker.CheckPermissionAsync(TestPlayer, "DynamicGroupPermission"));
        }
Exemple #4
0
        public virtual async Task TestRemovePermissionFromGroup()
        {
            IPermissionProvider provider = LoadProvider();
            IPermissionChecker  checker  = LoadChecker();

            IPermissionGroup group = await provider.GetGroupAsync("TestGroup2");

            Assert.IsTrue(await provider.RemovePermissionAsync(group, "GroupPermission2"));

            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(group, "GroupPermission2"));
            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(TestPlayer, "GroupPermission2"));
        }
        public async Task <TimeSpan?> GetLastCooldownAsync(IPlayerUser player, string kitName)
        {
            if (await m_PermissionChecker.CheckPermissionAsync(player, c_NoCooldownPermission) ==
                PermissionGrantResult.Grant ||
                !m_KitsCooldownData.KitsCooldown !.TryGetValue(player.Id, out var kitCooldowns))
            {
                return(null);
            }

            var kitCooldown = kitCooldowns !.Find(x =>
                                                  x.KitName?.Equals(kitName, StringComparison.CurrentCultureIgnoreCase) == true);

            return(kitCooldown == null ? null : DateTime.Now - kitCooldown.KitCooldown);
        }
Exemple #6
0
        public virtual async Task TestChildPermissions()
        {
            IPermissionChecker checker = LoadChecker();

            //should not be inherited
            Assert.AreEqual(PermissionResult.Default, await
                            checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.Test.ChildNode"));

            //should be inherited from PlayerPermission.Test2.*
            Assert.AreEqual(PermissionResult.Grant, await
                            checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.Test2.ChildNode"));

            //only has permission to the childs; not to the node itself
            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.Test2"));
        }
Exemple #7
0
        public async Task <DateTime?> GetLastExecutedAsync(ICommandActor actor, string command)
        {
            if (actor.Type == KnownActorTypes.Console)
            {
                return(null);
            }

            if (await m_PermissionChecker.CheckPermissionAsync(actor, "OpenMod.Core:cooldowns.immune") == PermissionGrantResult.Grant)
            {
                return(null);
            }

            await LoadPersistedRecords();

            var actorId = GetActorFullId(actor);

            if (m_Records.TryGetValue(actorId, out List <CooldownRecord> records))
            {
                var record = records.FirstOrDefault(x => x.Command == command);

                if (record != null)
                {
                    return(record.Executed);
                }
            }

            return(null);
        }
Exemple #8
0
        protected override async UniTask OnExecuteAsync()
        {
            if (Context.Parameters.Length > 0)
            {
                throw new CommandWrongUsageException(Context);
            }

            var warpsData = await m_DataStore.LoadAsync <WarpsData>(WarpsKey);

            string warps = "none";

            if (warpsData.Warps.Count != 0)
            {
                StringBuilder warpsBuilder = new StringBuilder();
                foreach (string warp in warpsData.Warps.Keys)
                {
                    if (await m_PermissionChecker.CheckPermissionAsync(Context.Actor, $"warps.{warp}") ==
                        PermissionGrantResult.Grant)
                    {
                        warpsBuilder.Append(warp + ", ");
                    }
                }

                if (warpsBuilder.Length != 0)
                {
                    warpsBuilder.Remove(warpsBuilder.Length - 2, 1);
                    warps = warpsBuilder.ToString();
                }
            }

            await Context.Actor.PrintMessageAsync(m_StringLocalizer["warps:list", new { Warps = warps }]);
        }
Exemple #9
0
        public async Task ExecuteAsync(ICommandContext context)
        {
            IUser targetPlayer = await context.Parameters.GetAsync <IUser>(0);

            string groupName = context.Parameters[1];

            string permission = "Rocket.Permissions.ManageGroups." + groupName;
            IPermissionProvider configPermissions = context.Container.Resolve <IPermissionProvider>("default_permissions");
            IPermissionChecker  permissionChecker = context.Container.Resolve <IPermissionChecker>();

            if (await permissionChecker.CheckPermissionAsync(context.User, permission) != PermissionResult.Grant)
            {
                throw new NotEnoughPermissionsException(context.User, permission,
                                                        "You don't have permissions to manage this group.");
            }

            IPermissionGroup groupToUpdate = await configPermissions.GetGroupAsync(groupName);

            if (groupToUpdate == null)
            {
                await context.User.SendMessageAsync($"Group \"{groupName}\" was not found.", Color.Red);

                return;
            }

            await UpdateGroupAsync(context.User, configPermissions, targetPlayer, groupToUpdate);
        }
Exemple #10
0
        public async Task <DateTime?> LastExecuted(ICommandActor actor, string command)
        {
            if (actor.Type == KnownActorTypes.Console)
            {
                return(null);
            }

            if (await m_PermissionChecker.CheckPermissionAsync(actor,
                                                               $"{m_PluginAccessor.Instance.OpenModComponentId}:immune") == PermissionGrantResult.Grant)
            {
                return(null);
            }

            string actorId = GetFullId(actor);

            if (m_Records.TryGetValue(actorId, out List <CooldownRecord> records))
            {
                var record = records.FirstOrDefault(x => x.Command == command);

                if (record != null)
                {
                    return(record.Executed);
                }
            }

            return((await GetPersistedRecords(actorId))?.FirstOrDefault(x => x.Command == command)?.Executed);
        }
Exemple #11
0
        public bool HasPermission(IRocketPlayer player, List <string> requestedPermissions)
        {
            if (player == null)
            {
                throw new ArgumentNullException(nameof(player));
            }

            if (requestedPermissions.Any(string.IsNullOrEmpty))
            {
                return(true);
            }

            var actor = ConvertToActor(player);

            return(AsyncHelper.RunSync(async() =>
            {
                foreach (var permission in requestedPermissions)
                {
                    var permissionRegistration = m_PermissionRegistry.FindPermission(m_RocketModComponent, permission);
                    if (permissionRegistration == null)
                    {
                        m_PermissionRegistry.RegisterPermission(m_RocketModComponent, permission);
                    }

                    if (await m_PermissionChecker.CheckPermissionAsync(actor, permission) == PermissionGrantResult.Grant)
                    {
                        return true;
                    }
                }

                return false;
            }));
        }
Exemple #12
0
 public async Task <bool> DeathShouldBeLogged(UnturnedPlayerDeadEvent @event)
 {
     if (_config.allowOtherPlayer)
     {
         return(true);
     }
     return(!_config.allowOtherPlayer && _permissionChecker.CheckPermissionAsync(@event.Player.User, "back").Result == PermissionResult.Grant);
 }
Exemple #13
0
        public virtual async Task TestRemovePermissionFromPlayer()
        {
            IPermissionChecker  checker  = LoadChecker();
            IPermissionProvider provider = LoadProvider();

            Assert.IsTrue(await provider.RemovePermissionAsync(TestPlayer, "PlayerPermission.Test"));
            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(TestPlayer, "PlayerPermission.Test"));
        }
Exemple #14
0
        protected override async UniTask OnExecuteAsync()
        {
            KitsData kitsData = await m_DataStore.LoadAsync <KitsData>(KitsKey);

            if (kitsData.Kits.Count == 0)
            {
                throw new UserFriendlyException(m_StringLocalizer["kits:none"]);
            }

            StringBuilder kitsBuilder = new StringBuilder();

            if (Context.Actor.Type == KnownActorTypes.Console)
            {
                foreach (var pair in kitsData.Kits)
                {
                    kitsBuilder.Append($"{pair.Key}, ");
                }

                // Remove trailing ", "
                kitsBuilder.Remove(kitsBuilder.Length - 2, 2);
                await Context.Actor.PrintMessageAsync(m_StringLocalizer["kits:list", new { List = kitsBuilder.ToString() }]);

                return;
            }

            foreach (var pair in kitsData.Kits)
            {
                if (await m_PermissionChecker.CheckPermissionAsync(Context.Actor, $"kits.kit.{pair.Key}") ==
                    PermissionGrantResult.Grant ||
                    await m_PermissionChecker.CheckPermissionAsync(Context.Actor, $"kits.kit.give.{pair.Key}") ==
                    PermissionGrantResult.Grant)
                {
                    kitsBuilder.Append($"{pair.Key}, ");
                }
            }

            if (kitsBuilder.Length == 0)
            {
                throw new UserFriendlyException(m_StringLocalizer["kits:none"]);
            }

            // Remove trailing ", "
            kitsBuilder.Remove(kitsBuilder.Length - 2, 2);
            await Context.Actor.PrintMessageAsync(m_StringLocalizer["kits:list", new { List = kitsBuilder.ToString() }]);
        }
            public async Task HandleEventAsync(object sender, IUserDisconnectedEvent @event)
            {
                UnturnedUser user = (UnturnedUser)@event.User;

                Jobs.Civil--;
                var medic = await ro_PermissionChecker.CheckPermissionAsync(user, ro_Configuration.GetSection("plugin_configuration:medic_permission").Get <string>());

                var police = await ro_PermissionChecker.CheckPermissionAsync(user, ro_Configuration.GetSection("plugin_configuration:police_permission").Get <string>());

                if (medic == PermissionGrantResult.Grant && !user.Player.Player.channel.owner.isAdmin && Jobs.Medic > 0)
                {
                    Jobs.Medic--;
                }
                if (police == PermissionGrantResult.Grant && !user.Player.Player.channel.owner.isAdmin && Jobs.Police > 0)
                {
                    Jobs.Police--;
                }
            }
Exemple #16
0
        public async Task GiveKitAsync(IPlayerUser user, string name, ICommandActor?instigator = null,
                                       bool forceGiveKit = false)
        {
            var kit = await m_KitStore.FindKitByNameAsync(name);

            if (kit == null)
            {
                throw new UserFriendlyException(m_StringLocalizer["commands:kit:notFound", new { Name = name }]);
            }

            if (!forceGiveKit && await m_PermissionChecker.CheckPermissionAsync(user,
                                                                                $"{KitDatabaseManager.c_KitsKey}.{kit.Name}") != PermissionGrantResult.Grant)
            {
                throw new UserFriendlyException(m_StringLocalizer["commands:kit:noPermission", new { Kit = kit }]);
            }

            var cooldown = await m_KitCooldownStore.GetLastCooldownAsync(user, name);

            if (!forceGiveKit && cooldown != null)
            {
                if (cooldown.Value.TotalSeconds < kit.Cooldown)
                {
                    throw new UserFriendlyException(m_StringLocalizer["commands:kit:cooldown",
                                                                      new { Kit = kit, Cooldown = kit.Cooldown - cooldown.Value.TotalSeconds }]);
                }
            }

            if (!forceGiveKit && kit.Cost != 0)
            {
                await m_EconomyProvider.UpdateBalanceAsync(user.Id, user.Type, -kit.Cost,
                                                           m_StringLocalizer["commands:kit:balanceUpdateReason:buy", new { Kit = kit }]);
            }

            await m_KitCooldownStore.RegisterCooldownAsync(user, name, DateTime.Now);

            await kit.GiveKitToPlayer(user, m_ServiceProvider);

            await user.PrintMessageAsync(m_StringLocalizer["commands:kit:success", new { Kit = kit }]);

            if (instigator != null)
            {
                await instigator.PrintMessageAsync(m_StringLocalizer["commands:kit:success", new { Kit = kit }]);
            }
        }
        public async Task ExecuteAsync(ICommandContext context)
        {
            if (context.Parameters.Length != 3)
            {
                throw new CommandWrongUsageException();
            }

            IPermissionEntity target;
            string            permission;
            string            permissionFailMessage;

            string type               = context.Parameters[0].ToLower();
            string targetName         = context.Parameters[1];
            string permissionToUpdate = context.Parameters[2];

            IPermissionProvider configPermissions = context.Container.Resolve <IPermissionProvider>("default_permissions");
            IPermissionChecker  permissionChecker = context.Container.Resolve <IPermissionChecker>();

            switch (type)
            {
            case "g":
            case "group":
                permission            = "Rocket.Permissions.ManageGroups." + targetName;
                permissionFailMessage = "You don't have permissions to manage this group.";

                target = await configPermissions.GetGroupAsync(targetName);

                if (target == null)
                {
                    await context.User.SendMessageAsync($"Group \"{targetName}\" was not found.", Color.Red);

                    return;
                }

                break;

            case "p":
            case "player":
                permission            = "Rocket.Permissions.ManagePlayers";
                permissionFailMessage = "You don't have permissions to manage permissions of players.";
                target = await context.Parameters.GetAsync <IUser>(1);

                break;

            default:
                throw new CommandWrongUsageException();
            }

            if (await permissionChecker.CheckPermissionAsync(context.User, permission) != PermissionResult.Grant)
            {
                throw new NotEnoughPermissionsException(context.User, permission, permissionFailMessage);
            }

            await UpdatePermissionAsync(context.User, configPermissions, target, permissionToUpdate);
        }
Exemple #18
0
        public async Task <double?> OnCooldownAsync(UserBase user, string sessionKey, string cooldownName, int cooldown)
        {
            // If there is a non-zero cooldown and the user is not exempt from cooldowns
            // Then we will add a cooldown to them for this specific kit/warp/etc
            // Unless they are already under a cooldown, in which we will return the remaining cooldown
            if (cooldown == 0 || await m_PermissionChecker.CheckPermissionAsync(user, $"{sessionKey}.cooldowns.exempt") != PermissionGrantResult.Deny)
            {
                return(null);
            }

            var key = $"{sessionKey}.cooldowns.{cooldownName}";

            var now = DateTime.Now;

            var cooldowns = new Dictionary <string, DateTime>();

            switch (await user.GetPersistentDataAsync <object>(CooldownsDataKey))
            {
            case Dictionary <string, DateTime> dict:
                cooldowns = dict;
                break;

            case Dictionary <object, object> dict:
                cooldowns = dict.Select(x =>
                                        new KeyValuePair <string, DateTime>(x.Key.ToString(), DateTime.Parse(x.Value.ToString())))
                            .ToDictionary(x => x.Key, y => y.Value);
                break;

                /*case Dictionary<string, string> dict:
                 *  cooldowns = dict.Select(x =>
                 *          new KeyValuePair<string, DateTime>(x.Key, DateTime.Parse(x.Value)))
                 *      .ToDictionary(x => x.Key, y => y.Value);
                 *  break;*/
            }

            if (cooldowns.TryGetValue(key, out var lastUse))
            {
                var secondsSinceLastUse = (now - lastUse).TotalSeconds;

                if (secondsSinceLastUse < cooldown)
                {
                    return(Math.Round(cooldown - secondsSinceLastUse, 2));
                }

                cooldowns[key] = now;
            }
            else
            {
                cooldowns.Add(key, now);
            }

            await user.SavePersistentDataAsync(CooldownsDataKey, cooldowns);

            return(null);
        }
Exemple #19
0
        public virtual Task <PermissionGrantResult> CheckPermissionAsync(string permission)
        {
            string prefix = "";

            if (!string.IsNullOrEmpty(m_CommandPermission))
            {
                prefix = m_CommandPermission + ".";
            }

            return(m_PermissionChecker.CheckPermissionAsync(Context.Actor, prefix + permission));
        }
Exemple #20
0
        protected override async UniTask OnExecuteAsync()
        {
            if (Context.Parameters.Length != 1)
            {
                throw new CommandWrongUsageException(Context);
            }

            var warpsData = await m_DataStore.LoadAsync <WarpsData>(WarpsKey);

            string searchTerm = Context.Parameters[0];

            if (!warpsData.Warps.ContainsKey(searchTerm))
            {
                throw new UserFriendlyException(m_StringLocalizer["warps:none", new { Warp = searchTerm }]);
            }

            if (await m_PermissionChecker.CheckPermissionAsync(Context.Actor, $"warps.{searchTerm}") == PermissionGrantResult.Deny)
            {
                throw new UserFriendlyException(m_StringLocalizer["warps:no_permission", new { Warp = searchTerm }]);
            }

            UnturnedUser uPlayer = (UnturnedUser)Context.Actor;
            var          warp    = warpsData.Warps[searchTerm];

            double?cooldown = await m_CooldownManager.OnCooldownAsync(uPlayer, "warps", searchTerm, warp.Cooldown);

            if (cooldown.HasValue)
            {
                throw new UserFriendlyException(m_StringLocalizer["warps:cooldown", new { Time = cooldown, Warp = searchTerm }]);
            }

            // Delay warping so that they cannot escape combat
            int  delay          = m_Configuration.GetValue <int>("teleportation:delay");
            bool cancelOnMove   = m_Configuration.GetValue <bool>("teleportation:cancelOnMove");
            bool cancelOnDamage = m_Configuration.GetValue <bool>("teleportation:cancelOnDamage");

            // Tell the player of the delay and not to move
            await uPlayer.PrintMessageAsync(m_StringLocalizer["warps:success", new { Warp = searchTerm, Time = delay }]);

            bool success = await m_TeleportService.TeleportAsync(uPlayer, new TeleportOptions(m_PluginAccessor.Instance, delay, cancelOnMove, cancelOnDamage));

            if (!success)
            {
                throw new UserFriendlyException(m_StringLocalizer["teleport:canceled"]);
            }

            await UniTask.SwitchToMainThread();

            uPlayer.Player.Player.teleportToLocation(warp.Location.ToUnityVector3(),
                                                     uPlayer.Player.Player.transform.eulerAngles.y);
        }
Exemple #21
0
        protected override async Task OnExecuteAsync()
        {
            var commands = await m_CommandStore.GetCommandsAsync();

            var totalCount = commands.Count;

            const int itemsPerPage = 10;

            int currentPage = 1;

            if (Context.Parameters.Length == 0 || Context.Parameters.TryGet(0, out currentPage))
            {
                if (currentPage < 1)
                {
                    throw new CommandWrongUsageException(Context);
                }

                var pageCommands = commands
                                   .Where(d => d.ParentId == null)
                                   .Skip(itemsPerPage * (currentPage - 1))
                                   .Take(itemsPerPage)
                                   .ToList();

                await PrintPageAsync(currentPage, (int)Math.Ceiling((double)totalCount / itemsPerPage), pageCommands);
            }
            else if (Context.Parameters.Length > 0)
            {
                var context    = m_CommandContextBuilder.CreateContext(Context.Actor, Context.Parameters.ToArray(), Context.CommandPrefix, commands);
                var permission = GetPermission(context.CommandRegistration, commands);

                if (context.CommandRegistration == null)
                {
                    await Context.Actor.PrintMessageAsync(m_StringLocalizer["commands:errors:not_found", new { CommandName = context.GetCommandLine(false) }], Color.Red);

                    return;
                }

                if (!string.IsNullOrEmpty(permission) && await m_PermissionChecker.CheckPermissionAsync(Context.Actor, permission) != PermissionGrantResult.Grant)
                {
                    throw new NotEnoughPermissionException(m_StringLocalizer, permission);
                }

                await PrintCommandHelpAsync(context, permission, commands);

                await context.DisposeAsync();
            }
        }
Exemple #22
0
        public bool HasPermission(IRocketPlayer player, List <string> requestedPermissions)
        {
            var actor = ConvertToActor(player);

            return(AsyncHelper.RunSync(async() =>
            {
                foreach (var permission in requestedPermissions)
                {
                    if (await m_PermissionChecker.CheckPermissionAsync(actor, permission) != PermissionGrantResult.Grant)
                    {
                        return false;
                    }
                }

                return true;
            }));
        }
Exemple #23
0
        public virtual async Task TestGroupPermissions()
        {
            IPermissionChecker  checker  = LoadChecker();
            IPermissionProvider provider = LoadProvider();

            IPermissionGroup group = await provider.GetGroupAsync("TestGroup2");

            Assert.AreEqual(PermissionResult.Default, await
                            checker.CheckPermissionAsync(TestPlayer,
                                                         "GroupPermission1")); // permission of a group the player doesnt belong to
            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(TestPlayer, "NonExistantPermission"));
            Assert.AreEqual(PermissionResult.Grant, await checker.CheckPermissionAsync(TestPlayer, "GroupPermission2"));
            Assert.AreEqual(PermissionResult.Deny, await checker.CheckPermissionAsync(TestPlayer, "GroupPermission3"));

            Assert.AreEqual(PermissionResult.Default, await checker.CheckPermissionAsync(group, "NonExistantPermission"));
            Assert.AreEqual(PermissionResult.Grant, await checker.CheckPermissionAsync(group, "GroupPermission2"));
            Assert.AreEqual(PermissionResult.Deny, await checker.CheckPermissionAsync(group, "GroupPermission3"));
        }
        public async Task ExecuteAsync(ICommandContext context)
        {
            IPermissionChecker     permissions  = context.Container.Resolve <IPermissionChecker>();
            ITranslationCollection translations = ((RocketUnturnedHost)context.Container.Resolve <IHost>()).ModuleTranslations;

            IPlayer target;

            if (await permissions.CheckPermissionAsync(context.User, Permission + ".Others") == PermissionResult.Grant &&
                context.Parameters.Length >= 1)
            {
                target = await context.Parameters.GetAsync <IPlayer>(0);
            }
            else
            {
                target = ((UnturnedUser)context.User).Player;
            }

            if (!(target is UnturnedPlayer uPlayer))
            {
                await context.User.SendMessageAsync($"Could not heal {target.User.DisplayName}", ConsoleColor.Red);

                return;
            }

            uPlayer.Entity.Heal(100);
            uPlayer.Entity.Bleeding  = false;
            uPlayer.Entity.Broken    = false;
            uPlayer.Entity.Infection = 0;
            uPlayer.Entity.Hunger    = 0;
            uPlayer.Entity.Thirst    = 0;

            if (target == context.User)
            {
                await context.User.SendLocalizedMessageAsync(translations, "command_heal_success");

                return;
            }

            await context.User.SendLocalizedMessageAsync(translations, "command_heal_success_me", null, target.User.DisplayName);

            await target.User.SendLocalizedMessageAsync(translations, "command_heal_success_other", null, context.User.DisplayName);
        }
Exemple #25
0
        /// <summary>
        ///     Checks if the target has all of the given permissions.
        /// </summary>
        /// <param name="permissionChecker">The permission checker.</param>
        /// <param name="target">The target to check.</param>
        /// <param name="permissions">The permissions to check.</param>
        /// <returns>
        ///     <see cref="PermissionResult.Grant" /> if the target explicity has access to all of the given permissions,
        ///     <see cref="PermissionResult.Deny" /> if the target explicitly does not have access to any of the permissions;
        ///     otherwise, <see cref="PermissionResult.Default" />
        /// </returns>
        public static async Task <PermissionResult> CheckHasAllPermissionsAsync(this IPermissionChecker permissionChecker, IPermissionActor target, params string[] permissions)
        {
            PermissionResult result = PermissionResult.Grant;

            foreach (string permission in permissions)
            {
                PermissionResult tmp = await permissionChecker.CheckPermissionAsync(target, permission);

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

                if (tmp == PermissionResult.Default)
                {
                    result = PermissionResult.Default;
                }
            }

            return(result);
        }
Exemple #26
0
        /// <summary>
        ///     Checks if the target has any of the given permissions.
        /// </summary>
        /// <param name="permissionChecker">The permission checker.</param>
        /// <param name="target">The target to check.</param>
        /// <param name="permissions">The permissions to check.</param>
        /// <returns>
        ///     <see cref="PermissionResult.Grant" /> if the target explicity has access to any of the given permissions,
        ///     <see cref="PermissionResult.Deny" /> if the target explicitly does not have access to any of the permissions;
        ///     otherwise, <see cref="PermissionResult.Default" />
        /// </returns>
        public static async Task <PermissionResult> CheckHasAnyPermissionAsync(this IPermissionChecker permissionChecker, IPermissionActor target, params string[] permissions)
        {
            foreach (string permission in permissions)
            {
                Console.WriteLine("Checking: " + permission);

                PermissionResult result = await permissionChecker.CheckPermissionAsync(target, permission);

                if (result == PermissionResult.Deny)
                {
                    Console.WriteLine("Denied: " + permission);
                    return(PermissionResult.Deny);
                }
                if (result == PermissionResult.Grant)
                {
                    Console.WriteLine("Granted: " + permission);
                    return(PermissionResult.Grant);
                }
            }

            Console.WriteLine("Default: " + permissions);
            return(PermissionResult.Default);
        }
Exemple #27
0
        public async Task ExecuteAsync(ICommandContext context)
        {
            PermissionResult permResult = await _permissionChecker.CheckPermissionAsync(context.User, "back");

            IUser target;
            bool  otherUser;

            if (context.Parameters.Length >= 1 && _config.allowOtherPlayer)
            {
                target = await context.Parameters.GetAsync <IUser>(0);

                otherUser = true;
            }
            else
            {
                if (context.Parameters.Length >= 1 && !_config.allowOtherPlayer)
                {
                    await context.User.SendMessageAsync("Other user functionality is disabled in the config");

                    return;
                }
                else
                {
                    target    = context.User;
                    otherUser = false;
                }
            }

            if (!(target is IUser paramType))
            {
                await context.User.SendMessageAsync("Invalid parameter");

                return;
            }

            UnturnedPlayer player = ((UnturnedUser)target).Player;

            switch (permResult)
            {
            case PermissionResult.Grant:
                if (_eventHandler.deaths.ContainsKey(target))
                {
                    await player.Entity.TeleportAsync(_eventHandler.deaths[target], player.Entity.Rotation);

                    await context.User.SendMessageAsync("You have been teleported back to your last death");
                }
                else
                {
                    if (otherUser)
                    {
                        await context.User.SendMessageAsync("This player hasn't died yet!");
                    }
                    else
                    {
                        await context.User.SendMessageAsync("You haven't died yet!");
                    }
                }
                break;

            case PermissionResult.Deny:
                await context.User.SendMessageAsync("You do not have permission to use this command!");     //I swear there was a built in way for this?

                break;

            case PermissionResult.Default:
                await context.User.SendMessageAsync("You do not have permission to use this command!");

                break;
            }
        }
        protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer,
                                                             IWebSocketReceiveResult result)
        {
            _logger.LogDebug($"Received {buffer.Length} bytes.");
            _logger.LogDebug(System.Text.Encoding.UTF8.GetString(buffer));
            _logger.LogDebug(string.Join(" ", buffer.Select(d => d.ToString("X"))));

            if (buffer.Length < 1)
            {
                return;
            }

            var type = buffer[0];

            switch (type)
            {
            case PacketAuthenticate:
            {
                if (context.Items.ContainsKey("user"))
                {
                    return;
                }

                var token = System.Text.Encoding.UTF8.GetString(buffer, 1, buffer.Length - 1);
                if (string.IsNullOrEmpty(token))
                {
                    _logger.LogDebug($"Closing socket.Invalid token: {token}.");
                    await CloseAsync(context);

                    return;
                }

                var user = await _authenticationService.AuthenticateAsync(token);

                if (user == null)
                {
                    _logger.LogDebug("Closing socket. User could not authenticate.");
                    await CloseAsync(context);

                    return;
                }

                if (await _permissionChecker.CheckPermissionAsync(user, PermissionAccessConsole) !=
                    PermissionGrantResult.Grant)
                {
                    _logger.LogDebug("Closing socket. User does not have permission.");

                    var msg = SerializeMessage(PacketMessage, new LogMessageDto
                        {
                            Message = $"Missing \"OpenMod.WebServer:{PermissionAccessConsole}\" permission to access console."
                        });

                    await SendAsync(context, msg);
                    await CloseAsync(context);

                    return;
                }

                var canReadLogs = false;         // await _permissionChecker.CheckPermissionAsync(user, PermissionAccessLogs) == PermissionGrantResult.Grant;
                context.Items.Add("user", canReadLogs ? user : new WebConsoleUser(user, context, this));
                context.Items.Add("canReadLogs", canReadLogs);

                _logger.LogDebug($"User accepted: {user.FullActorName} (canReadLogs: {canReadLogs})");
                break;
            }

            case PacketMessage:
            {
                if (!context.Items.ContainsKey("user"))
                {
                    _logger.LogDebug("Closing socket. User not authenticated.");
                    await CloseAsync(context);

                    return;
                }

                var user    = (IUser)context.Items["user"];
                var message = System.Text.Encoding.UTF8.GetString(buffer, 1, buffer.Length - 1);
                var args    = ArgumentsParser.ParseArguments(message);

                await _commandExecutor.ExecuteAsync(user, args, string.Empty);

                break;
            }
            }
        }
        protected override async Task OnExecuteAsync()
        {
            if (Context.Parameters.Length != 3)
            {
                throw new CommandWrongUsageException(Context);
            }

            IPermissionActor target;

            var actorType          = Context.Parameters[0].ToLower();
            var permission         = "permissions.manage." + actorType;
            var targetName         = Context.Parameters[1];
            var permissionToUpdate = Context.Parameters[2];

            switch (actorType)
            {
            case "r":
            case "role":
                permission = "permissions.manage.roles." + targetName;
                target     = await m_PermissionRoleStore.GetRoleAsync(targetName);

                // todo: register on startup instead of here so it can get written to a help file
                m_PermissionRegistry.RegisterPermission(Context.CommandRegistration.Component, permission, description: $"Manage role: {targetName}");

                if (target == null)
                {
                    await Context.Actor.PrintMessageAsync($"Role \"{targetName}\" was not found.", Color.Red);

                    return;
                }

                break;

            case "p":
            case "player":
                permission = "permissions.manage.players";
                actorType  = KnownActorTypes.Player;
                goto default;

            default:
                var idOrName = await Context.Parameters.GetAsync <string>(1);

                var user = await m_UserManager.FindUserAsync(actorType, idOrName, UserSearchMode.NameOrId);

                m_PermissionRegistry.RegisterPermission(Context.CommandRegistration.Component, permission, description: $"Manage actor: {actorType}");

                if (user == null)
                {
                    // todo: make localizable
                    throw new UserFriendlyException($"Player not found: {idOrName}");
                }

                var userData = await m_UserDataStore.GetUserDataAsync(user.Id, actorType);

                target = (UserDataPermissionActor)userData;
                break;
            }

            // we call m_PermissionChecker from here so the permission will become OpenMod.Core.manage.players instead of
            if (await m_PermissionChecker.CheckPermissionAsync(Context.Actor, permission) != PermissionGrantResult.Grant)
            {
                throw new NotEnoughPermissionException(Context, permission);
            }

            await ExecuteUpdateAsync(target, permissionToUpdate);
        }
Exemple #30
0
        private async UniTask CheckAfkPlayers()
        {
            if (Provider.isServer)
            {
                await SyncPlayers();
            }

            while (m_ServiceRunning)
            {
                await UniTask.SwitchToThreadPool();

                await UniTask.Delay(10000);

                var timeout  = m_Configuration.GetSection("afkchecker:timeout").Get <int>();
                var announce = m_Configuration.GetSection("afkchecker:announceAFK").Get <bool>();
                var kick     = m_Configuration.GetSection("afkchecker:kickAFK").Get <bool>();

                if (timeout < 0 || (!kick && !announce))
                {
                    continue;
                }

                foreach (var user in m_UnturnedUserDirectory.GetOnlineUsers().ToList())
                {
                    if (!user.Session.SessionData.TryGetValue("lastMovement", out object @time) || @time is not TimeSpan span)
                    {
                        continue;
                    }

                    bool afk = (DateTime.Now.TimeOfDay - span).TotalSeconds >= timeout &&
                               await m_PermissionChecker.CheckPermissionAsync(user, "afkchecker.exempt") != PermissionGrantResult.Grant;

                    if (!afk)
                    {
                        user.Session.SessionData["isAfk"] = false;
                        continue;
                    }

                    if (!user.Session.SessionData.TryGetValue("isAfk", out var unparsedAfk) || unparsedAfk is not bool isAfk)
                    {
                        continue;
                    }

                    // todo: add announceTime and kickTime (not just timeout)

                    if (announce && !isAfk)
                    {
                        await user.Provider?.BroadcastAsync(m_StringLocalizer["afk:announcement", new { Player = user.DisplayName }],
                                                            Color.White);
                    }

                    if (kick)
                    {
                        await user.Session?.DisconnectAsync(m_StringLocalizer["afk:kicked"]);

                        continue;
                    }

                    user.Session.SessionData["isAfk"] = true;
                }
            }
        }