Remove *some* duplicate code

This commit is contained in:
Daniel_I_Am 2020-10-16 17:25:34 +02:00
parent 9b604b67a7
commit 5019ea3d3e
No known key found for this signature in database
GPG Key ID: 80C428FCC9743E84

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Threading.Tasks;
using ChaosBot.Models;
using ChaosBot.Repositories;
using ChaosBot.Services;
using Discord.Commands;
using Discord.WebSocket;
@ -16,70 +17,10 @@ namespace ChaosBot.Discord.PreConditions
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
// Debug information
LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command.Name}");
if (CheckPermissions.CheckPerms(context, command.Name, _defaultRole))
return Task.FromResult(PreconditionResult.FromSuccess());
// If user is not SocketGuildUser, then return error
if (!(context.User is SocketGuildUser gUser)) return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command."));
// Get the possible permissions
List<CommandPermission> commandPermissions;
using (ChaosbotContext dbContext = new ChaosbotContext())
{
IQueryable<CommandPermission> permissions = dbContext.CommandPermissions;
commandPermissions = permissions.Where(p => p.Command.Equals(command.Name))
.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<ulong>($"Role:{perm.TargetId}", context.Guild.Id, perm.TargetId);
}
else if (perm.TargetType == (int) PermissionTarget.User)
{
if(context.User.Id == perm.TargetId)
return Task.FromResult(PreconditionResult.FromSuccess());
continue;
}
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 Task.FromResult(PreconditionResult.FromSuccess());
}
}
else
{
if (_defaultRole == "Admin")
{
if(gUser.GuildPermissions.Administrator)
return Task.FromResult(PreconditionResult.FromSuccess());
}
else if ( _defaultRole == "User")
{
if(gUser.GuildPermissions.SendMessages)
return Task.FromResult(PreconditionResult.FromSuccess());
}
else
LoggingFacade.Info($"CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default");
}
// Permission denied
return Task.FromResult(PreconditionResult.FromError($"You do not have access to this command."));
return Task.FromResult(PreconditionResult.FromError("No permission has been granted to your user or your role"));
}
}
}