feat(CodeGenerator): Die Methoden GenerateTotpSecretKey, GenerateTotpQrCode und GenerateTotpQrCode wurden als Schnittstellenimplementierung hinzugefügt.

This commit is contained in:
Developer 02
2024-12-10 22:05:52 +01:00
parent 1657a99aa6
commit 085f37de16
6 changed files with 65 additions and 14 deletions

View File

@@ -1,21 +1,26 @@
using EnvelopeGenerator.Application.Configurations;
using EnvelopeGenerator.Application.Contracts;
using Microsoft.Extensions.Options;
using OtpNet;
using QRCoder;
using System.Text;
namespace EnvelopeGenerator.Application.Services
{
public class CodeGenerator : ICodeGenerator
{
public static Lazy<CodeGenerator> LazyStatic => new(() => new CodeGenerator(Options.Create<CodeGeneratorConfig>(new())));
public static Lazy<CodeGenerator> LazyStatic => new(() => new CodeGenerator(Options.Create<CodeGeneratorParams>(new()), new QRCodeGenerator()));
public static CodeGenerator Static => LazyStatic.Value;
private readonly string _charPool;
private readonly CodeGeneratorParams _params;
public CodeGenerator(IOptions<CodeGeneratorConfig> options)
private readonly QRCodeGenerator _qrCodeGenerator;
public CodeGenerator(IOptions<CodeGeneratorParams> options, QRCodeGenerator qrCodeGenerator)
{
_charPool = options.Value.CharPool;
_params = options.Value;
_qrCodeGenerator = qrCodeGenerator;
}
public string GenerateCode(int length)
@@ -29,9 +34,33 @@ namespace EnvelopeGenerator.Application.Services
var passwordBuilder = new StringBuilder(length);
for (int i = 0; i < length; i++)
passwordBuilder.Append(_charPool[random.Next(_charPool.Length)]);
passwordBuilder.Append(_params.CharPool[random.Next(_params.CharPool.Length)]);
return passwordBuilder.ToString();
}
public string GenerateTotpSecretKey(int? length = null)
=> Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(length ?? _params.DefaultTotpSecretKeyLength));
public byte[] GenerateTotpQrCode(string userEmail, string secretKey, string? issuer = null, string? totpUrlFormat = null, int? pixelsPerModule = null)
{
var url = string.Format(totpUrlFormat ?? _params.TotpUrlFormat,
Uri.EscapeDataString(userEmail),
Uri.EscapeDataString(secretKey),
Uri.EscapeDataString(issuer ?? _params.TotpIssuer));
using var qrCodeData = _qrCodeGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
using var qrCode = new BitmapByteQRCode(qrCodeData);
return qrCode.GetGraphic(pixelsPerModule ?? _params.TotpQRPixelsPerModule);
}
public byte[] GenerateTotpQrCode(string userEmail, int? length = null, string? issuer = null, string? totpUrlFormat = null, int? pixelsPerModule = null)
{
return GenerateTotpQrCode(
userEmail: userEmail,
secretKey: GenerateTotpSecretKey(length: length),
issuer: issuer,
totpUrlFormat: totpUrlFormat,
pixelsPerModule: pixelsPerModule);
}
}
}