Overhaul the configuration system, let's see how much breaks.... #major

This commit is contained in:
Daniel_I_Am 2020-10-16 21:13:18 +02:00
commit b87d2a2c01
No known key found for this signature in database
GPG Key ID: 80C428FCC9743E84
25 changed files with 389 additions and 235 deletions

View File

@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace ChaosBot.ConfigHelpers
{
public class Configuration
{
private readonly IConfiguration _appSettingsWrapper;
private static readonly Dictionary<string, IConfigurationDetails> ConfigurationFlags = new Dictionary<string, IConfigurationDetails>
{
{"Bot:Name", new ConfigurationDetails<string>("Bot:Name", "ChaosBot", true, false)},
{"Bot:Version", new ConfigurationDetails<string>("Bot:Version", "1.0.0", true, false)},
{"WebServer:Port", new ConfigurationDetails<int>("WebServer:Port", 8080, true, true)},
{"WebServer:Debug", new ConfigurationDetails<bool>("WebServer:Debug", false, true, false)},
{"Discord:Prefix", new ConfigurationDetails<string>("Discord:Prefix", "!", true, false)},
{"Discord:Token", new ConfigurationDetails<string>("Discord:Token", "SECRET_TOKEN", true, true)},
{"Discord:BaseUri", new ConfigurationDetails<string>("Discord:BaseUri", "http://localhost:8080/", true, false)},
{"Discord:ClientId", new ConfigurationDetails<string>("Discord:ClientId", "1234567890", true, false)},
{"Discord:ClientSecret", new ConfigurationDetails<string>("Discord:ClientSecret", "1234567890_SECRET_TOKEN", true, true)},
{"Lodestone:ChaosBotApi:ApiToken", new ConfigurationDetails<string>("Lodestone:ChaosBotApi:ApiToken", "SECRET_TOKEN", true, true)},
{"Lodestone:ChaosBotApi:Url", new ConfigurationDetails<string>("Lodestone:ChaosBotApi:Url", "http://locahost:8000", true, true)},
{"Database:Host", new ConfigurationDetails<string>("Database:Host", "localhost", true, true)},
{"Database:Port", new ConfigurationDetails<int>("Database:Port", 3306, true, true)},
{"Database:User", new ConfigurationDetails<string>("Database:User", "root", true, true)},
{"Database:Pass", new ConfigurationDetails<string>("Database:Pass", "password", true, true)},
{"Database:Name", new ConfigurationDetails<string>("Database:Name", "chaosbot", true, true)},
{"Module:Experience:Enabled", new ConfigurationDetails<bool>("Module:Experience:Enabled", true, false, false)},
{"LevelUp:Channel", new ConfigurationDetails<string>("LevelUp:Channel", null, false, false)},
{"LevelUp:MentionUser", new ConfigurationDetails<bool>("LevelUp:MentionUser", true, false, false)},
};
public Configuration()
{
_appSettingsWrapper = GetAppSettingsWrapper();
}
public IConfigurationDetails GetByKey(string key)
{
if (ConfigurationFlags.TryGetValue(key, out IConfigurationDetails details))
{
return details;
}
throw new ArgumentException($"Configuration '{key}' is not available");
}
public IConfigurationDetails<T> GetByKey<T>(string key)
{
IConfigurationDetails configurationDetails = GetByKey(key);
if (configurationDetails.Type != typeof(T))
throw new ArgumentException($"Configuration flag '{key}' is not of type '{typeof(T)}'");
return (IConfigurationDetails<T>) configurationDetails;
}
internal static IConfiguration GetAppSettingsWrapper()
{
if (Program.AppSettingsHandler == null)
throw new NullReferenceException("Program.AppSettingsHandler is unset");
return Program.AppSettingsHandler;
}
public ImmutableDictionary<string, IConfigurationDetails> GetConfigurationFlags()
{
return ConfigurationFlags.ToImmutableDictionary();
}
public IConfigurationSection GetSection(string key)
{
return _appSettingsWrapper.GetSection(key);
}
}
public interface IConfigurationDetails
{
string Key { get; }
bool WriteRestricted { get; }
bool ReadRestricted { get; }
Type Type { get; }
object DefaultValue { get; }
string GetStringValue(ulong guildId);
void SetValueFromString(string value, ulong guildId);
void DeleteValue(ulong guildId);
}
public interface IConfigurationDetails<T> : IConfigurationDetails
{
new T DefaultValue { get; }
T GetValue(ulong? guildId = null, bool readRestricted = false);
T GetValue(T defaultValue, ulong? guildId = null, bool readValueEvenIfRestricted = false);
void SetValue(T value, ulong guildId);
}
public class ConfigurationDetails<T> : IConfigurationDetails<T>
{
public string Key { get; }
public bool WriteRestricted { get; }
public bool ReadRestricted { get; }
public T DefaultValue { get; }
object IConfigurationDetails.DefaultValue => DefaultValue;
public Type Type => typeof(T);
public ConfigurationDetails(string key, T defaultValue, bool writeRestricted, bool readRestricted)
{
Key = key;
DefaultValue = defaultValue;
WriteRestricted = writeRestricted;
ReadRestricted = readRestricted;
}
public T GetValue(ulong? guildId = null, bool readRestricted = false)
{
return GetValue(DefaultValue, guildId, readRestricted);
}
public T GetValue(T defaultValue, ulong? guildId = null, bool readValueEvenIfRestricted = false)
{
if (!readValueEvenIfRestricted && ReadRestricted)
throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted");
if (guildId.HasValue)
{
return ConfigurationRepository.GetValue(Key, guildId.Value, defaultValue);
}
return Configuration.GetAppSettingsWrapper().GetValue(Key, defaultValue);
}
public string GetStringValue(ulong guildId)
{
return GetValue(guildId: guildId).ToString();
}
public void SetValue(T value, ulong guildId)
{
if (WriteRestricted)
throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted");
ConfigurationRepository.SetValue(Key, value, guildId);
}
public void SetValueFromString(string value, ulong guildId)
{
SetValue((T)Convert.ChangeType(value, typeof(T)), guildId);
}
public void DeleteValue(ulong guildId)
{
if (WriteRestricted)
throw new UnauthorizedAccessException($"Configuration key '{Key}' is restricted");
ConfigurationRepository.DeleteValue(Key, guildId);
}
}
}

View File

@ -0,0 +1,57 @@
using System.Linq;
using System.Threading.Tasks;
using ChaosBot.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace ChaosBot.ConfigHelpers
{
internal static class ConfigurationRepository
{
public static T GetValue<T>(string key, ulong guildId)
{
return GetValue<T>(key, guildId, default);
}
public static T GetValue<T>(string key, ulong guildId, T defaultValue)
{
using ChaosbotContext dbContext = new ChaosbotContext();
Models.Configuration config = dbContext.Configuration
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
if (config == null || string.IsNullOrEmpty(config.SerializedValue))
return GetValueFromAppSettings(key, guildId, defaultValue);
return JsonSerializer.Deserialize<T>(config.SerializedValue);
}
public static void SetValue<T>(string key, T value, ulong guildId)
{
using ChaosbotContext dbContext = new ChaosbotContext();
Models.Configuration cnfSet = new Models.Configuration();
cnfSet.Key = key;
cnfSet.DiscordGuildId = guildId;
cnfSet.SerializedValue = JsonConvert.SerializeObject(value);
dbContext.Configuration.Upsert(cnfSet)
.On(x => new {x.Key, x.DiscordGuildId})
.Run();
}
public static void DeleteValue(string key, ulong guildId)
{
using ChaosbotContext dbContext = new ChaosbotContext();
Models.Configuration config = dbContext.Configuration
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
if (config == null) return;
dbContext.Remove(config);
dbContext.SaveChanges();
}
private static T GetValueFromAppSettings<T>(string key, ulong guildId, T defaultValue)
{
return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue));
}
}
}

View File

@ -3,6 +3,7 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.ConfigHelpers;
using ChaosBot.Discord.Services; using ChaosBot.Discord.Services;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -29,8 +30,11 @@ namespace ChaosBot.Discord
client.Ready += ReadyAsync; client.Ready += ReadyAsync;
services.GetRequiredService<CommandService>().Log += Log; services.GetRequiredService<CommandService>().Log += Log;
// Get the configuration handler
Configuration config = new Configuration();
// this is where we get the Token value from the configuration file, and start the bot // this is where we get the Token value from the configuration file, and start the bot
await client.LoginAsync(TokenType.Bot, Program.AppSettingsHandler.GetValue<string>("Discord:Token")); await client.LoginAsync(TokenType.Bot, config.GetByKey<string>("Discord:Token").GetValue(readRestricted: true));
await client.StartAsync(); await client.StartAsync();
// we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service // we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service

View File

@ -1,14 +1,16 @@
using System; using System;
using System.Collections.Immutable;
using Discord.Commands; using Discord.Commands;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text; using System.Text;
using ChaosBot.ConfigHelpers;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using ChaosBot.Services; using ChaosBot.Services;
using Discord; using Discord;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json; using Newtonsoft.Json;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Modules.Admin namespace ChaosBot.Discord.Modules.Admin
{ {
@ -43,19 +45,20 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Configuration Management Help"; embed.Title = $"Configuration Management Help";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To set a configuration value:"); sb.AppendLine("To set a configuration value:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config set <configFlag> <value>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}config set <configFlag> <value>");
sb.AppendLine("To get a configuration value:"); sb.AppendLine("To get a configuration value:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config get <configFlag>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}config get <configFlag>");
sb.AppendLine("To reset a configuration value to default:"); sb.AppendLine("To reset a configuration value to default:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config reset <configFlag>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}config reset <configFlag>");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To view this help:"); sb.AppendLine("To view this help:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config help"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}config help");
/* /*
* Add the string to the Embed * Add the string to the Embed
@ -79,23 +82,9 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
if ((key != null) && (value != null) ) if ((key != null) && (value != null) )
{ {
if(RestrictedConfig.IsAllowed(key)) new Configuration().GetByKey(key).SetValueFromString(value, Context.Guild.Id);
{
using (ChaosbotContext dbContext = new ChaosbotContext())
{
Configuration cnfSet = new Configuration();
cnfSet.Key = key;
cnfSet.DiscordGuildId = Context.Guild.Id;
cnfSet.SerializedValue = JsonConvert.SerializeObject(value);
await dbContext.Configuration.Upsert(cnfSet)
.On(x => new {x.Key, x.DiscordGuildId}).RunAsync();
await ConfigGet(key, true); await ConfigGet(key, true);
} }
}
}
else else
{ {
await ConfigHelp(); await ConfigHelp();
@ -112,7 +101,7 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
try try
{ {
if ((key != null) && (RestrictedConfig.IsAllowed(key))) if ((key != null))
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
EmbedBuilder embed = new EmbedBuilder(); EmbedBuilder embed = new EmbedBuilder();
@ -124,7 +113,22 @@ namespace ChaosBot.Discord.Modules.Admin
embed.Title = $"Configuration Retrieval"; embed.Title = $"Configuration Retrieval";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine($" Flag: {key}"); sb.AppendLine($" Flag: {key}");
sb.AppendLine($"Value: {ConfigurationRepository.GetValue(key, Context.Guild.Id, "NotSet")}");
Configuration config = new Configuration();
ImmutableDictionary<string, IConfigurationDetails> configFlags =
config.GetConfigurationFlags();
dynamic configValue;
if (configFlags.TryGetValue(key, out IConfigurationDetails configFlagValue))
{
configValue = new Configuration().GetByKey(key).GetStringValue(Context.Guild.Id);
}
else
{
configValue = "Not a valid key";
}
sb.AppendLine($"Value: {configValue}");
/* /*
* Add the string to the Embed * Add the string to the Embed
@ -152,12 +156,13 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
try try
{ {
if ((key != null) && (RestrictedConfig.IsAllowed(key))) if ((key != null))
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
EmbedBuilder embed = new EmbedBuilder(); EmbedBuilder embed = new EmbedBuilder();
Configuration config = new Configuration();
ConfigurationRepository.DeleteValue(key, Context.Guild.Id); config.GetByKey(key).DeleteValue(Context.Guild.Id);
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Configuration Reset"; embed.Title = $"Configuration Reset";

View File

@ -11,9 +11,9 @@ using System.Text;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Lodestone; using ChaosBot.Lodestone;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Newtonsoft.Json; using Newtonsoft.Json;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Modules.Admin namespace ChaosBot.Discord.Modules.Admin
{ {
@ -109,10 +109,9 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
using HttpClient client = new HttpClient(); using HttpClient client = new HttpClient();
IConfigurationSection configurationSection = Configuration config = new Configuration();
Program.AppSettingsHandler.GetSection("Lodestone:ChaosBotApi"); string endpoint =config.GetByKey<string>("Lodestone:ChaosBotApi:Url").GetValue(readRestricted: true);
string endpoint = configurationSection.GetValue<string>("Url"); string apiToken = config.GetByKey<string>("Lodestone:ChaosBotApi:ApiToken").GetValue(readRestricted: true);
string apiToken = configurationSection.GetValue<string>("ApiToken");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
HttpResponseMessage result = HttpResponseMessage result =

View File

@ -7,8 +7,8 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Modules.Admin namespace ChaosBot.Discord.Modules.Admin
{ {
@ -23,19 +23,20 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Role Management Help"; embed.Title = $"Role Management Help";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To add a role-reaction to a message:"); sb.AppendLine("To add a role-reaction to a message:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role add <emote> <role>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}role add <emote> <role>");
sb.AppendLine("To add many role-reactions to a message add more sets of emote and role:"); sb.AppendLine("To add many role-reactions to a message add more sets of emote and role:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role add <emote> <role> <emote> <role> <emote> <role>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}role add <emote> <role> <emote> <role> <emote> <role>");
sb.AppendLine("To remove a role-reaction from a message:"); sb.AppendLine("To remove a role-reaction from a message:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role remove <emote>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}role remove <emote>");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To view this help:"); sb.AppendLine("To view this help:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role help"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}role help");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -1,8 +1,8 @@
using System; using System;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.ConfigHelpers;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Repositories;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -20,10 +20,11 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Information {Program.AppSettingsHandler.GetValue<string>("Bot:Name")} v{Program.AppSettingsHandler.GetValue<string>("Bot:Version")}"; embed.Title = $"Information {config.GetByKey<string>("Bot:Name").GetValue()} v{config.GetByKey<string>("Bot:Version").GetValue()}";
sb.AppendLine($"Prefix: {ConfigurationRepository.GetValue<string>("Discord:Prefix", Context.Guild.Id)}"); sb.AppendLine($"Prefix: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -8,9 +8,9 @@ using System.Linq;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Lodestone; using ChaosBot.Lodestone;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using ChaosBot.Services; using ChaosBot.Services;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Modules.User namespace ChaosBot.Discord.Modules.User
{ {
@ -73,28 +73,29 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = "Lodestone API Help"; embed.Title = "Lodestone API Help";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To get FreeCompany Info:"); sb.AppendLine("To get FreeCompany Info:");
sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone freecompany 9231394073691143535"); sb.AppendLine($"By Id: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone freecompany 9231394073691143535");
sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone freecompany Siren Helix"); sb.AppendLine($"By Name: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone freecompany Siren Helix");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To get Character Info:"); sb.AppendLine("To get Character Info:");
sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone character 9231394073691143535"); sb.AppendLine($"By Id: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone character 9231394073691143535");
sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone character Siren Luna Kaisar"); sb.AppendLine($"By Name: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone character Siren Luna Kaisar");
if (CheckPermissions.CheckPerms(Context, "lodestone.link")) if (CheckPermissions.CheckPerms(Context, "lodestone.link"))
{ {
sb.AppendLine("To Link your Character:"); sb.AppendLine("To Link your Character:");
sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone link 9231394073691143535"); sb.AppendLine($"By Id: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone link 9231394073691143535");
sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone link Siren Luna Kaisar"); sb.AppendLine($"By Name: {config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}lodestone link Siren Luna Kaisar");
} }
sb.AppendLine(); sb.AppendLine();
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To view this help:"); sb.AppendLine("To view this help:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config help"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}config help");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -4,12 +4,12 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using ChaosBot.Services; using ChaosBot.Services;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Modules.User namespace ChaosBot.Discord.Modules.User
{ {
@ -76,19 +76,20 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = "Points system"; embed.Title = "Points system";
sb.AppendLine($"{Context.User.Mention} has requested points information."); sb.AppendLine($"{Context.User.Mention} has requested points information.");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Usage:"); sb.AppendLine("Usage:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points info"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}points info");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points help"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}points help");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Moderation commands:"); sb.AppendLine("Moderation commands:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points add <discord mention> <amount>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}points add <discord mention> <amount>");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}point remove <discord mention> <amount>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}point remove <discord mention> <amount>");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}point delete <discord mention>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}point delete <discord mention>");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -4,11 +4,11 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using ChaosBot.Services; using ChaosBot.Services;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Modules.User namespace ChaosBot.Discord.Modules.User
{ {
@ -85,23 +85,24 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = "Raffle system"; embed.Title = "Raffle system";
sb.AppendLine($"{Context.User.Mention} has requested Raffle information."); sb.AppendLine($"{Context.User.Mention} has requested Raffle information.");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Usage:"); sb.AppendLine("Usage:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle info"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle info");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle help"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle help");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle buy <amount>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle buy <amount>");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Moderation commands:"); sb.AppendLine("Moderation commands:");
if(CheckPermissions.CheckPerms(Context, "raffle.add", "Admin")) if(CheckPermissions.CheckPerms(Context, "raffle.add", "Admin"))
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle add <discord mention> <amount>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle add <discord mention> <amount>");
if(CheckPermissions.CheckPerms(Context, "raffle.remove", "Admin")) if(CheckPermissions.CheckPerms(Context, "raffle.remove", "Admin"))
{ {
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle remove <discord mention> <amount>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle remove <discord mention> <amount>");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle delete <discord mention>"); sb.AppendLine($"{config.GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle delete <discord mention>");
} }
/* /*
* Add the string to the Embed * Add the string to the Embed
@ -279,7 +280,7 @@ namespace ChaosBot.Discord.Modules.User
else else
{ {
await ReplyAsync( await ReplyAsync(
$"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle clear confirm```"); $"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{new Configuration().GetByKey<string>("Discord:Prefix").GetValue(Context.Guild.Id)}raffle clear confirm```");
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories; using ChaosBot.Services;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
@ -16,70 +16,10 @@ namespace ChaosBot.Discord.PreConditions
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{ {
// Debug information if (CheckPermissions.CheckPerms(context, command.Name, _defaultRole))
LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command.Name}");
// 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()); 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 return Task.FromResult(PreconditionResult.FromError("No permission has been granted to your user or your role"));
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."));
} }
} }
} }

View File

@ -1,6 +1,6 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.Repositories; using ChaosBot.ConfigHelpers;
using Discord.Commands; using Discord.Commands;
namespace ChaosBot.Discord.PreConditions namespace ChaosBot.Discord.PreConditions
@ -32,8 +32,7 @@ namespace ChaosBot.Discord.PreConditions
if (context.Guild == null) throw new Exception("This must be run in a guild"); if (context.Guild == null) throw new Exception("This must be run in a guild");
// Check if module enabled in database // Check if module enabled in database
return Convert.ToBoolean(ConfigurationRepository.GetValue<string>($"Module:{moduleName}:Enabled", return new Configuration().GetByKey<bool>($"Module:{moduleName}:Enabled").GetValue(true, context.Guild.Id);
context.Guild.Id, "true"));
} }
} }
} }

View File

@ -3,12 +3,12 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Services namespace ChaosBot.Discord.Services
{ {
@ -66,13 +66,14 @@ namespace ChaosBot.Discord.Services
SocketCommandContext context = new SocketCommandContext(_client, message); SocketCommandContext context = new SocketCommandContext(_client, message);
Configuration config = new Configuration();
int argPos = 0; int argPos = 0;
string prefix = ConfigurationRepository.GetValue("Discord:Prefix", context.Guild.Id, "!"); string prefix = config.GetByKey<string>("Discord:Prefix").GetValue(context.Guild.Id);
if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) ||
message.HasStringPrefix(prefix, ref argPos))) message.HasStringPrefix(prefix, ref argPos)))
{ {
if(Convert.ToBoolean(ConfigurationRepository.GetValue("Experience:Commands", context.Guild.Id, "false"))) if(config.GetByKey<bool>("Module:Experience:Enabled").GetValue(false, context.Guild.Id))
ExperienceHandler.AddXp(context); ExperienceHandler.AddXp(context);
return; return;
} }

View File

@ -2,11 +2,11 @@ using System;
using System.Linq; using System.Linq;
using ChaosBot.Discord.PreConditions; using ChaosBot.Discord.PreConditions;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Configuration = ChaosBot.ConfigHelpers.Configuration;
namespace ChaosBot.Discord.Services namespace ChaosBot.Discord.Services
{ {
@ -66,12 +66,13 @@ namespace ChaosBot.Discord.Services
{ {
// The user has leveled up, we can send a message // The user has leveled up, we can send a message
LoggingFacade.Info($"User leveled up [{context.User.Username}#{context.User.Discriminator} -> Level {newLevel}]"); LoggingFacade.Info($"User leveled up [{context.User.Username}#{context.User.Discriminator} -> Level {newLevel}]");
Configuration config = new Configuration();
string channelToSendIn = string channelToSendIn =
ConfigurationRepository.GetValue("LevelUp:Channel", context.Guild.Id, "false"); config.GetByKey<string>("LevelUp:Channel").GetValue(null, context.Guild.Id);
string mentionString = $"<@{context.User.Id}>"; string mentionString = $"<@{context.User.Id}>";
if (!Convert.ToBoolean(ConfigurationRepository.GetValue("LevelUp:MentionUser", context.Guild.Id, "true"))) if (!config.GetByKey<bool>("LevelUp:MentionUser").GetValue(context.Guild.Id))
{ {
mentionString = context.User.Username; mentionString = context.User.Username;
if (context.User is IGuildUser guildUser) if (context.User is IGuildUser guildUser)

View File

@ -1,4 +1,5 @@
using System; using System;
using ChaosBot.ConfigHelpers;
using ChaosBot.Services; using ChaosBot.Services;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
@ -15,8 +16,9 @@ namespace ChaosBot.Discord.Services
public static void Initialize(IServiceProvider services) public static void Initialize(IServiceProvider services)
{ {
_client = services.GetRequiredService<DiscordSocketClient>(); _client = services.GetRequiredService<DiscordSocketClient>();
Configuration config = new Configuration();
foreach (IConfigurationSection serverConfig in Program.AppSettingsHandler.GetSection("Servers").GetChildren()) foreach (IConfigurationSection serverConfig in config.GetSection("Servers").GetChildren())
{ {
long? lodestoneChannelSloganDescriptionId = serverConfig.GetValue<long?>("Lodestone:SloganDescription:Channel", null); long? lodestoneChannelSloganDescriptionId = serverConfig.GetValue<long?>("Lodestone:SloganDescription:Channel", null);
int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60); int refreshMinutes = serverConfig.GetValue("Lodestone:SloganDescription:RefreshMinutes", 60);

View File

@ -19,17 +19,32 @@ namespace ChaosBot.Models
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
string server, user, pass, name;
int port;
if (Program.AppSettingsHandler == null) if (Program.AppSettingsHandler == null)
{ {
Program.AppSettingsHandler = new ConfigurationBuilder() IConfiguration config = Program.AppSettingsHandler = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory()) .SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("./appsettings.json", optional: false, reloadOnChange: true).Build(); .AddJsonFile("./appsettings.json", optional: false, reloadOnChange: true).Build();
server = config.GetValue<string>("Database:Host");
port = config.GetValue<int>("Database:Port");
user = config.GetValue<string>("Database:User");
pass = config.GetValue<string>("Database:Pass");
name = config.GetValue<string>("Database:Name");
} }
string server = Program.AppSettingsHandler.GetValue<string>("Database:Host"); else
int port = Program.AppSettingsHandler.GetValue<int>("Database:Port"); {
string user = Program.AppSettingsHandler.GetValue<string>("Database:User"); ConfigHelpers.Configuration config = new ConfigHelpers.Configuration();
string pass = Program.AppSettingsHandler.GetValue<string>("Database:Pass");
string name = Program.AppSettingsHandler.GetValue<string>("Database:Name"); server = config.GetByKey<string>("Database:Host").GetValue(readRestricted: true);
port = config.GetByKey<int>("Database:Port").GetValue(readRestricted: true);
user = config.GetByKey<string>("Database:User").GetValue(readRestricted: true);
pass = config.GetByKey<string>("Database:Pass").GetValue(readRestricted: true);
name = config.GetByKey<string>("Database:Name").GetValue(readRestricted: true);
}
optionsBuilder.UseMySql( optionsBuilder.UseMySql(
$"server={server};port={port};user={user};password={pass};database={name}", $"server={server};port={port};user={user};password={pass};database={name}",
x => x.ServerVersion("5.5.64-mariadb")); x => x.ServerVersion("5.5.64-mariadb"));

View File

@ -4,6 +4,7 @@ using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using ChaosBot.Discord; using ChaosBot.Discord;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.ConfigHelpers;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
[assembly: InternalsVisibleTo("ChaosBot.UnitTests")] [assembly: InternalsVisibleTo("ChaosBot.UnitTests")]
@ -42,7 +43,8 @@ namespace ChaosBot
/* /*
* Initialize the Discord Client and Login * Initialize the Discord Client and Login
*/ */
_logger.Info($"Starting Up {AppSettingsHandler.GetValue<string>("Bot:Name")} v{AppSettingsHandler.GetValue<string>("Bot:Version")}"); Configuration config = new Configuration();
_logger.Info($"Starting Up {config.GetByKey<string>("Bot:Name").GetValue()} v{config.GetByKey<string>("Bot:Version").GetValue()}");
try try
{ {

View File

@ -1,45 +0,0 @@
using System;
using System.Linq;
using ChaosBot.Models;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
namespace ChaosBot.Repositories
{
public static class ConfigurationRepository
{
public static T GetValue<T>(string key, ulong guildId)
{
return GetValue<T>(key, guildId, default);
}
public static T GetValue<T>(string key, ulong guildId, T defaultValue)
{
using (ChaosbotContext dbContext = new ChaosbotContext())
{
Configuration config = dbContext.Configuration
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
if (config == null || string.IsNullOrEmpty(config.SerializedValue))
return GetValueFromAppSettings(key, guildId, defaultValue);
return JsonSerializer.Deserialize<T>(config.SerializedValue);
}
}
public static void DeleteValue(string key, ulong guildId)
{
using (ChaosbotContext dbContext = new ChaosbotContext())
{
Configuration config = dbContext.Configuration
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
if (config == null) return;
dbContext.Remove(config);
dbContext.SaveChanges();
}
}
private static T GetValueFromAppSettings<T>(string key, ulong guildId, T defaultValue)
{
return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue));
}
}
}

View File

@ -1,7 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using ChaosBot.Models; using ChaosBot.Models;
using ChaosBot.Repositories;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
@ -14,7 +13,7 @@ namespace ChaosBot.Services
// Debug information // Debug information
LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command}"); LoggingFacade.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command}");
// If user is not SocketGuildUser, then return error // If user is not SocketGuildUser, then do not grant permission
if (!(context.User is SocketGuildUser gUser)) return false; if (!(context.User is SocketGuildUser gUser)) return false;
// Get the possible permissions // Get the possible permissions
@ -33,31 +32,22 @@ namespace ChaosBot.Services
// Loop through all permissions // Loop through all permissions
foreach (CommandPermission perm in commandPermissions) foreach (CommandPermission perm in commandPermissions)
{ {
ulong requiredGroup; // TODO: fix {CommandPermission} model to not be int, but to be PermissionTarget, so we can remove the int casts
// Check if it's a role or group permission and fetch the right type if (perm.TargetType == (int) PermissionTarget.User)
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) if (context.User.Id == perm.TargetId)
return true; return true;
return false;
} }
else
// 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)
{ {
// Return the permission value
requiredGroup = perm.TargetId;
}
// Check if any of the users roles are of the required group, if so, permission granted // Check if any of the users roles are of the required group, if so, permission granted
if (gUser.Roles.Any(r => r.Id == requiredGroup)) if (gUser.Roles.Any(r => r.Id == perm.TargetId))
return true; return true;
} }
} }
}
else else
{ {
if (defaultRole == "Admin") if (defaultRole == "Admin")
@ -71,8 +61,10 @@ namespace ChaosBot.Services
return true; return true;
} }
else else
{
LoggingFacade.Info("CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default"); LoggingFacade.Info("CheckCommandperm.CheckPermissionsAsync|commandPermissions: No Default");
} }
}
// Permission denied // Permission denied
return false; return false;

View File

@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
namespace ChaosBot.Services
{
public class RestrictedConfig
{
public static Boolean IsAllowed(string key)
{
// TODO: List populated from DB
List<string> restrictedCfg = new List<string> {"Database:Host", "Database:Port", "Database:Name", "Database:User", "Database:Pass", "Bot:Version", "NLog", "WebServer", "Discord:Token"};
if (restrictedCfg.Contains(key))
return false;
return true;
}
}
}

View File

@ -4,8 +4,8 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChaosBot.ConfigHelpers;
using ChaosBot.Discord; using ChaosBot.Discord;
using ChaosBot.Repositories;
using ChaosBot.WebServer.Services; using ChaosBot.WebServer.Services;
using Discord; using Discord;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -36,9 +36,11 @@ namespace ChaosBot.WebServer.App
[HttpGet] [HttpGet]
public async Task<IActionResult> Index(string code = null) public async Task<IActionResult> Index(string code = null)
{ {
string redirectUri = $"{Program.AppSettingsHandler.GetValue<string>("Discord:BaseUri")}/api/discord"; Configuration config = new Configuration();
string clientId = Program.AppSettingsHandler.GetValue<string>("Discord:ClientId");
string clientSecret = Program.AppSettingsHandler.GetValue<string>("Discord:ClientSecret"); string redirectUri = $"{config.GetByKey<string>("Discord:BaseUri").GetValue()}/api/discord";
string clientId = config.GetByKey<string>("Discord:ClientId").GetValue();
string clientSecret = config.GetByKey<string>("Discord:ClientSecret").GetValue(readRestricted: true);
if (code == null) if (code == null)
return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds"); return Redirect($"https://discord.com/api/oauth2/authorize?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope=identify%20guilds");

View File

@ -1,3 +1,4 @@
using ChaosBot.ConfigHelpers;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
namespace ChaosBot.WebServer.Services namespace ChaosBot.WebServer.Services
@ -6,7 +7,7 @@ namespace ChaosBot.WebServer.Services
{ {
public string Generate() public string Generate()
{ {
string clientId = Program.AppSettingsHandler.GetValue<string>("Discord:ClientId"); string clientId = new Configuration().GetByKey<string>("Discord:ClientId").GetValue();
const ulong permissions = const ulong permissions =
0x00000020 + // MANAGE_CHANNELS 0x00000020 + // MANAGE_CHANNELS
0x04000000 + // CHANGE_NICKNAME 0x04000000 + // CHANGE_NICKNAME

View File

@ -29,6 +29,7 @@ namespace ChaosBot.WebServer.Services
ValidationResult result = ruleType switch ValidationResult result = ruleType switch
{ {
"optional" => CheckOptional(key, value),
"required" => CheckRequired(key, value), "required" => CheckRequired(key, value),
"type" => CheckType(key, value, ruleParts), "type" => CheckType(key, value, ruleParts),
"min" => CheckMin(key, value, ruleParts), "min" => CheckMin(key, value, ruleParts),
@ -36,6 +37,9 @@ namespace ChaosBot.WebServer.Services
_ => new ValidationResult.Unknown() _ => new ValidationResult.Unknown()
}; };
if (result.DoesForceSuccess())
break;
if (result.GetError() != null) if (result.GetError() != null)
{ {
errorBuilder.AppendLine($"[{result.GetKey()}] {result.GetError()}"); errorBuilder.AppendLine($"[{result.GetKey()}] {result.GetError()}");
@ -48,6 +52,13 @@ namespace ChaosBot.WebServer.Services
return error.Length == 0; return error.Length == 0;
} }
private ValidationResult CheckOptional(string key, dynamic value)
{
if (value == null)
return new ValidationResult.SuperSuccess();
return new ValidationResult.Success();
}
private ValidationResult CheckRequired(string key, dynamic value) private ValidationResult CheckRequired(string key, dynamic value)
{ {
if (value != null) if (value != null)
@ -155,6 +166,14 @@ namespace ChaosBot.WebServer.Services
_key = key; _key = key;
} }
internal class SuperSuccess : ValidationResult
{
public override bool DoesForceSuccess()
{
return true;
}
}
internal class Success : ValidationResult {} internal class Success : ValidationResult {}
internal class Failure : ValidationResult internal class Failure : ValidationResult
@ -172,5 +191,10 @@ namespace ChaosBot.WebServer.Services
{ {
return this._key; return this._key;
} }
public virtual bool DoesForceSuccess()
{
return false;
}
} }
} }

View File

@ -1,4 +1,5 @@
using System.Net.Http; using System.Net.Http;
using ChaosBot.ConfigHelpers;
using ChaosBot.WebServer.Services; using ChaosBot.WebServer.Services;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@ -42,7 +43,7 @@ namespace ChaosBot.WebServer
{ {
LoggingFacade.Info("Initializing Kestrel Startup and Configuration"); LoggingFacade.Info("Initializing Kestrel Startup and Configuration");
if (Program.AppSettingsHandler.GetValue<bool>("WebServer:Debug", false)) if (new Configuration().GetByKey<bool>("WebServer:Debug").GetValue())
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseForwardedHeaders(); app.UseForwardedHeaders();

View File

@ -1,5 +1,6 @@
using System.IO; using System.IO;
using System.Net; using System.Net;
using ChaosBot.ConfigHelpers;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
@ -22,12 +23,13 @@ namespace ChaosBot.WebServer
{ {
string contentRoot = Directory.GetCurrentDirectory(); string contentRoot = Directory.GetCurrentDirectory();
string webRoot = Path.Combine(contentRoot, "wwwroot/dist"); string webRoot = Path.Combine(contentRoot, "wwwroot/dist");
Configuration config = new Configuration();
webBuilder.UseContentRoot(contentRoot); webBuilder.UseContentRoot(contentRoot);
webBuilder.UseWebRoot(webRoot); webBuilder.UseWebRoot(webRoot);
webBuilder.ConfigureKestrel(serverOptions => webBuilder.ConfigureKestrel(serverOptions =>
{ {
serverOptions.Listen(IPAddress.Any, Program.AppSettingsHandler.GetValue<int>("WebServer:Port"), serverOptions.Listen(IPAddress.Any, config.GetByKey<int>("WebServer:Port").GetValue(readRestricted: true),
listenOptions => listenOptions =>
{ {
listenOptions.UseConnectionLogging(); listenOptions.UseConnectionLogging();
@ -37,7 +39,7 @@ namespace ChaosBot.WebServer
{ {
logging.ClearProviders(); logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace); logging.SetMinimumLevel(LogLevel.Trace);
logging.AddNLog(new NLogLoggingConfiguration(Program.AppSettingsHandler.GetSection("NLog"))); logging.AddNLog(new NLogLoggingConfiguration(config.GetSection("NLog")));
}) })
.UseStartup<Startup>(); .UseStartup<Startup>();
}); });