@page "/profile" @attribute [Authorize] @layout MainLayout @implements IDisposable @using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse @using Complete2faSetupResponse = Heimdall.Application.DTOs.Complete2faSetupResponse @inject HeimdallApiClient Api @inject AuthState Auth @inject UiLanguageService Language @inject UiText Text @inject ISnackbar Snackbar @inject HeimdallAuthStateProvider AuthProvider @inject IJSRuntime JS @Text["Profile"] @if (_loading) { } else if (_error) { @Text["ProfileLoadFailed"] @Text["Retry"] } else if (_profile is not null) { @* ─── Section 1: Informations personnelles ─── *@ @Text["PersonalInformation"] @if (!string.IsNullOrEmpty(_profileError)) { @_profileError } @Text["Email"] @_profile.Email @Text["Theme"] @Text["Auto"] @Text["Light"] @Text["Dark"] @Text["Language"] @Text["French"] @Text["English"] @if (_saving) { } @Text["Save"] @* ─── Section 2: Statistiques du compte ─── *@ @Text["Profile_AccountStatistics"] @Text["RegisteredAt"] @_profile.CreatedAt.ToString("g", Language.Culture) @Text["EmailConfirmed"] @(_profile.EmailConfirmed ? Text["Yes"] : Text["No"]) @Text["TwoFactor"] @(_profile.TwoFactorEnabled ? Text["TwoFactorEnabled"] : Text["TwoFactorDisabled"]) @if (_profile.TwoFactorEnabled) { @if (_toggling2fa) { } @Text["DisableTwoFactor"] @if (_confirmDisable2fa) { @Text["ConfirmDisableTwoFactor"] @Text["Cancel"] } } else { @if (_toggling2fa) { } @Text["EnableTwoFactor"] @if (_confirmEnable2fa) { @Text["ConfirmTwoFactor"] @Text["Cancel"] } } @Text["Roles"] @if (_profile.Roles is not null && _profile.Roles.Count > 0) { foreach (var r in _profile.Roles) { @r } } else { @Text["NoRoles"] } @* ─── Section 3: Changer le mot de passe ─── *@ @Text["ChangePassword"] @if (!string.IsNullOrEmpty(_passwordError)) { @_passwordError } @if (_changingPassword) { } @Text["ChangePassword"] @* ─── Section 4: Notifications ─── *@ @Text["Notifications"] @if (!string.IsNullOrEmpty(_notifError)) { @_notifError } @Text["PushSetupInstructions"] @Text["YourTopic"] @(!string.IsNullOrWhiteSpace(_ntfyTopic) ? _ntfyTopic : $"heimdall_{_profile?.Id}") @Text["CustomizeTopic"] @Text["EmailChannel"] @Text["PushChannel"] @Text["Summaries"] @Text["EventTypes"] @Text["SelectNotificationEventTypes"] @Text["AllEventsIfNone"] @foreach (var et in EventTypes) { } @if (_savingNotif) { } @Text["Save"] @(_testingNtfy ? Text["TestRunning"] : Text["TestNtfy"]) @if (_ntfyTestResult is not null) { @_ntfyTestResult.Message } } @* ─── Dialog d'enrôlement 2FA (QR + codes de récupération) ─── *@ @Text["EnableTwoFactor"] @if (_2faError is not null) { @_2faError } else if (_2faSetup is not null) { @Text["ScanQrInstructions"] @Text["TwoFactorKey"] @_2faSetup.SharedKey @if (!string.IsNullOrEmpty(_2faSetup.QrCodeUri)) { @Text["SetupLink"] @Text["OpenInApp"] } @if (_completed2faSetup is { RecoveryCodes.Count: > 0 }) { @Text["RecoveryCodes"] — @Text["KeepRecoveryCodes"] @Text["RecoveryCodesInstructions"] @Text["RecoveryCodeOneUse"] @foreach (var rc in _completed2faSetup.RecoveryCodes) { @rc } } else { @Text["ConfirmTwoFactor"] } } @Text["Close"] @code { private UserItem? _profile; private bool _loading = true; private bool _error; private bool _saving; private bool _changingPassword; // Section 1 — Informations personnelles private string _displayName = ""; private string _theme = "Auto"; private string _language = "fr"; private string _profileError = ""; // Section 3 — Changer le mot de passe private string _currentPassword = ""; private string _newPassword = ""; private string _confirmPassword = ""; private string _passwordError = ""; // Section 2FA private bool _toggling2fa; private bool _confirmDisable2fa; private string _disable2faPassword = ""; private bool _confirmEnable2fa; private string _enable2faPassword = ""; private bool _show2faDialog; private Enable2faResponse? _2faSetup; private Complete2faSetupResponse? _completed2faSetup; private string _authenticatorCode = ""; private string? _2faError; private bool _recoveryCodesConfirmed; protected override async Task OnInitializedAsync() { Language.LanguageChanged += OnLanguageChanged; await LoadProfile(); await LoadNotificationConfig(); } private async Task LoadProfile() { _loading = true; _error = false; try { var result = await Api.GetMyProfileAsync(); if (result is not null) { _profile = result; _displayName = result.DisplayName; _theme = result.Theme ?? "Auto"; _language = UiLanguageService.Normalize(result.Language); Language.SetLanguage(_language); } } catch { _error = true; Snackbar.Add(Text["OperationFailed"], Severity.Error); } finally { _loading = false; } } // ─── Section 1: Enregistrer le profil ───────────────────────── private async Task SaveProfile() { if (string.IsNullOrWhiteSpace(_displayName)) { _profileError = Text["DisplayNameRequired"]; return; } _saving = true; _profileError = ""; try { var success = await Api.UpdateMyProfileAsync(_displayName.Trim(), _theme, _language); if (success) { _language = UiLanguageService.Normalize(_language); Language.SetLanguage(_language); try { await JS.InvokeVoidAsync("heimdallLocalization.setLanguage", _language); } catch (JSException) { /* The saved preference still applies to this circuit. */ } Snackbar.Add(Text["ProfileUpdated"], Severity.Success); } else { _profileError = Text["ProfileUpdateFailed"]; } } catch { _profileError = Text["OperationFailed"]; } finally { _saving = false; } } // ─── Section 3: Changer le mot de passe ─────────────────────── private Task Enable2fa() { _confirmEnable2fa = true; return Task.CompletedTask; } private void CancelEnable2fa() { _confirmEnable2fa = false; _enable2faPassword = ""; } private async Task StartEnable2fa() { _toggling2fa = true; _2faError = null; _2faSetup = null; _completed2faSetup = null; _authenticatorCode = ""; _recoveryCodesConfirmed = false; var currentPassword = _enable2faPassword; _confirmEnable2fa = false; try { var setup = await Api.Enable2faAsync(currentPassword); if (setup is null) { _2faError = Text["OperationFailed"]; _show2faDialog = true; return; } // ResetAuthenticatorKeyAsync rotates the security stamp. Reissue both // the Blazor token state and middleware cookie before confirming setup. var renewedSession = await Api.LoginAsync(_profile!.Email, currentPassword); if (renewedSession is null || string.IsNullOrEmpty(renewedSession.AccessToken)) { _2faError = Text["OperationFailed"]; _show2faDialog = true; return; } await AuthProvider.NotifyLoginAsync(renewedSession); if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken))) { _2faError = Text["OperationFailed"]; _show2faDialog = true; return; } _2faSetup = setup; _show2faDialog = true; } catch { _2faError = Text["OperationFailed"]; _show2faDialog = true; } finally { _enable2faPassword = ""; _toggling2fa = false; await LoadProfile(); } } private void Close2faDialog() { _show2faDialog = false; _2faSetup = null; _completed2faSetup = null; _authenticatorCode = ""; _recoveryCodesConfirmed = false; } private async Task ConfirmEnable2fa() { _toggling2fa = true; try { var completed = await Api.ConfirmEnable2faAsync(_authenticatorCode); if (completed is null) { _2faError = "Code invalide ou activation impossible"; return; } _completed2faSetup = completed; _2faError = null; } catch { _2faError = Text["OperationFailed"]; } finally { _toggling2fa = false; await LoadProfile(); } } private Task Disable2fa() { _confirmDisable2fa = true; return Task.CompletedTask; } private void CancelDisable2fa() { _confirmDisable2fa = false; _disable2faPassword = ""; } private async Task ConfirmDisable2fa() { _toggling2fa = true; var disabled = false; try { var ok = await Api.Disable2faAsync(_disable2faPassword); disabled = ok; if (ok) { Snackbar.Add(Text["TwoFactorDisabled"], Severity.Success); } else { Snackbar.Add(Text["TwoFactorDisableFailed"], Severity.Error); } } catch { Snackbar.Add(Text["OperationFailed"], Severity.Error); } finally { _toggling2fa = false; if (disabled) CancelDisable2fa(); await LoadProfile(); } } private async Task ChangePassword() { if (string.IsNullOrWhiteSpace(_currentPassword)) { _passwordError = Text["CurrentPasswordRequired"]; return; } if (string.IsNullOrWhiteSpace(_newPassword)) { _passwordError = Text["NewPasswordRequired"]; return; } if (_newPassword.Length < 12) { _passwordError = Text["PasswordTooShort"]; return; } if (_newPassword != _confirmPassword) { _passwordError = Text["PasswordsMismatch"]; return; } _changingPassword = true; _passwordError = ""; try { var success = await Api.ChangePasswordAsync(_currentPassword, _newPassword); if (success) { _currentPassword = ""; _newPassword = ""; _confirmPassword = ""; Snackbar.Add(Text["PasswordChanged"], Severity.Success); } else { _passwordError = Text["PasswordChangeFailed"]; } } catch { _passwordError = Text["OperationFailed"]; } finally { _changingPassword = false; } } // ─── Section 4: Notifications ───────────────────────────────── private NotificationConfigItem? _notifConfig; private MudForm? _notifForm; private bool _emailEnabled; private string? _emailAddress; private bool _ntfyEnabled; private string? _ntfyUrl; private string? _ntfyTopic; private bool _dailyDigest; private bool _weeklyDigest; private bool _savingNotif; private string _notifError = ""; private bool _testingNtfy; private TestActionResult? _ntfyTestResult; // Event type subscription checkboxes private IReadOnlyList EventTypes => [ new("MotionDetected", Text["MotionDetected"], Icons.Material.Filled.NearMe), new("PersonDetected", Text["PersonDetected"], Icons.Material.Filled.Person), new("VehicleDetected", Text["VehicleDetected"], Icons.Material.Filled.DirectionsCar), new("UnknownPerson", Text["UnknownPerson"], Icons.Material.Filled.HelpOutline), new("FaceRecognized", Text["FaceRecognized"], Icons.Material.Filled.Face), new("LicensePlateDetected", Text["LicensePlateDetected"], Icons.Material.Filled.Pin), new("CameraOffline", Text["CameraOffline"], Icons.Material.Filled.VideocamOff), new("CameraOnline", Text["CameraOnline"], Icons.Material.Filled.Videocam), ]; private HashSet _subscribedEvents = new(); private sealed record EventTypeOption(string Value, string Label, string Icon); private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged); public void Dispose() => Language.LanguageChanged -= OnLanguageChanged; private void ToggleEventType(string value, bool selected) { if (selected) _subscribedEvents.Add(value); else _subscribedEvents.Remove(value); } private async Task LoadNotificationConfig() { try { _notifConfig = await Api.GetNotificationConfigAsync(); if (_notifConfig is not null) { _emailEnabled = _notifConfig.EmailEnabled; _emailAddress = _notifConfig.EmailAddress; _ntfyEnabled = _notifConfig.NtfyEnabled; _ntfyUrl = _notifConfig.NtfyUrl; _ntfyTopic = _notifConfig.NtfyTopic; _dailyDigest = _notifConfig.DailyDigest; _weeklyDigest = _notifConfig.WeeklyDigest; _subscribedEvents = _notifConfig.SubscribedEvents is not null ? new HashSet(_notifConfig.SubscribedEvents) : new HashSet(); } } catch (Exception) { _notifError = Text["NotificationConfigLoadFailed"]; } } private async Task SaveNotificationConfig() { _savingNotif = true; _notifError = ""; try { var request = new UpdateNotificationConfigRequest( _emailEnabled, string.IsNullOrWhiteSpace(_emailAddress) ? null : _emailAddress.Trim(), _ntfyEnabled, string.IsNullOrWhiteSpace(_ntfyUrl) ? null : _ntfyUrl.Trim(), string.IsNullOrWhiteSpace(_ntfyTopic) ? null : _ntfyTopic.Trim(), _dailyDigest, _weeklyDigest, _subscribedEvents.Count > 0 ? _subscribedEvents.ToList() : null, Language: UiLanguageService.Normalize(_language) ); var success = await Api.UpdateNotificationConfigAsync(request); if (success) { Snackbar.Add(Text["NotificationConfigUpdated"], Severity.Success); } else { _notifError = Text["NotificationConfigUpdateFailed"]; } } catch { _notifError = Text["OperationFailed"]; } finally { _savingNotif = false; } } private string? ResolveNtfyTopic() { if (!string.IsNullOrWhiteSpace(_ntfyTopic)) return _ntfyTopic.Trim(); return _profile is not null ? $"heimdall_{_profile.Id}" : null; } private async Task TestNtfyForUserAsync() { _testingNtfy = true; _ntfyTestResult = null; try { var topic = ResolveNtfyTopic(); var baseUrl = string.IsNullOrWhiteSpace(_ntfyUrl) ? null : _ntfyUrl.Trim(); _ntfyTestResult = await Api.TestNtfyAsync(topic, baseUrl) ?? new TestActionResult(false, Text["TestUnavailable"]); } catch (Exception) { _ntfyTestResult = new TestActionResult(false, Text["OperationFailed"]); } finally { _testingNtfy = false; } } }
@(!string.IsNullOrWhiteSpace(_ntfyTopic) ? _ntfyTopic : $"heimdall_{_profile?.Id}")
@_2faSetup.SharedKey