Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(twofactor): More customization and extended functioniality #3

Merged
merged 19 commits into from
May 9, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ title: TwoFactor Commands Introduction

Install the NuGet package `DisCatSharp.Extensions.TwoFactorCommands` into your project. Currently only available as prerelease.

You'll also need `DiscordSharp.Interactivity`.

Enable the extension by calling [UseTwoFactor](xref:DisCatSharp.Extensions.TwoFactorCommands.ExtensionMethods#DisCatSharp_Extensions_TwoFactorCommands_ExtensionMethods_UseTwoFactor_DiscordClient_DisCatSharp_Extensions_TwoFactorCommands_TwoFactorConfiguration_) on your [DiscordClient](xref:DisCatSharp.DiscordClient) instance:

```cs
Expand Down Expand Up @@ -88,18 +90,43 @@ To force a command to require two factor, use the [ApplicationCommandRequireEnro

To ask a user to submit their two factor code, use the function [RequestTwoFactorAsync()](xref:DisCatSharp.Extensions.TwoFactorCommands.ApplicationCommands.TwoFactorApplicationCommandExtension#DisCatSharp_Extensions_TwoFactorCommands_ApplicationCommands_TwoFactorApplicationCommandExtension_RequestTwoFactorAsync_BaseContext_) on your [BaseContext](xref:DisCatSharp.ApplicationCommands.Context.BaseContext).

It returns a [TwoFactorResponse](xref:DisCatSharp.Extensions.TwoFactorCommands.Enums.TwoFactorResponse).
Make sure to annotate your command with the [ApplicationCommandRequireEnrolledTwoFactorAttribute](xref:DisCatSharp.ApplicationCommands.Attributes.ApplicationCommandRequireEnrolledTwoFactorAttribute) attribute.
It returns a [TwoFactorResponse](xref:DisCatSharp.Extensions.TwoFactorCommands.Properties.TwoFactorResponse).

```cs
var tfa_result = ctx.RequestTwoFactorAsync();
var tfa_result = await ctx.RequestTwoFactorAsync();

if (tfa_result == TwoFactorResponse.ValidCode)
if (tfa_result.Result != TwoFactorResult.ValidCode)
{
// Do your stuff
// Handle incorrect code
return;
}

// Do your stuff
```

### Using TwoFactor with Buttons

Using two factor authentication on buttons is pretty similar to slash commands but it'll need a DiscordClient to attach to.

Run [RequestTwoFactorAsync()](xref:DisCatSharp.Extensions.TwoFactorCommands.ApplicationCommands.TwoFactorApplicationCommandExtension#DisCatSharp_Extensions_TwoFactorCommands_ApplicationCommands_TwoFactorApplicationCommandExtension_RequestTwoFactorAsync_BaseContext_) on your [ComponentInteractionCreateEventArgs](xref:DisCatSharp.EventArgs.ComponentInteractionCreateEventArgs) to ask the user for the two factor auth code.

Same deal as for slash commands, it'll return a [TwoFactorResponse](xref:DisCatSharp.Extensions.TwoFactorCommands.Properties.TwoFactorResponse).

```cs
async Task SomeButtonInteraction(DiscordClient sender, ComponentInteractionCreateEventArgs e)
{
var tfa_result = await e.RequestTwoFactorAsync(sender);

if (tfa_result.Result != TwoFactorResult.ValidCode)
{
// Handle incorrect code
return;
}

// Do your stuff
}
```

The user will be asked to submit their two factor code like this:

![Example](/images/two_factor_request_example.png)
![Example](/images/two_factor_request_example.png)
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ Extension allowing to require two factor authentication for commands.
<ItemGroup>
<PackageReference Include="DatabaseWrapper" Version="5.0.2" />
<PackageReference Include="DatabaseWrapper.Sqlite" Version="5.0.2" />
<PackageReference Include="DisCatSharp" Version="10.3.3-nightly-031" />
<PackageReference Include="DisCatSharp" Version="10.3.3-nightly-041" />
<PackageReference Include="DisCatSharp.Analyzer.Roselyn" Version="5.4.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="DisCatSharp.ApplicationCommands" Version="10.3.3-nightly-031" />
<PackageReference Include="DisCatSharp.ApplicationCommands" Version="10.3.3-nightly-041" />
<PackageReference Include="DisCatSharp.Attributes" Version="10.4.0" />
<PackageReference Include="DisCatSharp.CommandsNext" Version="10.3.3-nightly-031" />
<PackageReference Include="DisCatSharp.Common" Version="10.3.3-nightly-031" />
<PackageReference Include="DisCatSharp.Interactivity" Version="10.3.3-nightly-031" />
<PackageReference Include="DisCatSharp.CommandsNext" Version="10.3.3-nightly-041" />
<PackageReference Include="DisCatSharp.Common" Version="10.3.3-nightly-041" />
<PackageReference Include="DisCatSharp.Interactivity" Version="10.3.3-nightly-041" />
<PackageReference Include="Microsoft.DependencyValidation.Analyzers" Version="0.11.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
Expand Down
TheXorog marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespace DisCatSharp.Extensions.TwoFactorCommands.Enums;
/// <summary>
/// Represents two factor responses.
/// </summary>
public enum TwoFactorResponse : int
public enum TwoFactorResult : int
{
/// <summary>
/// Code is invalid.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@
// SOFTWARE.

using System;
using System.Linq;
using System.Threading.Tasks;

using DisCatSharp.ApplicationCommands.Context;
using DisCatSharp.Entities;
using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using DisCatSharp.Extensions.TwoFactorCommands.Enums;
using DisCatSharp.Extensions.TwoFactorCommands.Properties;
using DisCatSharp.Interactivity.Extensions;

namespace DisCatSharp.Extensions.TwoFactorCommands.ApplicationCommands;
Expand All @@ -44,31 +45,106 @@ public static class TwoFactorApplicationCommandExtension
public static async Task<TwoFactorResponse> RequestTwoFactorAsync(this BaseContext ctx)
{
var ext = ctx.Client.GetTwoFactor();
/*

if (!ext.IsEnrolled(ctx.User.Id))
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent("You are not enrolled in two factor."));
return TwoFactorResponse.NotEnrolled;
if (ext.Configuration.ResponseConfiguration.ShowResponse)
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationNotEnrolledMessage));

return new TwoFactorResponse() { Client = ctx.Client, Result = TwoFactorResult.NotEnrolled };
}
*/

DiscordInteractionModalBuilder builder = new(ext.Configuration.ResponseConfiguration.AuthenticationModalRequestTitle);
builder.AddTextComponent(new DiscordTextComponent(TextComponentStyle.Small, "code", "Code", "123456", ext.Configuration.Digits, ext.Configuration.Digits));
await ctx.CreateModalResponseAsync(builder);

var response = new TwoFactorResponse()
{
Client = ctx.Client
};

var inter = await ctx.Client.GetInteractivity().WaitForModalAsync(builder.CustomId, TimeSpan.FromSeconds(ext.Configuration.TwoFactorTimeout));
if (inter.TimedOut)
return TwoFactorResponse.TimedOut;
{
response.Result = TwoFactorResult.TimedOut;
return response;
}

await inter.Result.Interaction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent("Checking.."));
var res = ext.IsValidCode(ctx.User.Id, inter.Result.Interaction.Data.Components.First().Value);
response.Interaction = inter.Result;

if (ext.Configuration.ResponseConfiguration.ShowResponse)
await inter.Result.Interaction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent("Checking.."));
var res = ext.IsValidCode(ctx.User.Id, inter.Result.Interaction.Data.Components[0].Value);
if (res)
{
await inter.Result.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationSuccessMessage));
return TwoFactorResponse.ValidCode;
if (ext.Configuration.ResponseConfiguration.ShowResponse)
await inter.Result.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationSuccessMessage));

response.Result = TwoFactorResult.ValidCode;
return response;
}

await inter.Result.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationFailureMessage));
return TwoFactorResponse.InvalidCode;
if (ext.Configuration.ResponseConfiguration.ShowResponse)
await inter.Result.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationFailureMessage));

response.Result = TwoFactorResult.InvalidCode;
return response;
}

/// <summary>
/// <para>Asks the user via modal input for the two factor code.</para>
/// <para>This uses DisCatSharp.Interactivity.</para>
/// <para>To be used as first action for button.</para>
/// </summary>
/// <param name="evt">The interaction context.</param>
/// <param name="client">The discord client to use.</param>
/// <returns>A <see cref="TwoFactorResponse"/>.</returns>
public static async Task<TwoFactorResponse> RequestTwoFactorAsync(this ComponentInteractionCreateEventArgs evt, DiscordClient client)
{
var ext = client.GetTwoFactor();

if (!ext.IsEnrolled(evt.User.Id))
{
if (ext.Configuration.ResponseConfiguration.ShowResponse)
await evt.Interaction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationNotEnrolledMessage));

return new TwoFactorResponse() { Client = client, Result = TwoFactorResult.NotEnrolled };
}

DiscordInteractionModalBuilder builder = new(ext.Configuration.ResponseConfiguration.AuthenticationModalRequestTitle);
builder.AddTextComponent(new DiscordTextComponent(TextComponentStyle.Small, "code", "Code", "123456", ext.Configuration.Digits, ext.Configuration.Digits));
await evt.Interaction.CreateInteractionModalResponseAsync(builder);

var response = new TwoFactorResponse()
{
Client = client
};

var inter = await client.GetInteractivity().WaitForModalAsync(builder.CustomId, TimeSpan.FromSeconds(ext.Configuration.TwoFactorTimeout));
if (inter.TimedOut)
{
response.Result = TwoFactorResult.TimedOut;
return response;
}

response.Interaction = inter.Result;

if (ext.Configuration.ResponseConfiguration.ShowResponse)
await inter.Result.Interaction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral().WithContent("Checking.."));
var res = ext.IsValidCode(evt.User.Id, inter.Result.Interaction.Data.Components[0].Value);
if (res)
{
if (ext.Configuration.ResponseConfiguration.ShowResponse)
await inter.Result.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationSuccessMessage));

response.Result = TwoFactorResult.ValidCode;
return response;
}

if (ext.Configuration.ResponseConfiguration.ShowResponse)
await inter.Result.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(ext.Configuration.ResponseConfiguration.AuthenticationFailureMessage));

response.Result = TwoFactorResult.InvalidCode;
return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
using DisCatSharp.Attributes;
using DisCatSharp.CommandsNext;
using DisCatSharp.Extensions.TwoFactorCommands.Enums;
using DisCatSharp.Extensions.TwoFactorCommands.Properties;

namespace DisCatSharp.Extensions.TwoFactorCommands.CommandsNext;

Expand All @@ -35,11 +36,11 @@ public static class TwoFactorCommandsNextExtension
/// <para>Asks the user via private for the two factor code.</para>
/// <para>This uses DisCatSharp.Interactivity.</para>
/// <para>To be used for commands next.</para>
/// <para><note type="caution">Not implemented yet. Returns <see cref="TwoFactorResponse.NotImplemented"/>.</note></para>
/// <para><note type="caution">Not implemented yet. Returns <see cref="TwoFactorResult.NotImplemented"/>.</note></para>
/// </summary>
/// <param name="ctx">The command context.</param>
/// <returns>A <see cref="TwoFactorResponse"/>.</returns>
[Experimental("No support for this yet. Not implemented")]
public static async Task<TwoFactorResponse> RequestTwoFactorAsync(CommandContext ctx)
=> await Task.FromResult(TwoFactorResponse.NotImplemented);
=> await Task.FromResult(new TwoFactorResponse() { Result = TwoFactorResult.NotImplemented });
}
TheXorog marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// This file is part of the DisCatSharp project.
//
// Copyright (c) 2021-2023 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DisCatSharp.Entities;
using DisCatSharp.EventArgs;
using DisCatSharp.Extensions.TwoFactorCommands.Enums;

namespace DisCatSharp.Extensions.TwoFactorCommands.Properties;

/// <summary>
/// The response given upon attempted two factor authentication.
/// </summary>
public class TwoFactorResponse
{
/// <summary>
/// The modal response <see cref="ComponentInteractionCreateEventArgs"/>. Null if <see cref="Result"/> is <see cref="TwoFactorResult.NotEnrolled"/> or <see cref="TwoFactorResult.TimedOut"/>.
/// </summary>
public ComponentInteractionCreateEventArgs Interaction { get; internal set; } = null;

/// <summary>
/// The <see cref="DiscordClient"/> this interaction took place with.
/// </summary>
public DiscordClient Client { get; internal set; } = null;

/// <summary>
/// The <see cref="TwoFactorResult"/> of the two factor authentication.
/// </summary>
public TwoFactorResult Result { get; internal set; } = TwoFactorResult.TimedOut;

internal TwoFactorResponse() { }
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ public TwoFactorConfiguration(TwoFactorConfiguration other)
/// </summary>
public sealed class TwoFactorResponseConfiguration
{
/// <summary>
/// <para>Whether to show a response after entering a two factor code. If set to false, you'll need to respond to the modal interaction yourself.</para>
/// <para>Defaults to: true</para>
/// </summary>
public bool ShowResponse { internal get; set; } = true;

/// <summary>
/// <para>Sets the message when an correct two factor auth code was entered.</para>
/// <para>Defaults to: Code valid!</para>
Expand All @@ -124,6 +130,12 @@ public sealed class TwoFactorResponseConfiguration
/// </summary>
public string AuthenticationFailureMessage { internal get; set; } = "Code invalid..";

/// <summary>
/// <para>Sets the message when an user is not yet enrolled into two factor auth.</para>
/// <para>Defaults to: You are not enrolled in two factor.</para>
/// </summary>
public string AuthenticationNotEnrolledMessage { internal get; set; } = "You are not enrolled in two factor.";

/// <summary>
/// <para>Sets the modal title for two factor auth requests.</para>
/// <para>Defaults to: Enter 2FA Code</para>
Expand Down