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,12 +1,63 @@
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h4" Align="Align.Center">@GetDialogTitle()</MudText>
@if (InlineMode)
{
@* Inline rendering without MudDialog wrapper *@
<MudStack Spacing="2">
<MudText Typo="Typo.h5" Align="Align.Center">@GetDialogTitle()</MudText>
@PhoneOrVerifyContent()
</MudStack>
}
else
{
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h4" Align="Align.Center">@GetDialogTitle()</MudText>
</TitleContent>
<DialogContent>
@PhoneOrVerifyContent()
</DialogContent>
<DialogActions>
@if (!HideCancelButton)
{
<MudButton Variant="Variant.Text"
OnClick="Cancel"
Disabled="_isBusy">لغو</MudButton>
}
@if (_currentStep == AuthStep.Phone)
{
<MudButton Variant="Variant.Filled"
Color="Color.Primary"
OnClick="SendOtpAsync"
Disabled="_isBusy"
FullWidth="true">
ارسال رمز پویا
</MudButton>
}
else if (_currentStep == AuthStep.Verify)
{
<MudButton Variant="Variant.Filled"
Color="Color.Primary"
OnClick="VerifyOtpAsync"
Disabled="_isBusy || IsVerificationLocked"
FullWidth="true">
تأیید و ورود
</MudButton>
}
</DialogActions>
</MudDialog>
}
@code {
private RenderFragment PhoneOrVerifyContent() => __builder =>
{
if (_currentStep == AuthStep.Phone)
{
<!-- Phone Step -->
<MudText Typo="Typo.body2" Class="mb-4" Align="Align.Center">لطفاً شماره موبایل خود را وارد کنید تا رمز پویا ارسال شود.</MudText>
// Phone Step
__builder.OpenComponent(0, typeof(MudText));
__builder.AddAttribute(1, "Typo", Typo.body2);
__builder.AddAttribute(2, "Class", "mb-4");
__builder.AddAttribute(3, "Align", Align.Center);
__builder.AddContent(4, "لطفاً شماره موبایل خود را وارد کنید تا رمز پویا ارسال شود.");
__builder.CloseComponent();
<MudForm @ref="_phoneForm" Model="_phoneRequest" Validation="@(_phoneRequestValidator.ValidateValue)">
<MudTextField @bind-Value="_phoneRequest.Mobile"
@@ -21,6 +72,21 @@
HelperText="مثال: 09121234567"
Class="mb-2" />
@if (EnableCaptcha)
{
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2" Class="mt-2 mb-2">
<MudPaper Elevation="1" Class="captcha-box d-flex align-center justify-center" Style="min-width:100px;min-height:48px;">
<MudText Typo="Typo.h5">@_captchaCode</MudText>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Refresh" Disabled="_isBusy" OnClick="GenerateCaptcha">
تازه‌سازی کد
</MudButton>
</MudStack>
<MudTextField Label="کد کپچا" Placeholder="کد نمایش داده شده" Immediate="true"
Variant="Variant.Outlined" @bind-Value="_captchaInput" Required="true"
RequiredError="لطفاً کد کپچا را وارد کنید." />
}
<MudCheckBox T="bool"
Label="شرایط و قوانین را می‌پذیرم"
Class="mb-1" />
@@ -33,7 +99,7 @@
}
else if (_currentStep == AuthStep.Verify)
{
<!-- Verify Step -->
// Verify Step
<MudText Typo="Typo.body2" Class="mb-4" Align="Align.Center">رمز پویا شش رقمی ارسال ‌شده به @_phoneNumber را وارد کنید.</MudText>
<MudForm @ref="_verifyForm" Model="_verifyRequest" Validation="@(_verifyRequestValidator.ValidateValue)">
@@ -50,85 +116,28 @@
Class="mb-2"
MaxLength="6" />
@* <MudText Typo="Typo.body1" Align="Align.Center" Class="mb-2">
تلاش باقی‌مانده: @_attemptsLeft از @MaxVerificationAttempts
</MudText> *@
@if (!string.IsNullOrWhiteSpace(_errorMessage))
{
<MudAlert Severity="Severity.Error"
Dense="true"
Elevation="0"
Class="mb-2">
@(_errorMessage)
</MudAlert>
<MudAlert Severity="Severity.Error" Dense="true" Elevation="0" Class="mb-2">@(_errorMessage)</MudAlert>
}
@if (!string.IsNullOrWhiteSpace(_infoMessage))
{
<MudAlert Severity="Severity.Success"
Dense="true"
Elevation="0"
Class="mb-2">
@(_infoMessage)
</MudAlert>
<MudAlert Severity="Severity.Success" Dense="true" Elevation="0" Class="mb-2">@(_infoMessage)</MudAlert>
}
<MudStack Spacing="2">
<MudButton Variant="Variant.Text"
Color="Color.Secondary"
Disabled="_isBusy"
OnClick="ChangePhoneAsync">
تغییر شماره
</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Secondary" Disabled="_isBusy" OnClick="ChangePhoneAsync">تغییر شماره</MudButton>
</MudStack>
<MudDivider Class="my-2" />
@if (_resendRemaining > 0)
{
<MudText Typo="Typo.body2" Align="Align.Center" Class="mud-text-secondary">
امکان ارسال مجدد تا @_resendRemaining ثانیه دیگر
</MudText>
<MudText Typo="Typo.body2" Align="Align.Center" Class="mud-text-secondary">امکان ارسال مجدد تا @_resendRemaining ثانیه دیگر</MudText>
}
else
{
<MudButton Variant="Variant.Text"
Color="Color.Primary"
Disabled="_isBusy"
OnClick="ResendOtpAsync">
ارسال مجدد رمز پویا
</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Primary" Disabled="_isBusy" OnClick="ResendOtpAsync">ارسال مجدد رمز پویا</MudButton>
}
</MudForm>
}
</DialogContent>
<DialogActions>
@if (!HideCancelButton)
{
<MudButton Variant="Variant.Text"
OnClick="Cancel"
Disabled="_isBusy">لغو</MudButton>
}
@if (_currentStep == AuthStep.Phone)
{
<MudButton Variant="Variant.Filled"
Color="Color.Primary"
OnClick="SendOtpAsync"
Disabled="_isBusy"
FullWidth="true">
ارسال رمز پویا
</MudButton>
}
else if (_currentStep == AuthStep.Verify)
{
<MudButton Variant="Variant.Filled"
Color="Color.Primary"
OnClick="VerifyOtpAsync"
Disabled="_isBusy || IsVerificationLocked"
FullWidth="true">
تأیید و ورود
</MudButton>
}
</DialogActions>
</MudDialog>
};
}

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 ? "ورود/ثبت‌نام به حساب کاربری" : "تأیید رمز پویا";
}
}