From a672c3968f59e57537b0b737adc1dfdec1d735bc Mon Sep 17 00:00:00 2001 From: Sean Stoves Date: Wed, 5 Aug 2020 22:40:01 -0400 Subject: [PATCH] in Line code for special permission nodes --- ChaosBot/Services/CheckPermissions.cs | 86 +++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 ChaosBot/Services/CheckPermissions.cs diff --git a/ChaosBot/Services/CheckPermissions.cs b/ChaosBot/Services/CheckPermissions.cs new file mode 100644 index 0000000..dc27cfc --- /dev/null +++ b/ChaosBot/Services/CheckPermissions.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using ChaosBot.Models; +using ChaosBot.Repositories; +using Discord.Commands; +using Discord.WebSocket; +using NLog; + +namespace ChaosBot.Services +{ + public class CheckPermissions + { + private static ILogger _logger = Program.Logger; + + public static async Task CheckPerms(ICommandContext context, string command, string defaultRole = "User") + { + // Debug information + _logger.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command}"); + + // If user is not SocketGuildUser, then return error + if (!(context.User is SocketGuildUser gUser)) return false; + + // Get the possible permissions + List commandPermissions; + using (ChaosbotContext dbContext = new ChaosbotContext()) + { + IQueryable permissions = dbContext.CommandPermissions; + commandPermissions = permissions.Where(p => p.Command.Equals(command)) + .Where(p => p.DiscordGuildId == context.Guild.Id) + .ToList(); + } + + // If we can find a permission + if(commandPermissions.Count >= 1) + { + // Loop through all permissions + foreach (CommandPermission perm in commandPermissions) + { + ulong requiredGroup; + // Check if it's a role or group permission and fetch the right type + if (perm.TargetType == (int)PermissionTarget.Role) + { + // If it's a role, check the configuration for the role otherwise return the permission value + requiredGroup = ConfigurationRepository.GetValue($"Role:{perm.TargetId}", context.Guild.Id, perm.TargetId); + } + else if (perm.TargetType == (int) PermissionTarget.User) + { + if (context.User.Id == perm.TargetId) + return true; + + return false; + } + else + { + // Return the permission value + requiredGroup = perm.TargetId; + } + + // Check if any of the users roles are of the required group, if so, permission granted + if (gUser.Roles.Any(r => r.Id == requiredGroup)) + return true; + } + } + else + { + if (defaultRole == "Admin") + { + if (gUser.GuildPermissions.Administrator) + return true; + } + else if (defaultRole == "User") + { + if (gUser.GuildPermissions.SendMessages) + return true; + } + else + _logger.Info($"CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default"); + } + + // Permission denied + return false; + } + } +} \ No newline at end of file