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