using Google.Authenticator; using Microsoft.Extensions.Options; using Project.Application.DTOs.TwoFactorAuth; using Project.Application.Interfaces; using Project.Application.Options; using Project.Infrastructure.Interfaces; namespace Project.Application.Services { public class TwoFactorAuthService : ITwoFactorAuthService { // FIELDS FOR CTOR private readonly TwoFactorAuthenticator _twoFactorAuthenticator; private readonly ITwoFactorAuthRepository _twoFactorAuthRepository; private readonly string _issuer; // CTOR public TwoFactorAuthService(IOptions options, ITwoFactorAuthRepository twoFactorAuthRepository) { _twoFactorAuthenticator = new TwoFactorAuthenticator(); _twoFactorAuthRepository = twoFactorAuthRepository; _issuer = options.Value.Issuer; } //public void TwoFactorAuthenticatorMethods() //{ // _twoFactorAuthenticator.Equals(); // _twoFactorAuthenticator.GeneratePINAtInterval(); // _twoFactorAuthenticator.GenerateSetupCode(); // _twoFactorAuthenticator.GetCurrentPIN(); // _twoFactorAuthenticator.GetCurrentPINs(); // _twoFactorAuthenticator.GetHashCode(); // _twoFactorAuthenticator.GetType(); // _twoFactorAuthenticator.ToString(); // _twoFactorAuthenticator.ValidateTwoFactorPIN(); //} // GENERATE TWO FACTOR AUTH SETUP public async Task GenerateSetupCodeAsync(string userEmail) { var userSecretKey = Guid.NewGuid().ToString(); var setupInfo = _twoFactorAuthenticator.GenerateSetupCode( _issuer, // Envelope.Configuration.ApplicationName userEmail, // user.Email userSecretKey, false, 10); string manualEntryKey = setupInfo.ManualEntryKey; string qrCodeImageUrl = setupInfo.QrCodeSetupImageUrl; await _twoFactorAuthRepository.SaveSecretKeyAsync(userEmail, userSecretKey); return new TwoFactorSetupDto { SecretKey = userSecretKey, QrCodeImageUrl = qrCodeImageUrl, ManualEntryKey = manualEntryKey }; } // VALIDATE OTP public async Task ValidateCodeAsync(string userEmail, string userInputCode) { var secretKey = await _twoFactorAuthRepository.GetSecretKeyAsync(userEmail); if (string.IsNullOrEmpty(secretKey)) { throw new InvalidOperationException("Secret key not found!"); } return _twoFactorAuthenticator.ValidateTwoFactorPIN(secretKey, userInputCode); } //// SAVE SECRET KEY //public async Task SaveSecretKeyAsync(string userEmail, string userSecretKey) //{ // var user = await _twoFactorAuthRepository.GetUserByEmailAsync(userEmail); // if (user == null) // { // throw new InvalidOperationException("User not found!"); // } // await _twoFactorAuthRepository.SaveSecretKeyAsync(userEmail, userSecretKey); //} // GET SECRET KEY public async Task GetSecretKeyAsync(string userEmail) { var secretKey = await _twoFactorAuthRepository.GetSecretKeyAsync(userEmail); return secretKey; } } }