Add MasterCommands

This commit is contained in:
2021-06-07 15:42:59 +02:00
parent 5893d86e13
commit 8027229a7f

View File

@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akari.Prototype.Server.Services;
using Akari.Prototype.Server.Utils;
using Akari.Prototype.Server.Utils.Extensions;
using CliFx;
using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Spectre.Console;
namespace Akari.Prototype.Server.Cli.Commands
{
[Command("m", Description = "Manage master password")]
public class MasterCommands : ICommand
{
[Command("m c", Description = "Create master password")]
public class CreateMasterPasswordCommand : ICommand
{
private readonly IMasterKeyService _masterKeyService;
public CreateMasterPasswordCommand(IMasterKeyService masterKeyService)
{
_masterKeyService = masterKeyService;
}
public ValueTask ExecuteAsync(IConsole console)
{
var ansiConsole = console.AsAnsiConsole();
if (_masterKeyService.IsPasswordSet)
{
throw new CommandException("Can't create master password if it's already set");
}
ansiConsole.WriteLine();
string password = ansiConsole.Prompt(
new TextPrompt<string>("Enter [yellow]master password[/]")
.PromptStyle("red")
.Secret()
);
string passwordConfirm = ansiConsole.Prompt(
new TextPrompt<string>("Confirm [yellow]master password[/]")
.PromptStyle("red")
.Secret()
);
ansiConsole.WriteLine();
if (password != passwordConfirm)
{
throw new CommandException("Password doesn't match");
}
if (!_masterKeyService.CreatePassword(password))
{
throw new CommandException("Created master password but can't login");
}
ansiConsole.Markup("[green]Successfully created [yellow]master password[/][/]");
return default;
}
}
[Command("m l", Description = "Login and check master password")]
public class LoginMasterPasswordCommand : ICommand
{
private readonly IMasterKeyService _masterKeyService;
public LoginMasterPasswordCommand(IMasterKeyService masterKeyService)
{
_masterKeyService = masterKeyService;
}
public ValueTask ExecuteAsync(IConsole console)
{
var ansiConsole = console.AsAnsiConsole();
if (!_masterKeyService.IsPasswordSet)
{
throw new CommandException("Can't login if no master password has been set");
}
ansiConsole.WriteLine();
if (!CliUtils.Login(_masterKeyService, ansiConsole))
{
ansiConsole.Markup("[red]Invalid [yellow]master password[/][/]");
}
else
{
ansiConsole.Markup("[green]Successfully logged in[/]");
}
return default;
}
}
private readonly IMasterKeyService _masterKeyService;
public MasterCommands(IMasterKeyService masterKeyService)
{
_masterKeyService = masterKeyService;
}
public ValueTask ExecuteAsync(IConsole console)
{
var ansiConsole = console.AsAnsiConsole();
if (!_masterKeyService.IsPasswordSet)
{
ansiConsole.Markup("[yellow]Master password[/] is not set");
}
else
{
ansiConsole.Markup("[yellow]Master password[/] is set");
}
return default;
}
}
}