Exemple #1
0
        /// <summary>
        /// Converts the string representation of a PermissionLevel to its PermissionLevel equivalent.
        /// This fails if a valid permission level isn't found.
        /// </summary>
        /// <param name="levelStr">The string to convert.</param>
        /// <param name="permLevel">The PermissionLevel returned. Defaults to <see cref="PermissionLevels.User" /> if not found.</param>
        /// <returns>A bool indicating if the conversion was successful.</returns>
        public static bool TryParsePermissionLevel(string levelStr, out PermissionLevels permLevel)
        {
            //Try to parse into a number
            if (long.TryParse(levelStr, out long levelNum) == false)
            {
                //Failed to parse into a number, so check if the string passed in is a valid name
                if (Enum.TryParse <PermissionLevels>(levelStr, true, out PermissionLevels result) == false)
                {
                    permLevel = PermissionLevels.User;
                    return(false);
                }

                permLevel = result;
                return(true);
            }

            //Check if the given number matches any of these values
            PermissionLevels[] levelArray = EnumUtility.GetValues <PermissionLevels> .EnumValues;

            for (int i = 0; i < levelArray.Length; i++)
            {
                long lvlVal = (long)levelArray[i];

                //Check if the values match
                if (levelNum == lvlVal)
                {
                    permLevel = levelArray[i];
                    return(true);
                }
            }

            permLevel = PermissionLevels.User;
            return(false);
        }
			private FieldDescriptionPlus(FieldDescription fldDsc)
			{
				if (fldDsc == null) return;
				var mbc = MetaBriefcase.OpenInstance;
				if (mbc == null) return;

				_fieldDescription = fldDsc;
				var catsWhereThisFieldWasAssignedBefore = mbc.Categories.Where(cat => cat != null && cat.FieldDescriptionIds != null && cat.Id != null
					&& (fldDsc.JustAssignedToCats == null || !fldDsc.JustAssignedToCats.Contains(cat.Id)) && cat.FieldDescriptionIds.Contains(fldDsc.Id));

				if (catsWhereThisFieldWasAssignedBefore?.Any() == true)
				{
					if (GetIsElevated()) _isAllowDelete = PermissionLevels.WithCaution;
				}
				else _isAllowDelete = PermissionLevels.Yes;

				string currCatId = mbc.CurrentCategoryId;
				if (!string.IsNullOrEmpty(currCatId))
				{
					if (fldDsc.JustAssignedToCats.Contains(currCatId)) _isAllowUnassign = PermissionLevels.Yes;
					else
					{
						if (GetIsElevated()) _isAllowUnassign = PermissionLevels.WithCaution;
					}
				}
				else _isAllowUnassign = PermissionLevels.Yes;
			}
Exemple #3
0
 public static bool IsPermitted(ulong userId, ulong guildId, PermissionLevels level)
 {
     try
     {
         return(GetPermissions(userId, guildId) >= level);
     }
     catch
     {
         return(false);
     }
 }
Exemple #4
0
        public async Task <List <UserProfile> > GetUsersByPermissionLevelAsync(PermissionLevels permissionLevels)
        {
            var permission = (int)permissionLevels;

            using (var context = ServiceProvider.CreateScope())
            {
                var db = context.ServiceProvider.GetRequiredService <GretaDBContext>();

                return(await db.UserProfile.Where(u => u.Permission == permission && u.BotUserId != null).ToListAsync());
            }
        }
Exemple #5
0
        public string[] GetPermissionLevels(string currentUserName = null)
        {
            if (!string.IsNullOrEmpty(currentUserName))
            {
                string[] roles = GetUserRoles(currentUserName);

                if (roles.Contains(PermissionLevels.Administrator))
                {
                    return(roles);
                }
            }

            return(PermissionLevels.GetPermissionLevels());
        }
Exemple #6
0
            public override async Task <bool> CheckCondition(CommandFunction func, IMessageCreatedEvent context, ICommandConditionProvider provider)
            {
                var attribute = (CommandPermissionRequired)provider;

                var db = context.Db;

                if (context.Guild is not null)
                {
                    db.Entry(context.Guild).Collection(g => g.PermissionLevels).LoadAsync().Wait();

                    //var member = await ((DiscordMessageCreatedEvent)context)[email protected](ulong.Parse(context.Author.UserID));

                    var DGuild = await _bot.Client.GetGuildAsync(new Snowflake(context.Guild.GuildID));


                    PermissionLevels memberLevel = PermissionLevels.None;

                    if (context.Author.UserID == _conf.Value.Owner ||
                        context.Author.UserID == DGuild.OwnerId.ToString())
                    {
                        memberLevel = PermissionLevels.Owner;
                    }

                    var member = await DGuild.GetMemberAsync(new Snowflake(context.Author.UserID));

                    foreach (var guildLevel in context.Guild.PermissionLevels)
                    {
                        if (member.Roles.Any(r => r.Id.ToString() == guildLevel.RoleID))
                        {
                            if (guildLevel.PermissionLevel > memberLevel)
                            {
                                memberLevel = guildLevel.PermissionLevel;
                            }
                        }
                    }

                    if (attribute._permission > memberLevel)
                    {
                        context.RespondError($"You do not have the needed permissions. \n You must be {attribute._permission.ToString()} or above");
                        return(false);
                    }

                    return(true);
                }

                return(false);
            }
Exemple #7
0
        public string[] GetUserRoles(string userName)
        {
            IList <Role>  userRoles = userRepository.GetUserRoles(userName);
            List <string> roles     = new List <string>();

            foreach (Role role in userRoles)
            {
                string[] permissions = role.PermissionLevels.Split(new char[] { ',' });

                //Administrator will have all the permissions
                if (permissions.Contains(PermissionLevels.Administrator))
                {
                    roles = new List <string>(PermissionLevels.GetPermissionLevels());
                    roles.Add(PermissionLevels.Administrator);
                    break;
                }

                roles.AddRange(permissions);
            }

            return(roles.Distinct().ToArray());
        }
        /// <summary>
        /// Modifies the permissions associated with a folder.
        /// </summary>
        /// <param name="serverId">The server id</param>
        /// <param name="folderHandleIndex">index of folder handle in container</param>
        /// <param name="permissionLevel">The permission level</param>
        /// <returns>Indicate the result of this ROP operation.</returns>
        public RopResult ModifyPermissions(int serverId, int folderHandleIndex, PermissionLevels permissionLevel)
        {
            // Initialize ROP data.
            RopResult result = RopResult.InvalidParameter;
            uint folderHandle = this.handleContainer[folderHandleIndex];

            // Add Administrator user into permission list of the specific folder.
            TaggedPropertyValue[] taggedProperties = new TaggedPropertyValue[2];

            // EntryId
            TaggedPropertyValue propertyValueEntryId = new TaggedPropertyValue
            {
                PropertyTag = new PropertyTag(0x0FFF, 0x0102)
            };
            string userDN = Common.GetConfigurationPropertyValue("AdminUserESSDN", this.Site);
            AddressBookEntryId addressEntryId = new AddressBookEntryId(userDN);
            propertyValueEntryId.Value = Common.AddInt16LengthBeforeBinaryArray(addressEntryId.Serialize());
            taggedProperties[0] = propertyValueEntryId;

            // PidTagMemberRights
            TaggedPropertyValue propertyValueMemberRight = new TaggedPropertyValue
            {
                PropertyTag = new PropertyTag(0x6673, 0x0003),
                Value = BitConverter.GetBytes((uint)permissionLevel)
            };

            // Set permission.
            taggedProperties[1] = propertyValueMemberRight;
            PermissionData[] permissionsDataArray = new PermissionData[1];

            // Add row
            permissionsDataArray[0].PermissionDataFlags = (byte)0x01;
            permissionsDataArray[0].PropertyValueCount = (ushort)taggedProperties.Length;
            permissionsDataArray[0].PropertyValues = taggedProperties;

            // Construct ROP request.
            RopModifyPermissionsRequest modifyPermission = new RopModifyPermissionsRequest
            {
                RopId = 0x40,
                LogonId = 0x00,
                InputHandleIndex = 0x00,
                ModifyFlags = (byte)ModifyFlags.IncludeFreeBusy,
                ModifyCount = 0x01,
                PermissionsData = permissionsDataArray
            };

            // Send request and get response.
            RopModifyPermissionsResponse modifyPermissionresponse = (RopModifyPermissionsResponse)this.Process(serverId, modifyPermission, folderHandle);
            result = (RopResult)modifyPermissionresponse.ReturnValue;
            if (result == RopResult.Success)
            {
                this.currentPermission = permissionLevel;
                if (permissionLevel == PermissionLevels.None)
                {
                    // If the specific folder's permission is None, set existNoPermissionFolder as true to make client has no permission to access this folder now
                    this.existNoPermissionFolder = true;
                }
            }

            return result;
        }
Exemple #9
0
 public CommandPermissionRequired(PermissionLevels permission)
 {
     this._permission = permission;
 }
Exemple #10
0
        private void ProcessMsgAsInput(EvtUserMessageArgs e)
        {
            //Ignore commands as inputs
            if (e.UsrMessage.Message.StartsWith(DataConstants.COMMAND_IDENTIFIER) == true)
            {
                return;
            }

            GameConsole usedConsole = null;

            int lastConsoleID = 1;

            using (BotDBContext context = DatabaseManager.OpenContext())
            {
                lastConsoleID = (int)DataHelper.GetSettingIntNoOpen(SettingsConstants.LAST_CONSOLE, context, 1L);
                GameConsole lastConsole = context.Consoles.FirstOrDefault(c => c.ID == lastConsoleID);

                if (lastConsole != null)
                {
                    //Create a new console using data from the database
                    usedConsole = new GameConsole(lastConsole.Name, lastConsole.InputList, lastConsole.InvalidCombos);
                }
            }

            //If there are no valid inputs, don't attempt to parse
            if (usedConsole == null)
            {
                MsgHandler.QueueMessage($"The current console does not point to valid data. Please set a different console to use, or if none are available, add one.");
                return;
            }

            if (usedConsole.ConsoleInputs.Count == 0)
            {
                MsgHandler.QueueMessage($"The current console, \"{usedConsole.Name}\", does not have any available inputs.");
            }

            ParsedInputSequence inputSequence = default;
            string userName    = e.UsrMessage.Username;
            int    defaultDur  = 200;
            int    defaultPort = 0;

            try
            {
                int maxDur = 60000;

                string regexStr = usedConsole.InputRegex;

                string readyMessage = string.Empty;

                //Get default and max input durations
                //Use user overrides if they exist, otherwise use the global values
                User user = DataHelper.GetUser(userName);

                //Get default controller port
                defaultPort = (int)user.ControllerPort;

                defaultDur = (int)DataHelper.GetUserOrGlobalDefaultInputDur(userName);
                maxDur     = (int)DataHelper.GetUserOrGlobalMaxInputDur(userName);

                //TRBotLogger.Logger.Information($"Default dur: {defaultDur} | Max dur: {maxDur}");

                using (BotDBContext context = DatabaseManager.OpenContext())
                {
                    //Get input synonyms for this console
                    IQueryable <InputSynonym> synonyms = context.InputSynonyms.Where(syn => syn.ConsoleID == lastConsoleID);

                    //Prepare the message for parsing
                    readyMessage = InputParser.PrepParse(e.UsrMessage.Message, context.Macros, synonyms);
                }

                //Parse inputs to get our parsed input sequence
                inputSequence = InputParser.ParseInputs(readyMessage, regexStr, new ParserOptions(defaultPort, defaultDur, true, maxDur));
                TRBotLogger.Logger.Debug(inputSequence.ToString());
                TRBotLogger.Logger.Debug("Reverse Parsed (on parse): " + ReverseParser.ReverseParse(inputSequence, usedConsole,
                                                                                                    new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowNonDefaultPorts, defaultPort,
                                                                                                                                           ReverseParser.ShowDurationTypes.ShowNonDefaultDurations, defaultDur)));
            }
            catch (Exception exception)
            {
                string excMsg = exception.Message;

                //Handle parsing exceptions
                MsgHandler.QueueMessage($"ERROR PARSING: {excMsg} | {exception.StackTrace}", Serilog.Events.LogEventLevel.Warning);
                inputSequence.ParsedInputResult = ParsedInputResults.Invalid;
            }

            //Check for non-valid messages
            if (inputSequence.ParsedInputResult != ParsedInputResults.Valid)
            {
                //Display error message for invalid inputs
                if (inputSequence.ParsedInputResult == ParsedInputResults.Invalid)
                {
                    MsgHandler.QueueMessage(inputSequence.Error);
                }

                return;
            }

            #region Parser Post-Process Validation

            /* All this validation may be able to be performed faster.
             * Find a way to speed it up.
             */

            long globalInputPermLevel = DataHelper.GetSettingInt(SettingsConstants.GLOBAL_INPUT_LEVEL, 0L);
            int  userControllerPort   = 0;
            long userLevel            = 0;

            using (BotDBContext context = DatabaseManager.OpenContext())
            {
                User user = DataHelper.GetUserNoOpen(e.UsrMessage.Username, context);

                //Check if the user is silenced and ignore the message if so
                if (user.HasEnabledAbility(PermissionConstants.SILENCED_ABILITY) == true)
                {
                    return;
                }

                //Ignore based on user level and permissions
                if (user.Level < globalInputPermLevel)
                {
                    MsgHandler.QueueMessage($"Inputs are restricted to levels {(PermissionLevels)globalInputPermLevel} and above.");
                    return;
                }

                userControllerPort = (int)user.ControllerPort;
                userLevel          = user.Level;
            }

            //First, add delays between inputs if we should
            //We do this first so we can validate the inserted inputs later
            //The blank inputs can have a different permission level
            if (DataHelper.GetUserOrGlobalMidInputDelay(e.UsrMessage.Username, out long midInputDelay) == true)
            {
                MidInputDelayData midInputDelayData = ParserPostProcess.InsertMidInputDelays(inputSequence, userControllerPort, (int)midInputDelay, usedConsole);

                //If it's successful, replace the input list and duration
                if (midInputDelayData.Success == true)
                {
                    int oldDur = inputSequence.TotalDuration;
                    inputSequence.Inputs        = midInputDelayData.NewInputs;
                    inputSequence.TotalDuration = midInputDelayData.NewTotalDuration;

                    //TRBotLogger.Logger.Debug($"Mid input delay success. Message: {midInputDelayData.Message} | OldDur: {oldDur} | NewDur: {inputSequence.TotalDuration}\n{ReverseParser.ReverseParse(inputSequence, usedConsole, new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowAllPorts, 0))}");
                }
            }

            InputValidation validation = default;

            using (BotDBContext context = DatabaseManager.OpenContext())
            {
                User user = DataHelper.GetUserNoOpen(userName, context);

                //Check for restricted inputs on this user
                validation = ParserPostProcess.InputSequenceContainsRestrictedInputs(inputSequence, user.GetRestrictedInputs());

                if (validation.InputValidationType != InputValidationTypes.Valid)
                {
                    if (string.IsNullOrEmpty(validation.Message) == false)
                    {
                        MsgHandler.QueueMessage(validation.Message);
                    }
                    return;
                }

                //Check for invalid input combinations
                validation = ParserPostProcess.ValidateInputCombos(inputSequence, usedConsole.InvalidCombos,
                                                                   DataContainer.ControllerMngr, usedConsole);

                if (validation.InputValidationType != InputValidationTypes.Valid)
                {
                    if (string.IsNullOrEmpty(validation.Message) == false)
                    {
                        MsgHandler.QueueMessage(validation.Message);
                    }
                    return;
                }
            }

            //Check for level permissions and ports
            validation = ParserPostProcess.ValidateInputLvlPermsAndPorts(userLevel, inputSequence,
                                                                         DataContainer.ControllerMngr, usedConsole.ConsoleInputs);
            if (validation.InputValidationType != InputValidationTypes.Valid)
            {
                if (string.IsNullOrEmpty(validation.Message) == false)
                {
                    MsgHandler.QueueMessage(validation.Message, Serilog.Events.LogEventLevel.Warning);
                }
                return;
            }

            #endregion

            //Make sure inputs aren't stopped
            if (InputHandler.InputsHalted == true)
            {
                //We can't process inputs because they're currently stopped
                MsgHandler.QueueMessage("New inputs cannot be processed until all other inputs have stopped.", Serilog.Events.LogEventLevel.Warning);
                return;
            }

            //Fetch these values ahead of time to avoid passing the database context through so many methods
            long   autoPromoteEnabled  = DataHelper.GetSettingInt(SettingsConstants.AUTO_PROMOTE_ENABLED, 0L);
            long   autoPromoteInputReq = DataHelper.GetSettingInt(SettingsConstants.AUTO_PROMOTE_INPUT_REQ, long.MaxValue);
            long   autoPromoteLevel    = DataHelper.GetSettingInt(SettingsConstants.AUTO_PROMOTE_LEVEL, -1L);
            string autoPromoteMsg      = DataHelper.GetSettingString(SettingsConstants.AUTOPROMOTE_MESSAGE, string.Empty);

            bool addedInputCount = false;

            TRBotLogger.Logger.Debug($"Reverse Parsed (post-process): " + ReverseParser.ReverseParse(inputSequence, usedConsole,
                                                                                                     new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowNonDefaultPorts, defaultPort,
                                                                                                                                            ReverseParser.ShowDurationTypes.ShowNonDefaultDurations, defaultDur)));

            //Get the max recorded inputs per-user
            long maxUserRecInps = DataHelper.GetSettingInt(SettingsConstants.MAX_USER_RECENT_INPUTS, 0L);

            //It's a valid input - save it in the user's stats
            //Also record the input if we should
            using (BotDBContext context = DatabaseManager.OpenContext())
            {
                User user = DataHelper.GetUserNoOpen(e.UsrMessage.Username, context);

                //Ignore if the user is opted out
                if (user.IsOptedOut == false)
                {
                    user.Stats.ValidInputCount++;
                    addedInputCount = true;

                    context.SaveChanges();

                    //If we should store recent user inputs, do so
                    if (maxUserRecInps > 0)
                    {
                        //Get the input sequence - we may have added mid input delays between
                        //As a result, we'll need to reverse parse it
                        string message = ReverseParser.ReverseParse(inputSequence, usedConsole,
                                                                    new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowNonDefaultPorts, (int)user.ControllerPort,
                                                                                                           ReverseParser.ShowDurationTypes.ShowNonDefaultDurations, defaultDur));

                        //Add the recorded input
                        user.RecentInputs.Add(new RecentInput(message));
                        context.SaveChanges();

                        int diff = user.RecentInputs.Count - (int)maxUserRecInps;

                        //If we're over the max after adding, remove
                        if (diff > 0)
                        {
                            //Order by ascending ID and take the difference
                            //Lower IDs = older entries
                            IEnumerable <RecentInput> shouldRemove = user.RecentInputs.OrderBy(r => r.UserID).Take(diff);

                            foreach (RecentInput rec in shouldRemove)
                            {
                                user.RecentInputs.Remove(rec);
                                context.SaveChanges();
                            }
                        }
                    }
                }
            }

            bool autoPromoted = false;

            //Check if auto promote is enabled and auto promote the user if applicable
            if (addedInputCount == true)
            {
                using (BotDBContext context = DatabaseManager.OpenContext())
                {
                    User user = DataHelper.GetUserNoOpen(e.UsrMessage.Username, context);

                    //Check if the user was already autopromoted, autopromote is enabled,
                    //and if the user reached the autopromote input count requirement
                    if (user.Stats.AutoPromoted == 0 && autoPromoteEnabled > 0 &&
                        user.Stats.ValidInputCount >= autoPromoteInputReq)
                    {
                        //Only autopromote if this is a valid permission level
                        //We may not want to log or send a message for this, as it has potential to be very spammy,
                        //and it's not something the users can control
                        if (PermissionHelpers.IsValidPermissionValue(autoPromoteLevel) == true)
                        {
                            //Mark the user as autopromoted and save
                            user.Stats.AutoPromoted = 1;
                            autoPromoted            = true;

                            context.SaveChanges();
                        }
                    }
                }
            }

            if (autoPromoted == true)
            {
                //If the user is already at or above this level, don't set them to it
                //Only set if the user is below
                if (userLevel < autoPromoteLevel)
                {
                    //Adjust abilities and promote to the new level
                    DataHelper.AdjustUserLvlAndAbilitiesOnLevel(userName, autoPromoteLevel);

                    if (string.IsNullOrEmpty(autoPromoteMsg) == false)
                    {
                        PermissionLevels permLvl  = (PermissionLevels)autoPromoteLevel;
                        string           finalMsg = autoPromoteMsg.Replace("{0}", userName).Replace("{1}", permLvl.ToString());
                        MsgHandler.QueueMessage(finalMsg);
                    }
                }
            }

            InputModes inputMode = (InputModes)DataHelper.GetSettingInt(SettingsConstants.INPUT_MODE, 0L);

            //If the mode is Democracy, add it as a vote for this input
            if (inputMode == InputModes.Democracy)
            {
                //Set up the routine if it doesn't exist
                BaseRoutine      foundRoutine     = RoutineHandler.FindRoutine(RoutineConstants.DEMOCRACY_ROUTINE_ID, out int indexFound);
                DemocracyRoutine democracyRoutine = null;

                if (foundRoutine == null)
                {
                    long voteTime = DataHelper.GetSettingInt(SettingsConstants.DEMOCRACY_VOTE_TIME, 10000L);

                    democracyRoutine = new DemocracyRoutine(voteTime);
                    RoutineHandler.AddRoutine(democracyRoutine);
                }
                else
                {
                    democracyRoutine = (DemocracyRoutine)foundRoutine;
                }

                democracyRoutine.AddInputSequence(userName, inputSequence.Inputs);
            }
            //If it's Anarchy, carry out the input
            else
            {
                /************************************
                * Finally carry out the inputs now! *
                ************************************/

                InputHandler.CarryOutInput(inputSequence.Inputs, usedConsole, DataContainer.ControllerMngr);
            }
        }
Exemple #11
0
 public GuildPermissionLevel(string roleID, PermissionLevels permissionLevel)
 {
     RoleID          = roleID;
     PermissionLevel = permissionLevel;
 }
        public static RopResult ModifyPermissions(int serverId, int folderHandleIndex, PermissionLevels permissionLevel)
        {
            // The contraction conditions.
            Condition.IsTrue(connections.Count > 0);
            Condition.IsTrue(connections.Keys.Contains(serverId));
            Condition.IsTrue(connections[serverId].FolderContainer.Count > 0);

            // Initialize the return value.
            RopResult result = RopResult.InvalidParameter;
            ConnectionData changeConnection = connections[serverId];

            // Identify whether the Current folder is existent or not.
            AbstractFolder currentfolder = new AbstractFolder();
            bool isCurrentFolderExist = false;
            int currentfolderIndex = 0;

            // Find current folder
            foreach (AbstractFolder tempfolder in changeConnection.FolderContainer)
            {
                if (tempfolder.FolderHandleIndex == folderHandleIndex)
                {
                    isCurrentFolderExist = true;
                    currentfolder = tempfolder;
                    currentfolderIndex = changeConnection.FolderContainer.IndexOf(tempfolder);
                }
            }

            if (isCurrentFolderExist)
            {
                // Set folder Permission for CurrentFolder.
                currentfolder.FolderPermission = permissionLevel;
                changeConnection.FolderContainer = changeConnection.FolderContainer.Update(currentfolderIndex, currentfolder);
                connections[serverId] = changeConnection;
                result = RopResult.Success;
            }

            return result;
        }