Update MudBlazor integration, improve captcha handling, and upgrade project dependencies

This commit is contained in:
masoodafar-web
2025-11-14 09:32:19 +03:30
parent cce59612fa
commit 07ea8f0f47
15 changed files with 456 additions and 395 deletions

View File

@@ -1,20 +1,20 @@
using Blazored.LocalStorage;
using FrontOffice.BFF.User.Protobuf.Protos.User;
using FrontOffice.BFF.User.Protobuf.Validator;
using FrontOffice.Main.Utilities;
using Grpc.Core;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.WebUtilities;
using MudBlazor;
using MetadataAlias = Grpc.Core.Metadata; // resolve ambiguity with MudBlazor.Metadata
namespace FrontOffice.Main.Shared;
public partial class AuthDialog : IDisposable
{
[Parameter]
public bool HideCancelButton { get; set; } = false;
[Parameter] public bool HideCancelButton { get; set; }
[Parameter] public bool EnableCaptcha { get; set; }
[Parameter] public bool InlineMode { get; set; }
private enum AuthStep { Phone, Verify }
public enum AuthStep { Phone, Verify }
private const int DefaultResendCooldown = 120;
public const int MaxVerificationAttempts = 5;
private const string PhoneStorageKey = "auth:phone-number";
@@ -22,14 +22,14 @@ public partial class AuthDialog : IDisposable
private const string TokenStorageKey = "auth:token";
private const string OtpPurpose = "Login";
private AuthStep _currentStep = AuthStep.Phone;
public AuthStep _currentStep = AuthStep.Phone;
private CreateNewOtpTokenRequestValidator _phoneRequestValidator = new();
private CreateNewOtpTokenRequest _phoneRequest = new();
private readonly CreateNewOtpTokenRequestValidator _phoneRequestValidator = new();
private readonly CreateNewOtpTokenRequest _phoneRequest = new();
private MudForm? _phoneForm;
private VerifyOtpTokenRequestValidator _verifyRequestValidator = new();
private VerifyOtpTokenRequest _verifyRequest = new();
private readonly VerifyOtpTokenRequestValidator _verifyRequestValidator = new();
private readonly VerifyOtpTokenRequest _verifyRequest = new();
private MudForm? _verifyForm;
private bool _isBusy;
@@ -41,10 +41,14 @@ public partial class AuthDialog : IDisposable
private int _attemptsLeft = MaxVerificationAttempts;
private CancellationTokenSource? _operationCts;
// Captcha fields
private string? _captchaCode;
private string? _captchaInput;
[Inject] private ILocalStorageService LocalStorage { get; set; } = default!;
[Inject] private UserContract.UserContractClient UserClient { get; set; } = default!;
[CascadingParameter] private MudDialogInstance MudDialog { get; set; } = default!;
[CascadingParameter] private IDialogReference? MudDialog { get; set; }
[Parameter] public EventCallback OnLoginSuccess { get; set; }
@@ -55,6 +59,11 @@ public partial class AuthDialog : IDisposable
_phoneRequest.Purpose = OtpPurpose;
_verifyRequest.Purpose = OtpPurpose;
if (EnableCaptcha)
{
GenerateCaptcha();
}
var storedPhone = await LocalStorage.GetItemAsync<string>(PhoneStorageKey);
if (!string.IsNullOrWhiteSpace(storedPhone))
{
@@ -62,7 +71,13 @@ public partial class AuthDialog : IDisposable
}
}
private async Task SendOtpAsync()
private void GenerateCaptcha()
{
_captchaCode = Guid.NewGuid().ToString("N")[..6].ToUpperInvariant();
_captchaInput = string.Empty;
}
public async Task SendOtpAsync()
{
_errorMessage = null;
if (_phoneForm is null)
@@ -72,6 +87,15 @@ public partial class AuthDialog : IDisposable
if (!_phoneForm.IsValid)
return;
if (EnableCaptcha)
{
if (string.IsNullOrWhiteSpace(_captchaInput) || !string.Equals(_captchaInput.Trim(), _captchaCode, StringComparison.OrdinalIgnoreCase))
{
_errorMessage = "کد کپچا صحیح نیست.";
return;
}
}
_isBusy = true;
_operationCts?.Cancel();
_operationCts?.Dispose();
@@ -87,15 +111,9 @@ public partial class AuthDialog : IDisposable
}
var metadata = await BuildAuthMetadataAsync();
CreateNewOtpTokenResponse response;
if (metadata is not null)
{
response = await UserClient.CreateNewOtpTokenAsync(_phoneRequest, metadata, cancellationToken: _operationCts.Token);
}
else
{
response = await UserClient.CreateNewOtpTokenAsync(_phoneRequest, cancellationToken: _operationCts.Token);
}
CreateNewOtpTokenResponse response = metadata is not null
? await UserClient.CreateNewOtpTokenAsync(_phoneRequest, metadata, cancellationToken: _operationCts.Token)
: await UserClient.CreateNewOtpTokenAsync(_phoneRequest, cancellationToken: _operationCts.Token);
if (response?.Success != true)
{
@@ -118,6 +136,7 @@ public partial class AuthDialog : IDisposable
}
catch (OperationCanceledException)
{
// ignored - user canceled operation
}
catch (Exception ex)
{
@@ -131,28 +150,28 @@ public partial class AuthDialog : IDisposable
}
}
private async Task VerifyOtpAsync()
public async Task<bool> VerifyOtpAsync()
{
_errorMessage = null;
_infoMessage = null;
if (_verifyForm is null)
return;
return false;
await _verifyForm.Validate();
if (!_verifyForm.IsValid)
return;
return false;
if (IsVerificationLocked)
{
_errorMessage = "تعداد تلاش‌های مجاز به پایان رسیده است. لطفاً رمز جدید دریافت کنید.";
return;
return false;
}
if (string.IsNullOrWhiteSpace(_phoneNumber))
{
_errorMessage = "شماره موبایل یافت نشد. لطفاً دوباره تلاش کنید.";
return;
return false;
}
_isBusy = true;
@@ -162,7 +181,6 @@ public partial class AuthDialog : IDisposable
{
_verifyRequest.Mobile = _phoneNumber;
// Check for stored referral code and add it to the request
var storedReferralCode = await LocalStorage.GetItemAsync<string>("referral:code");
if (!string.IsNullOrWhiteSpace(storedReferralCode))
{
@@ -173,24 +191,18 @@ public partial class AuthDialog : IDisposable
if (!validationResult.IsValid)
{
_errorMessage = string.Join(" ", validationResult.Errors.Select(e => e.ErrorMessage).Distinct());
return;
return false;
}
var metadata = await BuildAuthMetadataAsync();
VerifyOtpTokenResponse response;
if (metadata is not null)
{
response = await UserClient.VerifyOtpTokenAsync(_verifyRequest, metadata, cancellationToken: cancellationToken);
}
else
{
response = await UserClient.VerifyOtpTokenAsync(_verifyRequest, cancellationToken: cancellationToken);
}
VerifyOtpTokenResponse response = metadata is not null
? await UserClient.VerifyOtpTokenAsync(_verifyRequest, metadata, cancellationToken: cancellationToken)
: await UserClient.VerifyOtpTokenAsync(_verifyRequest, cancellationToken: cancellationToken);
if (response is null)
{
_errorMessage = "تأیید رمز پویا انجام نشد. لطفاً دوباره تلاش کنید.";
return;
return false;
}
if (response.Success)
@@ -206,16 +218,17 @@ public partial class AuthDialog : IDisposable
await LocalStorage.RemoveItemAsync(PhoneStorageKey);
await LocalStorage.RemoveItemAsync(RedirectStorageKey);
// Clear referral code after successful registration/login
await LocalStorage.RemoveItemAsync("referral:code");
_attemptsLeft = MaxVerificationAttempts;
_verifyRequest.Code = string.Empty;
await OnLoginSuccess.InvokeAsync();
MudDialog.Close();
return;
if (!InlineMode)
{
MudDialog?.Close();
}
return true;
}
RegisterFailedAttempt(string.IsNullOrWhiteSpace(response.Message) ? "کد نادرست است." : response.Message);
@@ -226,6 +239,7 @@ public partial class AuthDialog : IDisposable
}
catch (OperationCanceledException)
{
// ignored - user canceled operation
}
catch (Exception ex)
{
@@ -237,6 +251,8 @@ public partial class AuthDialog : IDisposable
ClearOperationToken();
await InvokeAsync(StateHasChanged);
}
return false;
}
private async Task HandleVerificationFailureAsync(RpcException rpcEx)
@@ -269,23 +285,15 @@ public partial class AuthDialog : IDisposable
private void RegisterFailedAttempt(string baseMessage)
{
_attemptsLeft = Math.Max(0, _attemptsLeft - 1);
if (_attemptsLeft > 0)
{
_errorMessage = $"{baseMessage} {_attemptsLeft} تلاش باقی مانده است.";
}
else
{
_errorMessage = $"{baseMessage} تلاش‌های مجاز شما به پایان رسیده است. لطفاً رمز جدید دریافت کنید.";
}
_errorMessage = _attemptsLeft > 0
? $"{baseMessage} {_attemptsLeft} تلاش باقی مانده است."
: $"{baseMessage} تلاش‌های مجاز شما به پایان رسیده است. لطفاً رمز جدید دریافت کنید.";
}
private async Task ResendOtpAsync()
{
if (_resendRemaining > 0 || _isBusy || string.IsNullOrWhiteSpace(_phoneNumber))
{
return;
}
_errorMessage = null;
_infoMessage = null;
@@ -294,22 +302,11 @@ public partial class AuthDialog : IDisposable
try
{
var request = new CreateNewOtpTokenRequest
{
Mobile = _phoneNumber,
Purpose = OtpPurpose
};
var request = new CreateNewOtpTokenRequest { Mobile = _phoneNumber, Purpose = OtpPurpose };
var metadata = await BuildAuthMetadataAsync();
CreateNewOtpTokenResponse response;
if (metadata is not null)
{
response = await UserClient.CreateNewOtpTokenAsync(request, metadata, cancellationToken: cancellationToken);
}
else
{
response = await UserClient.CreateNewOtpTokenAsync(request, cancellationToken: cancellationToken);
}
CreateNewOtpTokenResponse response = metadata is not null
? await UserClient.CreateNewOtpTokenAsync(request, metadata, cancellationToken: cancellationToken)
: await UserClient.CreateNewOtpTokenAsync(request, cancellationToken: cancellationToken);
if (response?.Success != true)
{
@@ -319,10 +316,7 @@ public partial class AuthDialog : IDisposable
return;
}
_infoMessage = string.IsNullOrWhiteSpace(response.Message)
? "کد جدید ارسال شد."
: response.Message;
_infoMessage = string.IsNullOrWhiteSpace(response.Message) ? "کد جدید ارسال شد." : response.Message;
_attemptsLeft = MaxVerificationAttempts;
_verifyRequest.Code = string.Empty;
StartResendCountdown();
@@ -333,6 +327,7 @@ public partial class AuthDialog : IDisposable
}
catch (OperationCanceledException)
{
// ignored
}
catch (Exception ex)
{
@@ -373,6 +368,8 @@ public partial class AuthDialog : IDisposable
_resendTimer?.Dispose();
_resendTimer = null;
_resendRemaining = 0;
if (EnableCaptcha)
GenerateCaptcha();
}
private void StartResendCountdown(int seconds = DefaultResendCooldown)
@@ -388,23 +385,15 @@ public partial class AuthDialog : IDisposable
_resendTimer?.Dispose();
_resendTimer = null;
}
_ = InvokeAsync(StateHasChanged);
}, null, 1000, 1000);
}
private async Task<Metadata?> BuildAuthMetadataAsync()
private async Task<MetadataAlias?> BuildAuthMetadataAsync()
{
var token = await LocalStorage.GetItemAsync<string>(TokenStorageKey);
if (string.IsNullOrWhiteSpace(token))
{
return null;
}
return new Metadata
{
{ "Authorization", $"Bearer {token}" }
};
if (string.IsNullOrWhiteSpace(token)) return null;
return new MetadataAlias { { "Authorization", $"Bearer {token}" } };
}
private async Task ResetAuthenticationAsync()
@@ -430,7 +419,8 @@ public partial class AuthDialog : IDisposable
private void Cancel()
{
MudDialog.Cancel();
if (!InlineMode)
MudDialog?.Close(DialogResult.Cancel());
}
public void Dispose()
@@ -438,9 +428,9 @@ public partial class AuthDialog : IDisposable
_operationCts?.Cancel();
_operationCts?.Dispose();
_operationCts = null;
_resendTimer?.Dispose();
_resendTimer = null;
}
private string GetDialogTitle() => _currentStep == AuthStep.Phone ? "ورود/ثبت‌نام به حساب کاربری" : "تأیید رمز پویا";
}
}