using System.Text; namespace LehrerApp.Api; internal static class Cli { public static Task RunCreateUserAsync(string dataPath, string[] args) { if (args.Length < 2) { Console.Error.WriteLine("Verwendung: create-user [--password ]"); return Task.FromResult(1); } var username = args[1]; var password = ParsePassword(args); if (password is null) return Task.FromResult(1); Directory.CreateDirectory(dataPath); using var store = new UserStore(dataPath); if (!store.CreateUser(username, password)) { Console.Error.WriteLine($"Nutzer '{username}' existiert bereits."); return Task.FromResult(1); } Console.WriteLine($"Nutzer '{username}' angelegt."); return Task.FromResult(0); } public static Task RunSetPasswordAsync(string dataPath, string[] args) { if (args.Length < 2) { Console.Error.WriteLine("Verwendung: set-password [--password ]"); return Task.FromResult(1); } var username = args[1]; var password = ParsePassword(args); if (password is null) return Task.FromResult(1); Directory.CreateDirectory(dataPath); using var store = new UserStore(dataPath); if (!store.SetPassword(username, password)) { Console.Error.WriteLine($"Nutzer '{username}' existiert nicht."); return Task.FromResult(1); } Console.WriteLine($"Passwort für '{username}' aktualisiert."); return Task.FromResult(0); } private static string? ParsePassword(string[] args) { string? password = null; for (var i = 2; i < args.Length - 1; i++) if (args[i] == "--password") password = args[i + 1]; password ??= ReadPassword("Passwort (mind. 12 Zeichen): "); if (string.IsNullOrWhiteSpace(password) || password.Length < 12) { Console.Error.WriteLine("Passwort muss mindestens 12 Zeichen lang sein."); return null; } return password; } // docker exec ohne -it liefert kein TTY -> ReadKey wäre nicht möglich, dann normal lesen. private static string ReadPassword(string prompt) { Console.Write(prompt); if (Console.IsInputRedirected) return Console.ReadLine() ?? ""; var sb = new StringBuilder(); ConsoleKeyInfo key; while ((key = Console.ReadKey(intercept: true)).Key != ConsoleKey.Enter) { if (key.Key == ConsoleKey.Backspace && sb.Length > 0) { sb.Length--; Console.Write("\b \b"); } else if (!char.IsControl(key.KeyChar)) { sb.Append(key.KeyChar); Console.Write('*'); } } Console.WriteLine(); return sb.ToString(); } }