feat(postit): keep sessions online and replace banner with auth modal
All checks were successful
Forgejo Release / release (push) Successful in 10m4s
Dotnet build and test / build (pull_request) Successful in 15m16s

Remove the sticky session banner, keep the app connected when possible, restore sessions silently on startup, and show a blocking authentication modal with login, register, and forgot-password actions when auto-reconnect cannot resume the session. Add targeted auth and responsive-layout regressions and update the architecture notes to match the session lifecycle.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-13 12:32:58 +00:00
commit 0ac6970e9d
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
17 changed files with 629 additions and 164 deletions

View file

@ -186,15 +186,14 @@ public sealed class AndroidMarkdownEditorTestActivity : Activity
activity.CurrentFocus!.GetLocationInWindow(location);
var topLevel = TopLevel.GetTopLevel(root)!;
var navigation = root.FindControl<NavigationPage>("NavRoot")!;
var banner = root.FindControl<PostIt.Views.SessionStatusBanner>("SessionBanner")!;
var top = navigation.TranslatePoint(new Point(), topLevel)!.Value.Y * topLevel.RenderScaling + location[1];
var bottom = banner.TranslatePoint(new Point(0, banner.Bounds.Height), topLevel)!.Value.Y
var bottom = navigation.TranslatePoint(new Point(0, navigation.Bounds.Height), topLevel)!.Value.Y
* topLevel.RenderScaling + location[1];
var visibleBottom = decor.Height - bars.Bottom;
if (KeyboardVisible())
visibleBottom = Math.Min(visibleBottom, decor.Height - insets.GetInsets(WindowInsets.Type.Ime()).Bottom);
if (top < bars.Top - 2 || bottom > visibleBottom + 2 || !banner.IsVisible)
throw new InvalidOperationException($"Controls overlap system bars: top={top}, safeTop={bars.Top}, bottom={bottom}, safeBottom={visibleBottom}, banner={banner.IsVisible}.");
if (top < bars.Top - 2 || bottom > visibleBottom + 2)
throw new InvalidOperationException($"Controls overlap system bars: top={top}, safeTop={bars.Top}, bottom={bottom}, safeBottom={visibleBottom}.");
if (navigation.NavigationStack.LastOrDefault() is BlogsPage page)
{
var bar = NavigationPage.GetTopCommandBar(page)!;

View file

@ -26,6 +26,7 @@ public sealed class OIDCStubAuthority : IAsyncDisposable, IDisposable
public string Issuer { get; }
public string LoopbackRedirectUri { get; }
public int RefreshRequestCount { get; private set; }
public string? RefreshError { get; set; }
private OIDCStubAuthority(HttpListener listener, RSA rsa, string kid, string issuer, string loopback)
{
@ -137,6 +138,11 @@ public sealed class OIDCStubAuthority : IAsyncDisposable, IDisposable
if (form.TryGetValue("grant_type", out var grantType) && grantType == "refresh_token")
{
RefreshRequestCount++;
if (RefreshError is { } error)
{
await WriteJsonAsync(ctx.Response, new { error }, 503);
return;
}
if (!form.TryGetValue("refresh_token", out var suppliedToken)
|| !_refreshTokens.Remove(suppliedToken))
{

View file

@ -44,7 +44,7 @@ public class MarkdownEditorScrollTests
window.UpdateLayout();
Assert.True(page.DraftTitleTextBox.IsVisible);
Assert.True(page.AttachmentsBorder.IsVisible);
Assert.True(root.SessionBanner.IsVisible);
Assert.False(root.AuthenticationModal.IsVisible);
Assert.Equal(1, Grid.GetColumn(page.DraftTitleTextBox));
Assert.Equal(1, Grid.GetColumn(page.AttachmentsBorder));
Assert.True(page.StatusBar.IsVisible);
@ -60,7 +60,7 @@ public class MarkdownEditorScrollTests
window.UpdateLayout();
Assert.True(page.DraftTitleTextBox.IsVisible);
Assert.True(page.AttachmentsBorder.IsVisible);
Assert.True(root.SessionBanner.IsVisible);
Assert.False(root.AuthenticationModal.IsVisible);
Assert.Equal(0, Grid.GetColumn(page.DraftTitleTextBox));
Assert.Same(document, source.Document);
Assert.True(source.TextArea.IsFocused);
@ -98,10 +98,10 @@ public class MarkdownEditorScrollTests
window.UpdateLayout();
Assert.Equal(new Thickness(20, 26, 22, 32), root.Padding);
var navigationTop = root.NavRoot.TranslatePoint(new Point(), window)!.Value.Y;
var bannerBottom = root.SessionBanner.TranslatePoint(new Point(0, root.SessionBanner.Bounds.Height), window)!.Value.Y;
var navigationBottom = root.NavRoot.TranslatePoint(new Point(0, root.NavRoot.Bounds.Height), window)!.Value.Y;
Assert.True(navigationTop >= 26);
Assert.True(bannerBottom <= 768);
Assert.True(root.SessionBanner.IsVisible);
Assert.True(navigationBottom <= 768);
Assert.False(root.AuthenticationModal.IsVisible);
}
finally
{

View file

@ -0,0 +1,293 @@
using System.Net.Http;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Threading;
using Avalonia.VisualTree;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
[Collection(AvaloniaUiCollection.Name)]
public sealed class SessionAuthenticationTests(AvaloniaUiFixture ui)
{
[Theory]
[InlineData(false, 0)]
[InlineData(true, 600)]
[InlineData(true, -10)]
public Task Startup_restores_the_session_or_logs_in_without_confirmation(bool cached, int lifetime)
=> ui.RunAsync(async () =>
{
using var authority = await OIDCStubAuthority.StartAsync();
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
var previousBrowser = Platform.CreateBrowser;
var launches = 0;
try
{
var store = new TokenStore(path);
var settings = SettingsFor(authority);
Platform.CreateBrowser = () =>
{
launches++;
return new FakeAuthorizingBrowser(authority.LoopbackRedirectUri).CreateBrowser();
};
if (cached)
{
await using var original = new ProfileApi(settings, store);
await original.LoginInteractiveAsync();
store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(lifetime) });
}
launches = 0;
await using var api = new ProfileApi(settings, store);
var model = new SessionStatusViewModel { Api = api };
await model.InitializeAsync();
Assert.Equal(cached ? 0 : 1, launches);
Assert.Equal(cached && lifetime < 0 ? 1 : 0, authority.RefreshRequestCount);
Assert.True(model.IsLoggedIn);
Assert.True(model.IsAdministrator);
Assert.False(model.IsAuthenticationRequired);
Assert.NotNull(store.Load());
}
finally
{
Platform.CreateBrowser = previousBrowser;
File.Delete(path);
}
}, TestContext.Current.CancellationToken);
[Fact]
public Task Failed_startup_login_exposes_retry_and_account_actions()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
var previousBrowser = Platform.CreateBrowser;
try
{
Platform.CreateBrowser = null;
await using var api = new ProfileApi(new Settings(), new TokenStore(path));
var model = new SessionStatusViewModel { Api = api };
await model.InitializeAsync();
Assert.True(model.IsAuthenticationRequired);
Assert.False(model.IsLoggedIn);
Assert.Contains("Connexion impossible", model.SessionLabel);
Assert.True(model.LoginCommand.CanExecute(null));
Assert.True(model.RegisterCommand.CanExecute(null));
Assert.True(model.ForgotPasswordCommand.CanExecute(null));
}
finally
{
Platform.CreateBrowser = previousBrowser;
File.Delete(path);
}
}, TestContext.Current.CancellationToken);
[Fact]
public Task Transient_refresh_failure_keeps_tokens_and_successful_retry_closes_the_modal()
=> ui.RunAsync(async () =>
{
using var authority = await OIDCStubAuthority.StartAsync();
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
var previousBrowser = Platform.CreateBrowser;
try
{
var store = new TokenStore(path);
var settings = SettingsFor(authority);
Platform.CreateBrowser = () => new FakeAuthorizingBrowser(authority.LoopbackRedirectUri).CreateBrowser();
await using (var original = new ProfileApi(settings, store))
await original.LoginInteractiveAsync();
store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40) });
await using var api = new ProfileApi(settings, store);
var model = new SessionStatusViewModel { Api = api };
model.Refresh();
authority.RefreshError = "temporarily_unavailable";
var error = await Assert.ThrowsAsync<RefreshFailedException>(() =>
api.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken));
Dispatcher.UIThread.RunJobs();
Assert.False(error.IsPermanent);
Assert.NotNull(store.Load());
Assert.True(model.IsAuthenticationRequired);
authority.RefreshError = null;
await api.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken);
Dispatcher.UIThread.RunJobs();
Assert.True(model.IsLoggedIn);
Assert.True(model.IsAdministrator);
Assert.False(model.IsAuthenticationRequired);
Assert.Equal(2, authority.RefreshRequestCount);
}
finally
{
Platform.CreateBrowser = previousBrowser;
File.Delete(path);
}
}, TestContext.Current.CancellationToken);
[Fact]
public Task Expired_session_without_refresh_token_requires_authentication()
=> ui.RunAsync(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
try
{
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "", DateTimeOffset.UtcNow.AddSeconds(-1)));
await using var api = new ProfileApi(new Settings(), store);
var model = new SessionStatusViewModel { Api = api };
Assert.Equal(TimeSpan.Zero, api.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true));
await Assert.ThrowsAsync<RefreshFailedException>(() =>
api.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken));
Dispatcher.UIThread.RunJobs();
Assert.True(model.IsAuthenticationRequired);
Assert.False(api.HasValidSession);
Assert.Null(store.Load());
}
finally { File.Delete(path); }
}, TestContext.Current.CancellationToken);
[Fact]
public async Task Modal_restores_the_previous_page_and_focus_after_silent_recovery()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
try
{
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddMinutes(10)));
await using var api = new ProfileApi(new Settings(), store);
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
await ui.WithWindowAsync(() => new MainView
{
DataContext = new HomePageViewModel(api, api.Settings, session, null!)
}, async window =>
{
var root = Assert.IsType<MainView>(window.Content);
var editor = new TextBox { Text = "Brouillon conservé" };
var page = new ContentPage { Content = editor };
await root.NavRoot.PushAsync(page, null);
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
Assert.True(editor.Focus());
session.SetError("Session temporairement indisponible");
Dispatcher.UIThread.RunJobs();
Assert.True(root.LoginButton.IsFocused);
session.Refresh();
Dispatcher.UIThread.RunJobs();
Assert.False(root.AuthenticationModal.IsVisible);
Assert.True(root.NavRoot.IsEnabled);
Assert.True(editor.IsFocused);
Assert.Same(page, root.NavRoot.NavigationStack.Last());
Assert.Equal("Brouillon conservé", editor.Text);
}, TestContext.Current.CancellationToken);
}
finally { File.Delete(path); }
}
[Fact]
public Task Revoked_background_session_opens_the_modal_and_login_recovers()
=> ui.RunAsync(async () =>
{
using var authority = await OIDCStubAuthority.StartAsync();
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
var previousBrowser = Platform.CreateBrowser;
try
{
var settings = SettingsFor(authority);
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "revoked", DateTimeOffset.UtcNow.AddSeconds(40)));
await using var api = new ProfileApi(settings, store);
var model = new SessionStatusViewModel { Api = api };
model.Refresh();
Assert.False(model.IsAuthenticationRequired);
await Assert.ThrowsAsync<RefreshFailedException>(() =>
api.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken));
Dispatcher.UIThread.RunJobs();
Assert.False(model.IsLoggedIn);
Assert.False(model.IsAdministrator);
Assert.True(model.IsAuthenticationRequired);
Assert.Contains("Session expirée", model.SessionLabel);
Platform.CreateBrowser = () => new FakeAuthorizingBrowser(authority.LoopbackRedirectUri).CreateBrowser();
await model.LoginCommand.ExecuteAsync(null);
Assert.True(model.IsLoggedIn);
Assert.False(model.IsAuthenticationRequired);
await model.LogoutAsync();
Assert.True(model.IsAuthenticationRequired);
Assert.Null(store.Load());
}
finally
{
Platform.CreateBrowser = previousBrowser;
File.Delete(path);
}
}, TestContext.Current.CancellationToken);
[Theory]
[InlineData(320, 480)]
[InlineData(640, 240)]
public Task Modal_blocks_navigation_and_scrolls_on_small_screens_without_a_status_bar(int width, int height)
{
var session = new SessionStatusViewModel();
session.SetError("Session expirée");
var model = new HomePageViewModel(null!, new Settings(), session, null!);
return ui.WithWindowAsync(() => new MainView { DataContext = model }, async window =>
{
var root = Assert.IsType<MainView>(window.Content);
Assert.True(root.AuthenticationModal.IsVisible);
Assert.False(root.NavRoot.IsEnabled);
Assert.True(root.LoginButton.IsFocused);
Assert.Equal(KeyboardNavigationMode.Cycle, KeyboardNavigation.GetTabNavigation(root.AuthenticationModal));
var buttons = new[] { root.LoginButton, root.RegisterButton, root.ForgotPasswordButton };
foreach (var button in buttons)
{
Assert.True(button.IsEffectivelyEnabled);
button.BringIntoView();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var top = button.TranslatePoint(new Point(), root)!.Value.Y;
Assert.InRange(top, 0, root.Bounds.Height - button.Bounds.Height);
Assert.InRange(button.Bounds.Width, 1, width - 24);
}
Assert.DoesNotContain(root.GetVisualDescendants(),
control => control.GetType().Name == "SessionStatusBanner");
Assert.Equal(root.Bounds.Height, root.NavRoot.Bounds.Height);
await Task.CompletedTask;
}, TestContext.Current.CancellationToken, width, height);
}
[Theory]
[InlineData("https://oidc.example", "https://oidc.example/Account/")]
[InlineData("https://oidc.example/tenant/", "https://oidc.example/tenant/Account/")]
public async Task Account_actions_target_the_configured_authority(string authority, string expectedBase)
{
var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
await using var api = new ProfileApi(new Settings
{
Authentication = new AuthenticationSettings { Authority = authority }
}, new TokenStore(path));
var model = new SessionStatusViewModel { Api = api };
Assert.Equal(expectedBase + "Register", model.RegistrationUri.AbsoluteUri);
Assert.Equal(expectedBase + "ForgotPassword", model.ForgotPasswordUri.AbsoluteUri);
api.Settings.Authentication.Authority = "https://new.example";
Assert.Equal("https://new.example/Account/ForgotPassword", model.ForgotPasswordUri.AbsoluteUri);
}
private static Settings SettingsFor(OIDCStubAuthority authority) => new()
{
Authentication = new AuthenticationSettings
{
Authority = authority.Issuer,
ClientId = "postit-tests",
RedirectUri = authority.LoopbackRedirectUri,
Scopes = ["openid", "profile", "blog"]
}
};
private sealed class ProfileApi(Settings settings, TokenStore store) : YavscApiClient(settings, store)
{
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null,
CancellationToken ct = default)
=> Task.FromResult(JsonSerializer.Deserialize<T>("""{"Roles":["Administrator"]}""")!);
}
}

View file

@ -19,6 +19,30 @@ namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class YavscApiClientTests
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Rejected_authenticated_retry_requires_login_but_anonymous_401_does_not(bool anonymous)
{
using var authority = await OIDCStubAuthority.StartAsync();
using var apiServer = new StubApiServer { AlwaysUnauthorized = true };
await apiServer.StartAsync();
var path = TokensPath();
try
{
await using var client = await LoginAndPersistAsync(BuildSettings(authority, apiServer.BaseUrl), authority, path);
var changes = new List<string?>();
client.SessionChanged += changes.Add;
await Assert.ThrowsAsync<HttpRequestException>(() => anonymous
? client.GetAnonymousAsync<List<StubApiServer.Post>>(apiServer.BaseUrl, TestContext.Current.CancellationToken)
: client.CallAsync<List<StubApiServer.Post>>(HttpMethod.Get, apiServer.BaseUrl, TestContext.Current.CancellationToken));
Assert.Equal(anonymous ? 0 : 1, authority.RefreshRequestCount);
if (anonymous) Assert.Empty(changes);
else Assert.Contains("Veuillez vous reconnecter", changes.Last());
}
finally { File.Delete(path); }
}
[Theory]
[InlineData(600, true, false, 540)]
[InlineData(3600, false, true, 3540)]
@ -792,6 +816,7 @@ internal sealed class StubApiServer : IAsyncDisposable, IDisposable
public List<string> SeenBearers { get; } = new();
public int RequestCount => _requestCount;
public string? RejectedBearer { get; set; }
public bool AlwaysUnauthorized { get; set; }
public StubApiServer(bool forceFirstRequest = false)
{
@ -824,7 +849,7 @@ internal sealed class StubApiServer : IAsyncDisposable, IDisposable
if (!string.IsNullOrEmpty(auth))
SeenBearers.Add(auth!);
if ((_forceFirstRequest && _requestCount == 1)
if (AlwaysUnauthorized || (_forceFirstRequest && _requestCount == 1)
|| (RejectedBearer is not null && auth == RejectedBearer))
{
ctx.Response.StatusCode = 401;

View file

@ -270,7 +270,6 @@ public partial class App : Application, ILiveView, IVMPusherApp
if (rootView.DataContext==null)
rootView.DataContext = ServiceProvider!.GetRequiredService<HomePageViewModel>();
rootView.SessionBanner.DataContext = sessionStatus;
this.View = rootView;
}
@ -296,21 +295,17 @@ public partial class App : Application, ILiveView, IVMPusherApp
private Task BootOnceAsync()
{
var api = ServiceProvider!.GetRequiredService<YavscApiClient>();
return _bootTask ??= BootAsync(ServiceProvider!, api);
return _bootTask ??= BootAsync(ServiceProvider!);
}
/// <summary>
/// Refresh cached OIDC tokens once per application process.
/// Each root view initializes or restores its own navigation stack separately.
/// </summary>
private static async Task BootAsync(
IServiceProvider provider,
YavscApiClient api)
private static async Task BootAsync(IServiceProvider provider)
{
await api.TrySilentLoginAsync().ConfigureAwait(true);
var sessionStatus = provider.GetRequiredService<SessionStatusViewModel>();
await sessionStatus.RefreshAsync();
await sessionStatus.InitializeAsync();
await provider.GetRequiredService<MessagingSession>().StartAsync(connectOnLogin: OperatingSystem.IsAndroid());
}

View file

@ -144,12 +144,10 @@ public static class ServiceCollectionHelpers
services.AddTransient<PostAclDialog>();
services.AddTransient<AddCircleMemberDialog>();
services.AddTransient<ConfirmationDialog>();
// Persistent session banner: one instance for the lifetime of
// the app so the same VM survives page navigation.
// Authentication state survives page navigation and Android activity recreation.
var sessionStatus = new SessionStatusViewModel { Api = api };
sessionStatus.Refresh();
services.AddSingleton(sessionStatus);
services.AddSingleton<SessionStatusBanner>();
services.AddSingleton<BlogsViewModel>();
return services.BuildServiceProvider();
}

View file

@ -28,6 +28,8 @@ namespace PostIt.Services;
public class YavscApiClient : IYavscApiClient, IAsyncDisposable
{
public event Func<Task>? SigningOut;
/// <summary>A null error announces renewal or logout; failures require authentication UI.</summary>
public event Action<string?>? SessionChanged;
private int _signingOut;
public bool IsSigningOut => Volatile.Read(ref _signingOut) != 0;
// 60s of slack before the access_token's nominal expiry. Covers
@ -138,16 +140,19 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
{
var tokens = _tokens;
if ((!applicationActive && !Settings.AndroidKeepChatConnected)
|| IsSigningOut || string.IsNullOrEmpty(tokens?.RefreshToken))
|| IsSigningOut || tokens is null)
return Timeout.InfiniteTimeSpan;
var delay = tokens.AccessTokenExpiresAt - RefreshSkew - now;
var delay = tokens.AccessTokenExpiresAt
- (string.IsNullOrEmpty(tokens.RefreshToken) ? TimeSpan.Zero : RefreshSkew) - now;
return delay > TimeSpan.Zero ? delay : TimeSpan.Zero;
}
internal async Task RefreshSessionIfNeededAsync(bool applicationActive, CancellationToken ct)
{
if ((!applicationActive && !Settings.AndroidKeepChatConnected)
|| IsSigningOut || string.IsNullOrEmpty(_tokens?.RefreshToken)) return;
|| IsSigningOut || _tokens is null) return;
if (string.IsNullOrEmpty(_tokens.RefreshToken)
&& _tokens.AccessTokenExpiresAt > DateTimeOffset.UtcNow) return;
await ForceRefreshAsync(ct).ConfigureAwait(false);
}
@ -174,6 +179,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
catch (Exception ex)
{
Console.Error.WriteLine($"Session maintenance failed: {ex}");
SessionChanged?.Invoke($"Renouvellement automatique de la session impossible : {ex.Message}");
Settings.SetActionStatus($"Renouvellement automatique de la session impossible : {ex.Message}",
PostIt.Models.StatusSeverity.Error);
await _maintenanceChanged.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
@ -230,14 +236,18 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
"Missing refresh_token — vérifie le scope 'offline_access'.");
}
_tokens = new RefreshTokenRecord(
AccessToken: result.AccessToken,
RefreshToken: result.RefreshToken,
AccessTokenExpiresAt: ComputeExpiry(result.AccessTokenExpiration, result.AccessToken),
IdToken: result.IdentityToken);
_store.Save(_tokens);
WakeSessionMaintenance();
await _refreshGate.WaitAsync(ct).ConfigureAwait(false);
try
{
_tokens = new RefreshTokenRecord(
AccessToken: result.AccessToken,
RefreshToken: result.RefreshToken,
AccessTokenExpiresAt: ComputeExpiry(result.AccessTokenExpiration, result.AccessToken),
IdToken: result.IdentityToken);
_store.Save(_tokens);
WakeSessionMaintenance();
}
finally { _refreshGate.Release(); }
progress?.Report(OIDCLoginPhase.Success);
}
@ -264,11 +274,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
return true;
}
// Access token expired but we have a refresh token: try the
// silent refresh once. If the OP rejects (revoked, rotation
// theft, network down), the refresh path already purges the
// store and throws RefreshFailedException; we catch and route
// the user back to the login page.
// Only a permanent rejection clears the store; transient failures retain it for retry.
try
{
progress?.Report(OIDCLoginPhase.ExchangingCode);
@ -276,13 +282,19 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
progress?.Report(OIDCLoginPhase.Success);
return true;
}
catch (RefreshFailedException)
catch (RefreshFailedException ex)
{
Console.Error.WriteLine($"Silent login failed: {ex}");
progress?.Report(OIDCLoginPhase.Idle);
return false;
}
catch
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Silent login failed: {ex}");
progress?.Report(OIDCLoginPhase.Idle);
return false;
}
@ -433,7 +445,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
/// here is enough to make the next "click Save" self-explanatory
/// (e.g. <i>"Error: 400 — The Title field is required."</i>).
/// </summary>
private static async Task EnsureSuccessOrThrowAsync(HttpResponseMessage response, CancellationToken ct)
private async Task EnsureSuccessOrThrowAsync(HttpResponseMessage response, CancellationToken ct)
{
if (response.IsSuccessStatusCode) return;
@ -458,6 +470,9 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
var msg = body.Length > 0
? $"{(int)response.StatusCode} {response.ReasonPhrase}: {body}"
: $"{(int)response.StatusCode} {response.ReasonPhrase}";
if (response.StatusCode == HttpStatusCode.Unauthorized
&& !(response.RequestMessage?.Options.TryGetValue(AnonymousRequest, out var anonymous) == true && anonymous))
SessionChanged?.Invoke("Le serveur a refusé la session. Veuillez vous reconnecter.");
throw new HttpRequestException(msg, inner: null, statusCode: response.StatusCode);
}
@ -484,8 +499,15 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
if (IsSigningOut)
throw new InvalidOperationException("Deconnexion en cours.");
var tokens = _tokens;
if (tokens is null || string.IsNullOrEmpty(tokens.RefreshToken))
if (tokens is null)
throw new InvalidOperationException("Session expirée. Veuillez vous reconnecter.");
if (string.IsNullOrEmpty(tokens.RefreshToken))
{
_store.Clear();
_tokens = null;
WakeSessionMaintenance();
throw new RefreshFailedException("Session expirée. Veuillez vous reconnecter.", isPermanent: true);
}
if (rejectedAccessToken is null
? tokens.AccessTokenExpiresAt - DateTimeOffset.UtcNow > RefreshSkew
@ -517,6 +539,17 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
_store.Save(_tokens);
WakeSessionMaintenance();
SessionChanged?.Invoke(null);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
if (!IsSigningOut)
SessionChanged?.Invoke(ex.Message);
throw;
}
finally
{
@ -671,6 +704,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
_refreshGate.Release();
Interlocked.Exchange(ref _signingOut, 0);
WakeSessionMaintenance();
SessionChanged?.Invoke(null);
}
}
// Optional: clear the IdP session in the browser too.

View file

@ -2,6 +2,8 @@ using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
@ -11,19 +13,7 @@ using PostIt.Services;
namespace PostIt.ViewModels;
/// <summary>
/// Persistent session banner VM, hosted in
/// <c>MainWindow.axaml</c>. Mirrors <see cref="YavscApiClient"/>'s
/// session state ("Connecté" / "Déconnecté") and exposes a
/// <c>Logout</c> command that purges the token store and asks the
/// navigation owner to route the user back to <c>HomePage</c>, plus
/// a <c>Login</c> command that drives the OIDC interactive flow
/// and raises a <see cref="LoginSucceeded"/> event on success so
/// <c>MainWindow</c> can push <c>MainPage</c> on top of
/// <c>HomePage</c>.
///
/// Construction is deferred until the API client exists; the
/// App.axaml.cs wiring sets <see cref="Api"/> after building both,
/// so the banner reflects reality from frame zero.
/// Shared authentication state and commands for the modal and home menu.
/// </summary>
public partial class SessionStatusViewModel : ViewModelBase
{
@ -31,9 +21,7 @@ public partial class SessionStatusViewModel : ViewModelBase
/// <c>App.axaml.cs</c> listens and swaps the navigation root.</summary>
public event System.Action? LogoutCompleted;
/// <summary>Raised after <see cref="LoginAsync"/> acquired a valid session;
/// <c>App.axaml.cs</c> listens and pushes <c>MainPage</c> on top of
/// <c>HomePage</c> so the user lands on the blog editor.</summary>
/// <summary>Raised after an interactive login acquired a valid session.</summary>
public event System.Action? LoginSucceeded;
[ObservableProperty]
@ -44,27 +32,62 @@ public partial class SessionStatusViewModel : ViewModelBase
private int _accessVersion;
/// <summary>Inverse of <see cref="IsLoggedIn"/>, for XAML bindings
/// (the banner shows the Login button when the user is logged out).
/// Updated from <see cref="Refresh"/>.</summary>
[ObservableProperty]
public partial bool IsLoggedOut { get; private set; } = true;
[ObservableProperty]
public partial bool IsAuthenticationRequired { get; private set; }
[ObservableProperty]
public partial string SessionLabel { get; private set; } = "Déconnecté";
/// <summary>True while a Login flow is in flight; the Login button
/// binds <c>IsEnabled</c> to <c>!IsBusy</c> via
/// <see cref="LoginCommand"/>'s <c>CanExecute</c>.</summary>
[ObservableProperty]
public partial string? ProfileError { get; private set; }
[ObservableProperty]
public partial bool IsBusy { get; private set; }
/// <summary>The API client backing the banner. Set once at startup;
/// the banner polls <c>HasValidSession</c> on demand rather than
/// subscribing to a stream — the session state only changes at
/// login, logout, and silent refresh, all of which already
/// re-evaluate from the same <c>_tokens</c> snapshot.</summary>
public YavscApiClient? Api { get; set; }
private YavscApiClient? _api;
public YavscApiClient? Api
{
get => _api;
set
{
if (_api is not null) _api.SessionChanged -= OnSessionChanged;
_api = value;
if (_api is not null) _api.SessionChanged += OnSessionChanged;
}
}
public Uri RegistrationUri => AccountUri("Register");
public Uri ForgotPasswordUri => AccountUri("ForgotPassword");
private Uri AccountUri(string action) => new(
new Uri((Api?.Settings.Authentication.Authority ?? AuthenticationSettings.DefaultAuthority).TrimEnd('/') + "/"),
"Account/" + action);
private void OnSessionChanged(string? error)
{
void Update()
{
if (error is not null)
SetError(error);
else if (!IsLoggedIn || Api?.HasValidSession != true)
_ = RefreshAsync();
}
if (Dispatcher.UIThread.CheckAccess()) Update();
else Dispatcher.UIThread.Post(Update);
}
public async Task InitializeAsync()
{
if (Api is null)
throw new InvalidOperationException("Client d'authentification indisponible.");
if (await Api.TrySilentLoginAsync())
await RefreshAsync();
else
await LoginAsync();
}
public override bool CanNavigateNext
{
@ -85,6 +108,8 @@ public partial class SessionStatusViewModel : ViewModelBase
var has = Api?.HasValidSession ?? false;
IsLoggedIn = has;
IsLoggedOut = !has;
IsAuthenticationRequired = !has;
ProfileError = null;
SessionLabel = has ? "Connecté" : "Déconnecté";
}
@ -108,44 +133,40 @@ public partial class SessionStatusViewModel : ViewModelBase
catch (Exception ex)
{
if (version == _accessVersion)
{
SessionLabel = $"Impossible de vérifier les droits : {ex.Message}";
ProfileError = SessionLabel;
}
}
}
/// <summary>
/// Override the banner label with an error message. Used when
/// an interactive login attempt fails so the operator sees
/// something on the persistent UI without us needing a
/// dedicated error page. The next <see cref="Refresh"/> call
/// reverts to "Connecté" / "Déconnecté".
/// </summary>
public void SetError(string message)
{
++_accessVersion;
IsAdministrator = false;
IsLoggedIn = false;
IsLoggedOut = true;
IsAuthenticationRequired = true;
ProfileError = null;
SessionLabel = message;
}
/// <summary>
/// Drive the OIDC interactive login. On success, refreshes
/// the banner state and raises <see cref="LoginSucceeded"/> so
/// the navigation owner can push <c>MainPage</c>. On failure,
/// surfaces the error in the banner via <see cref="SetError"/>.
/// </summary>
[RelayCommand(CanExecute = nameof(CanLogin))]
public async Task LoginAsync()
{
if (Api is null) return;
if (IsBusy) return;
var api = Api;
IsBusy = true;
SessionLabel = "Connexion en cours dans le navigateur…";
try
{
await Api.LoginInteractiveAsync().ConfigureAwait(true);
if (api is null)
throw new InvalidOperationException("Client d'authentification indisponible.");
await api.LoginInteractiveAsync().ConfigureAwait(true);
}
catch (Exception ex)
{
SetError($"Login failed: {ex.Message}");
SetError($"Connexion impossible : {ex.Message}");
return;
}
finally
@ -154,13 +175,41 @@ public partial class SessionStatusViewModel : ViewModelBase
}
await RefreshAsync();
if (Api.HasValidSession)
if (IsLoggedIn)
LoginSucceeded?.Invoke();
}
private bool CanLogin() => !IsBusy;
partial void OnIsBusyChanged(bool value) => LoginCommand.NotifyCanExecuteChanged();
partial void OnIsBusyChanged(bool value)
{
LoginCommand.NotifyCanExecuteChanged();
RegisterCommand.NotifyCanExecuteChanged();
ForgotPasswordCommand.NotifyCanExecuteChanged();
}
[RelayCommand(CanExecute = nameof(CanLogin))]
private Task Register() => OpenAccountPageAsync("Register");
[RelayCommand(CanExecute = nameof(CanLogin))]
private Task ForgotPassword() => OpenAccountPageAsync("ForgotPassword");
private async Task OpenAccountPageAsync(string action)
{
try
{
var uri = AccountUri(action);
var view = (App.Current as App)?.View;
var topLevel = view is null ? null : TopLevel.GetTopLevel(view);
if (topLevel is null || !await topLevel.Launcher.LaunchUriAsync(uri))
throw new InvalidOperationException("Impossible d'ouvrir le navigateur.");
SessionLabel = "Terminez l'opération dans le navigateur, puis choisissez Se connecter.";
}
catch (Exception ex)
{
SetError(ex.Message);
}
}
[RelayCommand]
public async System.Threading.Tasks.Task LogoutAsync()

View file

@ -26,6 +26,15 @@
Label="Podcasts : directs et replays" />
</CommandBar.PrimaryCommands>
<CommandBar.SecondaryCommands>
<CommandBarButton
Command="{Binding SessionStatus.OpenSettingsCommand}"
Label="Paramètres" />
<CommandBarButton
Command="{Binding SessionStatus.OpenAboutCommand}"
Label="À propos" />
<CommandBarButton
Command="{Binding SessionStatus.LogoutCommand}"
Label="Se déconnecter" />
<CommandBarButton
Command="{Binding OpenContacts}"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"
@ -99,6 +108,11 @@
FontWeight="SemiBold"
Text="{x:Static lang:Resources.GreetingText}" />
<TextBlock
Foreground="{DynamicResource SystemControlErrorTextForegroundBrush}"
Text="{Binding SessionStatus.ProfileError}"
TextWrapping="Wrap" />
<Grid ColumnDefinitions="*,Auto">
<TextBlock
VerticalAlignment="Center"

View file

@ -3,7 +3,6 @@
xmlns:vm="using:PostIt.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:PostIt.Views"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="PostIt.Views.MainView"
x:DataType="vm:HomePageViewModel">
@ -13,11 +12,38 @@
<vm:HomePageViewModel />
</Design.DataContext>
<DockPanel LastChildFill="True">
<views:SessionStatusBanner
x:Name="SessionBanner"
DataContext="{Binding SessionStatus}"
DockPanel.Dock="Bottom"/>
<Grid>
<NavigationPage x:Name="NavRoot"/>
</DockPanel>
<Border x:Name="AuthenticationModal"
IsVisible="{Binding SessionStatus.IsAuthenticationRequired, FallbackValue=False}"
Background="#80000000"
Padding="12"
KeyboardNavigation.TabNavigation="Cycle">
<Border MaxWidth="420"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Padding="20"
CornerRadius="8"
Background="{DynamicResource SystemControlBackgroundAltHighBrush}"
AutomationProperties.Name="Connexion requise">
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
<StackPanel Spacing="12">
<TextBlock Text="Connexion requise" FontSize="22" FontWeight="SemiBold" TextWrapping="Wrap"/>
<TextBlock Text="PostIt nécessite une connexion. Connectez-vous pour continuer." TextWrapping="Wrap"/>
<TextBlock Text="{Binding SessionStatus.SessionLabel}" TextWrapping="Wrap"/>
<ProgressBar Height="4" IsIndeterminate="True" IsVisible="{Binding SessionStatus.IsBusy}"/>
<Button x:Name="LoginButton" Content="Se connecter"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
Command="{Binding SessionStatus.LoginCommand}"/>
<Button x:Name="RegisterButton" Content="Créer un compte"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
Command="{Binding SessionStatus.RegisterCommand}"/>
<Button x:Name="ForgotPasswordButton" Content="Mot de passe oublié"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
Command="{Binding SessionStatus.ForgotPasswordCommand}"/>
</StackPanel>
</ScrollViewer>
</Border>
</Border>
</Grid>
</UserControl>

View file

@ -2,6 +2,8 @@ using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Threading;
namespace PostIt.Views;
@ -11,11 +13,43 @@ public partial class MainView : UserControl
private IInsetsManager? _insetsManager;
private Thickness _safeArea;
private Rect? _keyboardRect;
private IInputElement? _previousFocus;
internal bool IsSoftKeyboardOpen { get; private set; }
public MainView()
{
InitializeComponent();
AuthenticationModal.PropertyChanged += (_, e) =>
{
if (e.Property != IsVisibleProperty) return;
if (AuthenticationModal.IsVisible)
{
_previousFocus = TopLevel.GetTopLevel(this)?.FocusManager?.GetFocusedElement();
NavRoot.IsEnabled = false;
Dispatcher.UIThread.Post(FocusAuthentication, DispatcherPriority.Input);
}
else
{
NavRoot.IsEnabled = true;
var previousFocus = _previousFocus;
_previousFocus = null;
Dispatcher.UIThread.Post(() =>
{
if (!AuthenticationModal.IsVisible)
previousFocus?.Focus();
}, DispatcherPriority.Input);
}
};
LoginButton.PropertyChanged += (_, e) =>
{
if (e.Property == IsEnabledProperty && LoginButton.IsEnabled && AuthenticationModal.IsVisible)
Dispatcher.UIThread.Post(FocusAuthentication, DispatcherPriority.Input);
};
Loaded += (_, _) =>
{
Dispatcher.UIThread.Post(FocusAuthentication, DispatcherPriority.Input);
};
NavRoot.IsEnabled = !AuthenticationModal.IsVisible;
TopLevel.SetAutoSafeAreaPadding(this, false);
AttachedToVisualTree += (_, _) =>
{
@ -46,6 +80,12 @@ public partial class MainView : UserControl
SizeChanged += (_, _) => ApplyKeyboardOcclusion(_keyboardRect);
}
private void FocusAuthentication()
{
if (AuthenticationModal.IsVisible)
LoginButton.Focus();
}
private void InputPaneStateChanged(object? sender, InputPaneStateEventArgs e)
=> ApplyKeyboardOcclusion(e.NewState == InputPaneState.Open ? e.EndRect : null);

View file

@ -1,36 +0,0 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
x:Class="PostIt.Views.SessionStatusBanner"
x:DataType="vm:SessionStatusViewModel">
<Design.DataContext>
<vm:SessionStatusViewModel />
</Design.DataContext>
<Border DockPanel.Dock="Top"
BorderBrush="#B0BEC5"
BorderThickness="0,0,0,1"
Padding="12,6">
<DockPanel LastChildFill="False">
<TextBlock Text="{Binding SessionLabel}"
FontWeight="SemiBold"
VerticalAlignment="Center"
DockPanel.Dock="Left"/>
<Button Content="Se déconnecter"
Command="{Binding LogoutAsync}"
IsVisible="{Binding IsLoggedIn}"
DockPanel.Dock="Right"/>
<Button Content="Se connecter"
Command="{Binding LoginCommand}"
IsVisible="{Binding IsLoggedOut}"
DockPanel.Dock="Right"/>
<Button Content="Paramètres"
Command="{Binding OpenSettingsCommand}"
DockPanel.Dock="Right"/>
<Button Content="À propos"
Command="{Binding OpenAboutCommand}"
DockPanel.Dock="Right"/>
</DockPanel>
</Border>
</UserControl>

View file

@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace PostIt.Views;
public partial class SessionStatusBanner : UserControl
{
public SessionStatusBanner()
{
InitializeComponent();
}
}