chaosbot/ChaosBot/Services/CheckPermissions.cs

74 lines
2.8 KiB
C#

using System.Collections.Generic;
using System.Linq;
using ChaosBot.Models;
using Discord.Commands;
using Discord.WebSocket;
namespace ChaosBot.Services
{
public class CheckPermissions
{
public static bool CheckPerms(ICommandContext context, string command, string defaultRole = "User")
{
// Debug information
LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command}");
// If user is not SocketGuildUser, then do not grant permission
if (!(context.User is SocketGuildUser gUser)) return false;
// 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))
.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)
{
// TODO: fix {CommandPermission} model to not be int, but to be PermissionTarget, so we can remove the int casts
if (perm.TargetType == (int) PermissionTarget.User)
{
if (context.User.Id == perm.TargetId)
return true;
}
// TODO: fix {CommandPermission} model to not be int, but to be PermissionTarget, so we can remove the int casts
if (perm.TargetType == (int) PermissionTarget.Role)
{
// Check if any of the users roles are of the required group, if so, permission granted
if (gUser.Roles.Any(r => r.Id == perm.TargetId))
return true;
}
}
}
else
{
if (defaultRole == "Admin")
{
if (gUser.GuildPermissions.Administrator)
return true;
}
else if (defaultRole == "User")
{
if (gUser.GuildPermissions.SendMessages)
return true;
}
else
{
LoggingFacade.Info("CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default");
}
}
// Permission denied
return false;
}
}
}