mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-04-15 00:12:50 +08:00
Custom mask for secret (#970)
* Masking Character added, not yet used. * Setting the masking character can be chained with other extensions. * Added string extension for masking, and replaced hardcoded asterisks. * Check if mask is null first. * Fixed Typo in previous test and added new test for custom masks. * Added tests for masking with null character * Added docs and example. * Adjusted extensions so that Mask is integrated into Secret extension. Updated Exampls and Tests accordingly
This commit is contained in:
parent
088db165ed
commit
eb02c3d534
@ -63,6 +63,23 @@ What's the secret number? _
|
||||
|
||||
```text
|
||||
Enter password: ************_
|
||||
```
|
||||
|
||||
## Masks
|
||||
|
||||
<?# Example symbol="M:Prompt.Program.AskPasswordWithCustomMask" project="Prompt" /?>
|
||||
|
||||
|
||||
```text
|
||||
Enter password: ------------_
|
||||
```
|
||||
|
||||
You can utilize a null character to completely hide input.
|
||||
|
||||
<?# Example symbol="M:Prompt.Program.AskPasswordWithNullMask" project="Prompt" /?>
|
||||
|
||||
```text
|
||||
Enter password: _
|
||||
```
|
||||
|
||||
## Optional
|
||||
|
@ -33,7 +33,13 @@ namespace Prompt
|
||||
var age = AskAge();
|
||||
|
||||
WriteDivider("Secrets");
|
||||
var password = AskPassword();
|
||||
var password = AskPassword();
|
||||
|
||||
WriteDivider("Mask");
|
||||
var mask = AskPasswordWithCustomMask();
|
||||
|
||||
WriteDivider("Null Mask");
|
||||
var nullMask = AskPasswordWithNullMask();
|
||||
|
||||
WriteDivider("Optional");
|
||||
var color = AskColor();
|
||||
@ -48,7 +54,9 @@ namespace Prompt
|
||||
.AddRow("[grey]Favorite fruit[/]", fruit)
|
||||
.AddRow("[grey]Favorite sport[/]", sport)
|
||||
.AddRow("[grey]Age[/]", age.ToString())
|
||||
.AddRow("[grey]Password[/]", password)
|
||||
.AddRow("[grey]Password[/]", password)
|
||||
.AddRow("[grey]Mask[/]", mask)
|
||||
.AddRow("[grey]Null Mask[/]", nullMask)
|
||||
.AddRow("[grey]Favorite color[/]", string.IsNullOrEmpty(color) ? "Unknown" : color));
|
||||
}
|
||||
|
||||
@ -145,6 +153,22 @@ namespace Prompt
|
||||
new TextPrompt<string>("Enter [green]password[/]?")
|
||||
.PromptStyle("red")
|
||||
.Secret());
|
||||
}
|
||||
|
||||
public static string AskPasswordWithCustomMask()
|
||||
{
|
||||
return AnsiConsole.Prompt(
|
||||
new TextPrompt<string>("Enter [green]password[/]?")
|
||||
.PromptStyle("red")
|
||||
.Secret('-'));
|
||||
}
|
||||
|
||||
public static string AskPasswordWithNullMask()
|
||||
{
|
||||
return AnsiConsole.Prompt(
|
||||
new TextPrompt<string>("Enter [green]password[/]?")
|
||||
.PromptStyle("red")
|
||||
.Secret(null));
|
||||
}
|
||||
|
||||
public static string AskColor()
|
||||
|
@ -5,7 +5,7 @@ namespace Spectre.Console;
|
||||
/// </summary>
|
||||
public static partial class AnsiConsoleExtensions
|
||||
{
|
||||
internal static async Task<string> ReadLine(this IAnsiConsole console, Style? style, bool secret, IEnumerable<string>? items = null, CancellationToken cancellationToken = default)
|
||||
internal static async Task<string> ReadLine(this IAnsiConsole console, Style? style, bool secret, char? mask, IEnumerable<string>? items = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (console is null)
|
||||
{
|
||||
@ -60,8 +60,9 @@ public static partial class AnsiConsoleExtensions
|
||||
|
||||
if (!char.IsControl(key.KeyChar))
|
||||
{
|
||||
text += key.KeyChar.ToString();
|
||||
console.Write(secret ? "*" : key.KeyChar.ToString(), style);
|
||||
text += key.KeyChar.ToString();
|
||||
var output = key.KeyChar.ToString();
|
||||
console.Write(secret ? output.Mask(mask) : output, style);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -185,5 +185,28 @@ public static class StringExtensions
|
||||
#else
|
||||
return text.Contains(value, StringComparison.Ordinal);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Masks" every character in a string.
|
||||
/// </summary>
|
||||
/// <param name="value">String value to mask.</param>
|
||||
/// <param name="mask">Character to use for masking.</param>
|
||||
/// <returns>Masked string.</returns>
|
||||
public static string Mask(this string value, char? mask)
|
||||
{
|
||||
var output = string.Empty;
|
||||
|
||||
if (mask is null)
|
||||
{
|
||||
return output;
|
||||
}
|
||||
|
||||
foreach (var c in value)
|
||||
{
|
||||
output += mask;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
@ -28,7 +28,13 @@ public sealed class TextPrompt<T> : IPrompt<T>
|
||||
/// Gets or sets a value indicating whether input should
|
||||
/// be hidden in the console.
|
||||
/// </summary>
|
||||
public bool IsSecret { get; set; }
|
||||
public bool IsSecret { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the character to use while masking
|
||||
/// a secret prompt.
|
||||
/// </summary>
|
||||
public char? Mask { get; set; } = '*';
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the validation error message.
|
||||
@ -119,14 +125,15 @@ public sealed class TextPrompt<T> : IPrompt<T>
|
||||
|
||||
while (true)
|
||||
{
|
||||
var input = await console.ReadLine(promptStyle, IsSecret, choices, cancellationToken).ConfigureAwait(false);
|
||||
var input = await console.ReadLine(promptStyle, IsSecret, Mask, choices, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Nothing entered?
|
||||
if (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
if (DefaultValue != null)
|
||||
{
|
||||
console.Write(IsSecret ? "******" : converter(DefaultValue.Value), promptStyle);
|
||||
{
|
||||
var defaultValue = converter(DefaultValue.Value);
|
||||
console.Write(IsSecret ? defaultValue.Mask(Mask) : defaultValue, promptStyle);
|
||||
console.WriteLine();
|
||||
return DefaultValue.Value;
|
||||
}
|
||||
@ -201,13 +208,14 @@ public sealed class TextPrompt<T> : IPrompt<T>
|
||||
{
|
||||
appendSuffix = true;
|
||||
var converter = Converter ?? TypeConverterHelper.ConvertToString;
|
||||
var defaultValueStyle = DefaultValueStyle?.ToMarkup() ?? "green";
|
||||
var defaultValueStyle = DefaultValueStyle?.ToMarkup() ?? "green";
|
||||
var defaultValue = converter(DefaultValue.Value);
|
||||
|
||||
builder.AppendFormat(
|
||||
CultureInfo.InvariantCulture,
|
||||
" [{0}]({1})[/]",
|
||||
defaultValueStyle,
|
||||
IsSecret ? "******" : converter(DefaultValue.Value));
|
||||
IsSecret ? defaultValue.Mask(Mask) : defaultValue);
|
||||
}
|
||||
|
||||
var markup = builder.ToString().Trim();
|
||||
|
@ -286,6 +286,25 @@ public static class TextPromptExtensions
|
||||
|
||||
obj.IsSecret = true;
|
||||
return obj;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces prompt user input with mask in the console.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The prompt type.</typeparam>
|
||||
/// <param name="obj">The prompt.</param>
|
||||
/// <param name="mask">The masking character to use for the secret.</param>
|
||||
/// <returns>The same instance so that multiple calls can be chained.</returns>
|
||||
public static TextPrompt<T> Secret<T>(this TextPrompt<T> obj, char? mask)
|
||||
{
|
||||
if (obj is null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(obj));
|
||||
}
|
||||
|
||||
obj.IsSecret = true;
|
||||
obj.Mask = mask;
|
||||
return obj;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -0,0 +1 @@
|
||||
Favorite fruit? (------): ------
|
@ -0,0 +1 @@
|
||||
Favorite fruit? ():
|
@ -233,7 +233,7 @@ public sealed class TextPromptTests
|
||||
|
||||
[Fact]
|
||||
[Expectation("SecretDefaultValue")]
|
||||
public Task Should_Chose_Masked_Default_Value_If_Nothing_Is_Entered_And_Prompt_Is_Secret()
|
||||
public Task Should_Choose_Masked_Default_Value_If_Nothing_Is_Entered_And_Prompt_Is_Secret()
|
||||
{
|
||||
// Given
|
||||
var console = new TestConsole();
|
||||
@ -247,6 +247,42 @@ public sealed class TextPromptTests
|
||||
|
||||
// Then
|
||||
return Verifier.Verify(console.Output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
[Expectation("SecretDefaultValueCustomMask")]
|
||||
public Task Should_Choose_Custom_Masked_Default_Value_If_Nothing_Is_Entered_And_Prompt_Is_Secret_And_Mask_Is_Custom()
|
||||
{
|
||||
// Given
|
||||
var console = new TestConsole();
|
||||
console.Input.PushKey(ConsoleKey.Enter);
|
||||
|
||||
// When
|
||||
console.Prompt(
|
||||
new TextPrompt<string>("Favorite fruit?")
|
||||
.Secret('-')
|
||||
.DefaultValue("Banana"));
|
||||
|
||||
// Then
|
||||
return Verifier.Verify(console.Output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
[Expectation("SecretDefaultValueNullMask")]
|
||||
public Task Should_Choose_Empty_Masked_Default_Value_If_Nothing_Is_Entered_And_Prompt_Is_Secret_And_Mask_Is_Null()
|
||||
{
|
||||
// Given
|
||||
var console = new TestConsole();
|
||||
console.Input.PushKey(ConsoleKey.Enter);
|
||||
|
||||
// When
|
||||
console.Prompt(
|
||||
new TextPrompt<string>("Favorite fruit?")
|
||||
.Secret(null)
|
||||
.DefaultValue("Banana"));
|
||||
|
||||
// Then
|
||||
return Verifier.Verify(console.Output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
Loading…
x
Reference in New Issue
Block a user