| | | 1 | | using QRCoder; |
| | | 2 | | using Estud.Back.Domain.Identity; |
| | | 3 | | |
| | | 4 | | namespace Estud.Back.Features.Identity.GetTwoFactorKey; |
| | | 5 | | |
| | 34 | 6 | | public class GetTwoFactorKeyService(EstudDbContext ctx, UserManager<EstudUser> userManager) : IEstudService |
| | | 7 | | { |
| | | 8 | | public async Task<GetTwoFactorKeyOut> Get() |
| | | 9 | | { |
| | 34 | 10 | | var userId = ctx.RequestUser.Id; |
| | 34 | 11 | | var key = await ctx.GetUserTwoFactorKeyAsync(userId); |
| | 34 | 12 | | var user = await ctx.Users.Where(u => u.Id == userId).Select(x => new { x.Email, x.TwoFactorEnabled }).FirstOrDe |
| | | 13 | | |
| | 34 | 14 | | if (key == null) |
| | | 15 | | { |
| | 28 | 16 | | var estudUser = await userManager.Users.FirstAsync(u => u.Id == ctx.RequestUser.Id); |
| | 28 | 17 | | await userManager.ResetAuthenticatorKeyAsync(estudUser); |
| | 28 | 18 | | key = await userManager.GetAuthenticatorKeyAsync(estudUser); |
| | 28 | 19 | | } |
| | | 20 | | |
| | 34 | 21 | | return new() |
| | 34 | 22 | | { |
| | 34 | 23 | | Key = key!, |
| | 34 | 24 | | TwoFactorEnabled = user.TwoFactorEnabled, |
| | 34 | 25 | | QrCodeBase64 = GenerateQrCodeBase64(key, user.Email) |
| | 34 | 26 | | }; |
| | 34 | 27 | | } |
| | | 28 | | |
| | | 29 | | private static string GenerateQrCodeBase64(string key, string email) |
| | | 30 | | { |
| | | 31 | | const string provider = "Estud"; |
| | | 32 | | |
| | 34 | 33 | | using var qrGenerator = new QRCodeGenerator(); |
| | 34 | 34 | | using var qrCodeData = qrGenerator.CreateQrCode( |
| | 34 | 35 | | $"otpauth://totp/{provider}:{email}?secret={key}&issuer={provider}", |
| | 34 | 36 | | QRCodeGenerator.ECCLevel.Q |
| | 34 | 37 | | ); |
| | | 38 | | |
| | 34 | 39 | | var qrCode = new PngByteQRCode(qrCodeData); |
| | | 40 | | |
| | 34 | 41 | | var bytes = qrCode.GetGraphic(20); |
| | | 42 | | |
| | 34 | 43 | | return string.Format("data:image/png;base64,{0}", Convert.ToBase64String(bytes)); |
| | 34 | 44 | | } |
| | | 45 | | } |