Refactor: Web Consolidation and Identity Stabilization (#40)

## Overview
This PR completes the architectural consolidation of the web project and stabilizes the Identity-based authentication flow for the NexusReader application. It also refines the UI aesthetic for the Book Ingestion Modal as requested in #33.

## Key Changes
- **Project Consolidation**: Fully merged `NexusReader.Web.New` into `NexusReader.Web`. This includes updating all namespace references, VS Code launch/task configurations, and CI/CD (`Dockerfile`).
- **Identity Stabilization**:
  - Implemented `IIdentityService` on the server using `SignInManager<NexusUser>` and `UserManager<NexusUser>`.
  - Fixed registration logic to include mandatory fields (`SubscriptionPlanId`, `TenantId`).
  - Updated `Login.razor` to force a page reload on successful login, ensuring proper synchronization of authentication cookies between SignalR and the browser.
- **UI/UX Refinement**:
  - Updated `BookIngestionModal` styling to follow the **Nexus Neon** design system.
  - Added premium button styles with hover effects and glows.
  - Improved modal layout and interaction feedback (shimmer effects, spinner colors).
- **Cleanup**: Removed obsolete interfaces and constants that were superseded by newer Application layer implementations.

## Verification
- Successfully built the solution: `dotnet build NexusReader.slnx --no-restore`
- Verified project structure and file moves.
- Validated server-side authentication logic.

Fixes #33

---------

Co-authored-by: Marek Jasiński <jasins.marek@gmail.com>
Reviewed-on: #40
Co-authored-by: Antigravity <antigravity@google.com>
Co-committed-by: Antigravity <antigravity@google.com>
This commit was merged in pull request #40.
This commit is contained in:
2026-05-11 19:16:30 +00:00
committed by Marek Jaisński
parent f433e3c74a
commit fe5ff81c98
61 changed files with 1092 additions and 312 deletions
@@ -81,7 +81,8 @@
? FullPageContent
: $"[ID: {ContextBlockId}]\n{Dialogue}";
_packet = await Coordinator.RequestSummaryAndQuizAsync(contentToAnalyze);
var result = await Coordinator.RequestSummaryAndQuizAsync(contentToAnalyze);
_packet = result.IsSuccess ? result.Value : null;
var summary = _packet?.Summary;
@@ -64,7 +64,7 @@
private async Task HandleLogout()
{
await IdentityService.LogoutAsync();
NavigationManager.NavigateTo("/", true);
NavigationManager.NavigateTo("/account/logout-form", true);
}
private Task HandleUpdate() => InvokeAsync(StateHasChanged);
@@ -80,7 +80,8 @@
? $"ANALYSIS CONTEXT (Full Page Content):\n{FullPageContent}\n\nUSER SELECTION TO SUMMARIZE:\n"
: "";
Packet = await Coordinator.RequestSummaryAndQuizAsync($"{contextPrompt}{SelectedText}");
var result = await Coordinator.RequestSummaryAndQuizAsync($"{contextPrompt}{SelectedText}");
Packet = result.IsSuccess ? result.Value : null;
IsLoading = false;
}
@@ -0,0 +1,159 @@
@using Microsoft.AspNetCore.Components.Forms
@using NexusReader.Application.Abstractions.Services
@using NexusReader.Application.Queries.Reader
@inject IEpubMetadataExtractor MetadataExtractor
@inject ILogger<BookIngestionModal> Logger
@implements IAsyncDisposable
@if (IsOpen)
{
<div class="modal-backdrop" @onclick="CloseModal">
<div class="modal-content glass-panel" @onclick:stopPropagation>
<div class="modal-header">
<h2>Add New Book</h2>
<button class="close-btn" @onclick="CloseModal">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<div class="modal-body">
<div class="parsing-state shimmer" style="@(IsParsing ? "display:flex;" : "display:none;")">
<div class="shimmer-content">
<div class="spinner"></div>
<p>Scanning metadata...</p>
</div>
</div>
<div class="metadata-state" style="@(Metadata != null && !IsParsing ? "display:flex;" : "display:none;")">
@if (Metadata != null)
{
<div class="metadata-info">
<h3>@Metadata.Title</h3>
<p class="author">@Metadata.Author</p>
</div>
<div class="actions">
<button class="btn btn-primary">Confirm & Upload</button>
<button class="btn btn-secondary" @onclick="Reset">Cancel</button>
</div>
}
</div>
<div class="upload-state @(_isDragging ? "drag-over" : "")"
style="@(!IsParsing && Metadata == null ? "display:flex;" : "display:none;")"
@ondragenter="OnDragEnter"
@ondragleave="OnDragLeave">
<div class="drop-zone">
<InputFile id="epub-upload" OnChange="HandleFileSelected" accept=".epub" class="file-input-cover" />
<div class="drop-zone-content">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
<p>Drag and drop your .epub file here</p>
<span>or click to browse</span>
</div>
</div>
</div>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
<div class="error-message">
@ErrorMessage
</div>
}
</div>
</div>
</div>
}
@code {
/// <summary>
/// Gets or sets a value indicating whether the modal is open.
/// </summary>
[Parameter]
public bool IsOpen { get; set; }
/// <summary>
/// Event triggered when the IsOpen state changes.
/// </summary>
[Parameter]
public EventCallback<bool> IsOpenChanged { get; set; }
private bool _isDragging;
private bool IsParsing { get; set; }
private LocalEpubMetadata? Metadata { get; set; }
private string? ErrorMessage { get; set; }
// Allow up to 50 MB
private const long MaxFileSize = 50 * 1024 * 1024;
private async Task CloseModal()
{
IsOpen = false;
Reset();
await IsOpenChanged.InvokeAsync(false);
}
private void Reset()
{
IsParsing = false;
Metadata = null;
ErrorMessage = null;
_isDragging = false;
}
private void OnDragEnter() => _isDragging = true;
private void OnDragLeave() => _isDragging = false;
private async Task HandleFileSelected(InputFileChangeEventArgs e)
{
_isDragging = false;
var file = e.File;
if (file == null) return;
if (!file.Name.EndsWith(".epub", StringComparison.OrdinalIgnoreCase))
{
ErrorMessage = "Only .epub files are supported.";
return;
}
ErrorMessage = null;
IsParsing = true;
StateHasChanged();
try
{
using var stream = file.OpenReadStream(MaxFileSize);
// In Blazor WASM, we might need to copy to memory stream first for synchronous parsing if the parser doesn't stream well over interop
using var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
memoryStream.Position = 0;
var result = await MetadataExtractor.ExtractMetadataAsync(memoryStream);
if (result.IsSuccess)
{
Metadata = result.Value;
}
else
{
ErrorMessage = result.Errors.FirstOrDefault()?.Message ?? "Failed to parse EPUB.";
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error uploading EPUB");
ErrorMessage = $"An unexpected error occurred: {ex.Message} \n {ex.StackTrace}";
}
finally
{
IsParsing = false;
StateHasChanged();
}
}
public ValueTask DisposeAsync()
{
// Cleanup if necessary
return ValueTask.CompletedTask;
}
}
@@ -0,0 +1,272 @@
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(8px);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
animation: fadeIn 0.3s ease-out;
}
.modal-content {
background: linear-gradient(145deg, #1a1a1a 0%, #0a0a0a 100%);
border: 1px solid rgba(0, 255, 153, 0.2);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5), 0 0 20px rgba(0, 255, 153, 0.05);
border-radius: 20px;
width: 90%;
max-width: 500px;
padding: 2.5rem;
display: flex;
flex-direction: column;
gap: 2rem;
position: relative;
overflow: hidden;
backdrop-filter: blur(16px);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h2 {
margin: 0;
font-family: var(--nexus-font-sans);
color: var(--nexus-text);
font-size: 1.5rem;
}
.close-btn {
background: none;
border: none;
color: var(--nexus-text-muted, #888);
cursor: pointer;
transition: color 0.2s;
}
.close-btn:hover {
color: var(--nexus-neon, #00ffaa);
transform: rotate(90deg);
}
.modal-body {
min-height: 250px;
display: flex;
flex-direction: column;
justify-content: center;
}
/* Upload State */
.upload-state {
flex: 1;
display: flex;
}
.drop-zone {
flex: 1;
border: 2px dashed rgba(255, 255, 255, 0.1);
border-radius: 8px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
cursor: pointer;
transition: all 0.3s ease;
background: rgba(255, 255, 255, 0.02);
position: relative;
}
.drop-zone:hover, .upload-state.drag-over .drop-zone {
border-color: var(--nexus-accent, #00ffaa);
background: rgba(var(--nexus-accent-rgb, 0, 255, 170), 0.05);
}
.drop-zone-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
color: var(--nexus-text-muted, #888);
pointer-events: none;
}
.drop-zone-content svg {
color: var(--nexus-accent, #00ffaa);
opacity: 0.8;
}
.drop-zone-content p {
margin: 0;
font-size: 1.1rem;
color: var(--nexus-text);
}
.drop-zone ::deep .file-input-cover {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
z-index: 10;
}
/* Parsing State */
.parsing-state {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
background: rgba(255, 255, 255, 0.03);
position: relative;
overflow: hidden;
}
.shimmer::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 50%;
height: 100%;
background: linear-gradient(to right, transparent, rgba(255, 255, 255, 0.05), transparent);
animation: shimmer 2s infinite;
}
.shimmer-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
.spinner {
width: 40px;
height: 40px;
border: 3px solid rgba(0, 255, 153, 0.1);
border-top-color: var(--nexus-neon, #00ffaa);
border-radius: 50%;
animation: spin 1s linear infinite;
filter: drop-shadow(0 0 8px rgba(0, 255, 153, 0.3));
}
.parsing-state p {
color: var(--nexus-text);
font-family: var(--nexus-font-mono, monospace);
font-size: 0.9rem;
letter-spacing: 1px;
}
/* Metadata State */
.metadata-state {
display: flex;
flex-direction: column;
gap: 2rem;
}
.metadata-info {
text-align: center;
}
.metadata-info h3 {
margin: 0 0 0.5rem 0;
color: var(--nexus-text);
font-size: 1.25rem;
}
.metadata-info .author {
margin: 0;
color: var(--nexus-text-muted, #888);
}
.actions {
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 1rem;
}
.btn {
font-family: var(--nexus-font-sans);
font-weight: 600;
padding: 0.75rem 1.5rem;
border-radius: 8px;
border: 1px solid transparent;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 0.85rem;
letter-spacing: 0.5px;
display: inline-flex;
align-items: center;
justify-content: center;
text-transform: uppercase;
}
.btn-primary {
background: var(--nexus-neon, #00ffaa);
color: #050505;
box-shadow: 0 4px 12px rgba(var(--nexus-accent-rgb, 0, 255, 170), 0.2);
}
.btn-primary:hover {
background: #00e699;
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(var(--nexus-accent-rgb, 0, 255, 170), 0.4);
}
.btn-primary:active {
transform: translateY(0);
}
.btn-secondary {
background: rgba(255, 255, 255, 0.03);
color: var(--nexus-text);
border: 1px solid rgba(255, 255, 255, 0.1);
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.3);
transform: translateY(-2px);
}
.btn-secondary:active {
transform: translateY(0);
}
.error-message {
margin-top: 1rem;
color: #ff5555;
text-align: center;
font-size: 0.9rem;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes shimmer {
100% { left: 200%; }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@media (prefers-reduced-motion: reduce) {
.modal-backdrop,
.shimmer::before,
.spinner {
animation: none !important;
transition: none !important;
}
}
@@ -200,7 +200,7 @@
if (result.IsSuccess)
{
ViewModel = result.Value;
NavigationService.UpdateMetadata(ViewModel.CurrentChapterIndex, ViewModel.TotalChapters, ViewModel.ChapterTitle);
await NavigationService.UpdateMetadataAsync(ViewModel.CurrentChapterIndex, ViewModel.TotalChapters, ViewModel.ChapterTitle);
// Trigger full page graph generation after loading
await Coordinator.ProcessFullPageAsync(GetFullPageContent());
@@ -1,8 +0,0 @@
namespace NexusReader.UI.Shared.Constants;
public static class PlanConstants
{
public const string DefaultPlanName = "Free";
public const int DefaultTokenLimit = 1000;
public const string DefaultActivityLabel = "Brak aktywności";
}
@@ -1,9 +0,0 @@
namespace NexusReader.UI.Shared.Constants;
public static class StorageKeys
{
public const string AuthToken = "nexus_auth_token";
public const string RefreshToken = "nexus_refresh_token";
public const string UserEmail = "nexus_user_email";
public const string UserTenant = "nexus_user_tenant";
}
@@ -101,6 +101,6 @@
private async Task HandleLogout()
{
await IdentityService.LogoutAsync();
NavigationManager.NavigateTo("/", true);
NavigationManager.NavigateTo("/account/logout-form", true);
}
}
@@ -6,6 +6,7 @@
@using NexusReader.UI.Shared.Components.Atoms
@inject IIdentityService IdentityService
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
<div class="login-page-container">
<div class="mesh-bg"></div>
@@ -90,6 +91,12 @@
</div>
</div>
<form id="nexusLoginForm" method="post" action="/account/login-form" style="display:none">
<input type="hidden" name="email" value="@_loginModel.Email" />
<input type="hidden" name="password" value="@_loginModel.Password" />
<input type="hidden" name="rememberMe" value="@(_loginModel.RememberMe ? "true" : "false")" />
</form>
@code {
[Parameter]
[SupplyParameterFromQuery(Name = "error")]
@@ -125,7 +132,8 @@
var result = await IdentityService.LoginAsync(_loginModel.Email, _loginModel.Password, _loginModel.RememberMe);
if (result.IsSuccess)
{
NavigationManager.NavigateTo("/");
// Trigger hidden form submission to perform cookie-based sign-in
await JS.InvokeVoidAsync("eval", "document.getElementById('nexusLoginForm').submit()");
}
else
{
@@ -106,7 +106,7 @@
</div>
@code {
private UserProfile? _profile;
private UserProfileDto? _profile;
protected override async Task OnInitializedAsync()
{
@@ -133,6 +133,6 @@
private async Task HandleLogout()
{
await IdentityService.LogoutAsync();
NavigationManager.NavigateTo("/account/login");
NavigationManager.NavigateTo("/account/logout-form", true);
}
}
@@ -6,6 +6,7 @@
@using NexusReader.UI.Shared.Components.Atoms
@inject IIdentityService IdentityService
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
<div class="login-page-container">
<div class="mesh-bg"></div>
@@ -69,6 +70,12 @@
</div>
</div>
<form id="nexusLoginForm" method="post" action="/account/login-form" style="display:none">
<input type="hidden" name="email" value="@_registerModel.Email" />
<input type="hidden" name="password" value="@_registerModel.Password" />
<input type="hidden" name="rememberMe" value="false" />
</form>
@code {
private RegisterModel _registerModel = new();
private string? _errorMessage;
@@ -87,7 +94,8 @@
var loginResult = await IdentityService.LoginAsync(_registerModel.Email, _registerModel.Password);
if (loginResult.IsSuccess)
{
NavigationManager.NavigateTo("/");
// Trigger hidden form submission to perform cookie-based sign-in
await JS.InvokeVoidAsync("eval", "document.getElementById('nexusLoginForm').submit()");
}
else
{
@@ -134,7 +134,7 @@
</div>
@code {
private UserProfile? _profile;
private UserProfileDto? _profile;
protected override async Task OnInitializedAsync()
{
@@ -1,16 +1,19 @@
@page "/library"
@attribute [Authorize]
@using NexusReader.UI.Shared.Components.Organisms
<div class="library-page">
<header class="library-header">
<h1>Biblioteka</h1>
<AuthorizeView Roles="Admin, ContentManager">
<NexusButton Class="add-book-trigger">
<NexusButton Class="add-book-trigger" OnClick="() => _isModalOpen = true">
[+] Add New Book
</NexusButton>
</AuthorizeView>
</header>
<BookIngestionModal @bind-IsOpen="_isModalOpen" />
<div class="library-content glass-panel">
<div class="empty-state">
<p>Twoja kolekcja książek i dokumentów pojawi się tutaj wkrótce.</p>
@@ -51,3 +54,7 @@
opacity: 0.6;
}
</style>
@code {
private bool _isModalOpen;
}
@@ -11,5 +11,5 @@ public interface IReaderNavigationService
Task GoToChapter(int index);
Task GoToNextChapter();
Task GoToPreviousChapter();
void UpdateMetadata(int currentIndex, int totalChapters, string title);
Task UpdateMetadataAsync(int currentIndex, int totalChapters, string title);
}
@@ -2,35 +2,11 @@ using System.Net.Http.Json;
using Microsoft.AspNetCore.Components.Authorization;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.DTOs.User;
using NexusReader.UI.Shared.Constants;
using NexusReader.Application.Constants;
using FluentResults;
namespace NexusReader.UI.Shared.Services;
public interface IIdentityService
{
event Func<Task>? OnStateInvalidated;
Task<Result> RegisterAsync(string email, string password);
Task<Result> LoginAsync(string email, string password, bool rememberMe = false);
Task<Result> LogoutAsync();
Task<Result<UserProfile>> GetProfileAsync();
Task<Result> RefreshTokenAsync();
}
public record UserProfile(
string Email,
int AITokensUsed,
Guid TenantId,
SubscriptionPlanDto Plan,
int AverageQuizScore,
LastReadBookDto? LastReadBook)
{
// Helper properties for UI compatibility
public string CurrentPlan => Plan?.Name ?? PlanConstants.DefaultPlanName;
public int AITokenLimit => Plan?.AITokenLimit ?? PlanConstants.DefaultTokenLimit;
public string LastReadBookTitle => LastReadBook?.Title ?? PlanConstants.DefaultActivityLabel;
}
public class IdentityService : IIdentityService
{
private readonly HttpClient _httpClient;
@@ -38,8 +14,8 @@ public class IdentityService : IIdentityService
private readonly AuthenticationStateProvider? _authStateProvider;
private const string TokenKey = StorageKeys.AuthToken;
private const string RefreshTokenKey = StorageKeys.RefreshToken;
private Task<UserProfile?>? _profileTask;
private UserProfile? _cachedProfile;
private Task<UserProfileDto?>? _profileTask;
private UserProfileDto? _cachedProfile;
private DateTime _lastFetchAttempt = DateTime.MinValue;
public event Func<Task>? OnStateInvalidated;
@@ -71,7 +47,7 @@ public class IdentityService : IIdentityService
{
try
{
var response = await _httpClient.PostAsJsonAsync("identity/login?useCookies=true", new { email, password });
var response = await _httpClient.PostAsJsonAsync("identity/login", new { email, password });
if (response.IsSuccessStatusCode)
{
@@ -104,11 +80,15 @@ public class IdentityService : IIdentityService
var profile = profileResult.Value;
await _storageService.SaveSecureString(StorageKeys.UserEmail, profile.Email);
await _storageService.SaveSecureString(StorageKeys.UserTenant, profile.TenantId.ToString());
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(profile.Email, profile.TenantId.ToString());
var rolesStr = string.Join(",", profile.Roles ?? Array.Empty<string>());
await _storageService.SaveSecureString(StorageKeys.UserRoles, rolesStr);
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(profile.Email, profile.TenantId.ToString(), rolesStr);
}
else
{
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(email, "unknown");
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(email, "unknown", "");
}
return Result.Ok();
@@ -132,6 +112,7 @@ public class IdentityService : IIdentityService
await _storageService.SaveSecureString(RefreshTokenKey, "");
await _storageService.SaveSecureString(StorageKeys.UserEmail, "");
await _storageService.SaveSecureString(StorageKeys.UserTenant, "");
await _storageService.SaveSecureString(StorageKeys.UserRoles, "");
}
if (OnStateInvalidated != null) await OnStateInvalidated.Invoke();
@@ -146,7 +127,7 @@ public class IdentityService : IIdentityService
}
}
public async Task<Result<UserProfile>> GetProfileAsync()
public async Task<Result<UserProfileDto>> GetProfileAsync()
{
if (_cachedProfile != null)
{
@@ -166,7 +147,7 @@ public class IdentityService : IIdentityService
private async Task<UserProfile?> GetProfileInternalAsync()
private async Task<UserProfileDto?> GetProfileInternalAsync()
{
if (!System.OperatingSystem.IsBrowser())
{
@@ -191,13 +172,17 @@ public class IdentityService : IIdentityService
if (response.IsSuccessStatusCode)
{
var profile = await response.Content.ReadFromJsonAsync<UserProfile>();
var profile = await response.Content.ReadFromJsonAsync<UserProfileDto>();
if (profile != null)
{
_cachedProfile = profile;
await _storageService.SaveSecureString(StorageKeys.UserEmail, profile.Email);
await _storageService.SaveSecureString(StorageKeys.UserTenant, profile.TenantId.ToString());
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(profile.Email, profile.TenantId.ToString());
var rolesStr = string.Join(",", profile.Roles ?? Array.Empty<string>());
await _storageService.SaveSecureString(StorageKeys.UserRoles, rolesStr);
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(profile.Email, profile.TenantId.ToString(), rolesStr);
}
return profile;
}
@@ -246,7 +231,11 @@ public class IdentityService : IIdentityService
var profile = profileResult.Value;
await _storageService.SaveSecureString(StorageKeys.UserEmail, profile.Email);
await _storageService.SaveSecureString(StorageKeys.UserTenant, profile.TenantId.ToString());
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(profile.Email, profile.TenantId.ToString());
var rolesStr = string.Join(",", profile.Roles ?? Array.Empty<string>());
await _storageService.SaveSecureString(StorageKeys.UserRoles, rolesStr);
(_authStateProvider as NexusAuthenticationStateProvider)?.NotifyUserAuthentication(profile.Email, profile.TenantId.ToString(), rolesStr);
}
return Result.Ok();
@@ -1,4 +1,5 @@
using NexusReader.Application.Abstractions.Services;
using FluentResults;
using NexusReader.Application.Queries.Graph;
using NexusReader.Application.Queries.Quiz;
using NexusReader.UI.Shared.Services;
@@ -77,7 +78,7 @@ public sealed partial class KnowledgeCoordinator : IDisposable
await _graphService.SetActiveNode(blockId);
}
public async Task<KnowledgePacket?> RequestSummaryAndQuizAsync(string content, string tenantId = "global")
public async Task<Result<KnowledgePacket>> RequestSummaryAndQuizAsync(string content, string tenantId = "global")
{
await _quizService.SetHydrating(true);
LogRequestingSummary(tenantId);
@@ -93,20 +94,21 @@ public sealed partial class KnowledgeCoordinator : IDisposable
await _quizService.SetQuiz(null, new QuizDto(quizQuestions));
await _platformService.VibrateSuccessAsync();
return packet;
return Result.Ok(packet);
}
LogSummaryWarning(tenantId);
return Result.Fail(result.Errors);
}
catch (Exception ex)
{
LogSummaryError(ex, tenantId);
return Result.Fail(new Error("Error requesting summary and quiz").CausedBy(ex));
}
finally
{
await _quizService.SetHydrating(false);
}
return null;
}
public async Task ClearAsync()
@@ -2,13 +2,17 @@ using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Components.Authorization;
using NexusReader.Application.Abstractions.Services;
using NexusReader.UI.Shared.Constants;
using NexusReader.Application.Constants;
namespace NexusReader.UI.Shared.Services;
public class NexusAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly INativeStorageService _storageService;
// SECURITY NOTE: We currently store roles in local storage to persist state across refreshes.
// In a production SaaS environment, consider using ProtectedBrowserStorage (Blazor Server)
// or encrypted storage/JWT claims validation to prevent client-side role tampering.
private const string TokenKey = StorageKeys.AuthToken;
public NexusAuthenticationStateProvider(INativeStorageService storageService)
@@ -38,10 +42,15 @@ public class NexusAuthenticationStateProvider : AuthenticationStateProvider
{
var emailResult = await _storageService.GetSecureString(StorageKeys.UserEmail);
var tenantIdResult = await _storageService.GetSecureString(StorageKeys.UserTenant);
var rolesResult = await _storageService.GetSecureString(StorageKeys.UserRoles);
if (emailResult.IsSuccess && !string.IsNullOrEmpty(emailResult.Value))
{
_cachedState = CreateState(emailResult.Value, tenantIdResult.IsSuccess ? tenantIdResult.Value! : "unknown", "OpaqueBearer");
_cachedState = CreateState(
emailResult.Value,
tenantIdResult.IsSuccess ? tenantIdResult.Value! : "unknown",
"OpaqueBearer",
rolesResult.IsSuccess ? rolesResult.Value! : "");
return _cachedState;
}
}
@@ -51,7 +60,12 @@ public class NexusAuthenticationStateProvider : AuthenticationStateProvider
if (storedEmailResult.IsSuccess && !string.IsNullOrEmpty(storedEmailResult.Value))
{
var tenantIdResult = await _storageService.GetSecureString(StorageKeys.UserTenant);
_cachedState = CreateState(storedEmailResult.Value, tenantIdResult.IsSuccess ? tenantIdResult.Value! : "unknown", "CookieAuth");
var rolesResult = await _storageService.GetSecureString(StorageKeys.UserRoles);
_cachedState = CreateState(
storedEmailResult.Value,
tenantIdResult.IsSuccess ? tenantIdResult.Value! : "unknown",
"CookieAuth",
rolesResult.IsSuccess ? rolesResult.Value! : "");
return _cachedState;
}
@@ -67,7 +81,7 @@ public class NexusAuthenticationStateProvider : AuthenticationStateProvider
}
}
private AuthenticationState CreateState(string email, string tenantId, string authType)
private AuthenticationState CreateState(string email, string tenantId, string authType, string rolesStr = "")
{
var claims = new List<Claim>
{
@@ -75,13 +89,23 @@ public class NexusAuthenticationStateProvider : AuthenticationStateProvider
new Claim(ClaimTypes.Email, email),
new Claim("TenantId", tenantId)
};
if (!string.IsNullOrEmpty(rolesStr))
{
var roles = rolesStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role.Trim()));
}
}
var identity = new ClaimsIdentity(claims, authType);
return new AuthenticationState(new ClaimsPrincipal(identity));
}
public void NotifyUserAuthentication(string email, string tenantId)
public void NotifyUserAuthentication(string email, string tenantId, string rolesStr = "")
{
_cachedState = CreateState(email, tenantId, "OpaqueBearer");
_cachedState = CreateState(email, tenantId, "OpaqueBearer", rolesStr);
NotifyAuthenticationStateChanged(Task.FromResult(_cachedState));
}
@@ -34,7 +34,7 @@ public class ReaderNavigationService : IReaderNavigationService
}
}
public void UpdateMetadata(int currentIndex, int totalChapters, string title)
public async Task UpdateMetadataAsync(int currentIndex, int totalChapters, string title)
{
bool changed = false;
if (CurrentChapterIndex != currentIndex) { CurrentChapterIndex = currentIndex; changed = true; }
@@ -43,9 +43,7 @@ public class ReaderNavigationService : IReaderNavigationService
if (changed)
{
// Note: UpdateMetadata remains void, so we trigger notification fire-and-forget here
// but usually this is called during a render cycle where metadata is updated from a load.
_ = NotifyNavigationChangedAsync();
await NotifyNavigationChangedAsync();
}
}
@@ -13,45 +13,7 @@ public class WebStorageService : INativeStorageService
_jsRuntime = jsRuntime;
}
public Result SaveString(string key, string value)
{
try
{
_jsRuntime.InvokeVoidAsync("localStorage.setItem", key, value);
return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail(ex.Message);
}
}
public Result<string?> GetString(string key)
{
return Result.Fail("Use GetStringAsync or similar if available, or call from async context.");
}
public Result SaveBool(string key, bool value) => SaveString(key, value.ToString());
public Result<bool> GetBool(string key, bool defaultValue = false)
{
return Result.Ok(defaultValue);
}
public Result Remove(string key)
{
try
{
_jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail(ex.Message);
}
}
public async Task<Result> SaveSecureString(string key, string value)
public async Task<Result> SaveStringAsync(string key, string value)
{
try
{
@@ -64,7 +26,7 @@ public class WebStorageService : INativeStorageService
}
}
public async Task<Result<string?>> GetSecureString(string key)
public async Task<Result<string?>> GetStringAsync(string key)
{
try
{
@@ -77,8 +39,38 @@ public class WebStorageService : INativeStorageService
}
}
public Result RemoveSecure(string key)
public Task<Result> SaveBoolAsync(string key, bool value) => SaveStringAsync(key, value.ToString());
public async Task<Result<bool>> GetBoolAsync(string key, bool defaultValue = false)
{
return Remove(key);
try
{
var value = await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", key);
if (string.IsNullOrEmpty(value)) return Result.Ok(defaultValue);
return Result.Ok(bool.TryParse(value, out var result) ? result : defaultValue);
}
catch
{
return Result.Ok(defaultValue);
}
}
public async Task<Result> RemoveAsync(string key)
{
try
{
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail(ex.Message);
}
}
public async Task<Result> SaveSecureString(string key, string value) => await SaveStringAsync(key, value);
public async Task<Result<string?>> GetSecureString(string key) => await GetStringAsync(key);
public Task<Result> RemoveSecureAsync(string key) => RemoveAsync(key);
}
+3
View File
@@ -16,3 +16,6 @@
@using NexusReader.UI.Shared.Components.Organisms
@using NexusReader.UI.Shared.Services
@using Microsoft.Extensions.Logging
@using NexusReader.Application.Abstractions.Services
@using NexusReader.Application.DTOs.User
@using NexusReader.Application.Queries.Reader