Skip to content

Commit

Permalink
Merge branch 'dev' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
BrammyS committed Aug 9, 2021
2 parents 04134d8 + 89d6ff0 commit 477903e
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 5 deletions.
1 change: 1 addition & 0 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
actions: read
contents: read
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
jobs:
build:
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
matrix:
os: [ubuntu-latest]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;
using Color_Chan.Discord.Commands.Contexts;
using Color_Chan.Discord.Commands.Results;
using Color_Chan.Discord.Core.Results;

namespace Color_Chan.Discord.Commands.Attributes.ProvidedRequirements
{
/// <summary>
/// This attribute requires a command to be executed in a specific channel.
/// </summary>
/// <example>
/// <code language="cs">
/// [SlashCommandRequireChannel(0123456789)]
/// public class PongCommands : SlashCommandModule
/// {
/// [SlashCommand("ping", "Ping Pong!")]
/// public Task&lt;IDiscordInteractionResponse&gt; PongAsync()
/// {
/// // Command code...
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class SlashCommandRequireChannelAttribute : SlashCommandRequirementAttribute
{
private readonly ulong _channelId;

/// <summary>
/// Initializes a new instance of <see cref="SlashCommandRequireChannelAttribute" />.
/// </summary>
/// <param name="channelId">The ID of the channel.</param>
public SlashCommandRequireChannelAttribute(ulong channelId)
{
_channelId = channelId;
}

/// <inheritdoc />
public override Task<Result> CheckRequirementAsync(ISlashCommandContext context, IServiceProvider services)
{
return Task.FromResult(context.ChannelId != _channelId
? Result.FromError(new SlashCommandRequirementErrorResult($"Channel with ID {_channelId.ToString()} is required to use this command."))
: Result.FromSuccess());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public static IServiceCollection AddColorChanDiscordCommand(this IServiceCollect
services.TryAddTransient<ISlashCommandGuildBuildService, SlashCommandGuildBuildService>();
services.TryAddTransient<ISlashCommandAutoSyncService, SlashCommandAutoSyncService>();
services.TryAddTransient<ISlashCommandBuildService, SlashCommandBuildService>();
services.TryAddSingleton<IDiscordSlashCommandHandler, DiscordSlashCommandHandler>();
services.TryAddSingleton<ISlashCommandService, SlashCommandService>();

slashCommandConfigs ??= configuration =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public async Task<IDiscordInteractionResponse> HandleSlashCommandAsync(IDiscordI
IDiscordGuild? guild = null;
if (_slashCommandConfiguration.EnableAutoGetGuild && interaction.GuildId is not null)
{
var guildResult = await _restGuild.GetGuildAsync(interaction.GuildId.Value).ConfigureAwait(false);
var guildResult = await _restGuild.GetGuildAsync(interaction.GuildId.Value, true).ConfigureAwait(false);
guild = guildResult.Entity;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public async Task<Result<IDiscordInteractionResponse>> ExecuteSlashCommandAsync(
catch (Exception e)
{
_logger.LogError(e, "Exception thrown while running command {CommandName}", commandMethod.Name);
return Result<IDiscordInteractionResponse>.FromError(default, new ExceptionResult(e.InnerException!));
return Result<IDiscordInteractionResponse>.FromError(default, new ExceptionResult(e.InnerException ?? e));
}
}

Expand Down
13 changes: 11 additions & 2 deletions src/Color-Chan.Discord/Controllers/DiscordInteractionController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ namespace Color_Chan.Discord.Controllers
[Route("api/v{apiVersion}/discord")]
public class DiscordInteractionController : ControllerBase
{
private const string SignatureHeader = "X-Signature-Ed25519";
private const string TimeStampHeader = "X-Signature-Timestamp";
private const string ReturnContentType = "application/json";
private readonly IDiscordInteractionAuthService _authService;
private readonly IDiscordSlashCommandHandler _commandHandler;
Expand Down Expand Up @@ -67,9 +69,16 @@ public DiscordInteractionController(IDiscordInteractionAuthService authService,
[HttpPost("interaction")]
public async Task<ActionResult> HandleInteractionRequestAsync()
{
// Check if the request has the headers needed for verification.
if (!Request.Headers.ContainsKey(SignatureHeader) || !Request.Headers.ContainsKey(TimeStampHeader))
{
return Unauthorized();
}

// Verify the interaction request.
var signature = Request.Headers["X-Signature-Ed25519"].ToString();
var timeStamp = Request.Headers["X-Signature-Timestamp"].ToString();
var signature = Request.Headers[SignatureHeader].ToString();
var timeStamp = Request.Headers[TimeStampHeader].ToString();

if (!await _authService.VerifySignatureAsync(signature, timeStamp, Request.Body).ConfigureAwait(false))
{
_logger.LogWarning("Failed to verify interaction command");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ public static IServiceCollection AddColorChanDiscord(this IServiceCollection ser
services.AddColorChanDiscordCommand(configurations.SlashCommandConfigs, configurations.DefaultCacheConfig, configurations.RedisCacheOptions);

services.AddSingleton(_ => new DiscordTokens(botToken, publicBotToken, applicationId));
services.AddSingleton<IDiscordSlashCommandHandler, DiscordSlashCommandHandler>();
services.TryAddTransient<IDiscordInteractionAuthService, DiscordInteractionAuthService>();

configurations.InteractionConfigs ??= configuration =>
Expand Down

0 comments on commit 477903e

Please sign in to comment.