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

@ -6,6 +6,8 @@
### Added ### Added
* [PostIt/Authentication] Remove the persistent session status bar to recover small-screen space. Restore cached sessions silently and launch OIDC login automatically at startup when restoration fails. Keep proactive renewal and transient-failure retries; display a blocking, scrollable authentication modal on login failure, logout, expired/revoked sessions or a final authenticated 401, with login, registration and password recovery on the configured authority. Move settings, About and logout to the Home menu, preserve the current page during recovery, and cover startup, renewal, account URLs, focus and compact layouts.
* [Resources/Notifications] Persist private user alerts when net resource consumption crosses 50%, 75%, 90%, 95% or 99% of the personal limit, atomically with accounting. Report only the highest threshold crossed per update and rearm after credits or released storage lower consumption. Keep notification consultation and dismissal accessible at quota without consuming resources; no email or live push is sent. * [Resources/Notifications] Persist private user alerts when net resource consumption crosses 50%, 75%, 90%, 95% or 99% of the personal limit, atomically with accounting. Report only the highest threshold crossed per update and rearm after credits or released storage lower consumption. Keep notification consultation and dismissal accessible at quota without consuming resources; no email or live push is sent.
* [Yavsc.Api] Preserve `application/problem+json` for resource-usage relief errors instead of overriding it with a JSON-only Produces attribute; document success/error media types in OpenAPI and verify error payloads. Restore the haircut and grouped-haircut commands removed from the test seed while retaining its three catalog prestations, with repeated-reset coverage. * [Yavsc.Api] Preserve `application/problem+json` for resource-usage relief errors instead of overriding it with a JSON-only Produces attribute; document success/error media types in OpenAPI and verify error payloads. Restore the haircut and grouped-haircut commands removed from the test seed while retaining its three catalog prestations, with repeated-reset coverage.

View file

@ -20,7 +20,10 @@ L'authentification suit **RFC 8252 §7.1** (OAuth 2.0 for Native
Apps — Custom URI Scheme Redirect), pas le pattern loopback Apps — Custom URI Scheme Redirect), pas le pattern loopback
historique. La séquence : historique. La séquence :
1. L'utilisateur clique **Se connecter** sur `LoginPage`. 1. Au démarrage, PostIt restaure la session silencieusement. Si cette
reprise échoue, il lance directement le login OIDC, sans confirmation.
Une nouvelle tentative peut aussi être lancée avec **Se connecter**
dans la modale d'authentification.
2. `YavscApiClient.LoginInteractiveAsync` demande à `OidcClient` 2. `YavscApiClient.LoginInteractiveAsync` demande à `OidcClient`
de calculer l'authorize URL et de la passer à de calculer l'authorize URL et de la passer à
`CustomSchemeBrowser.InvokeAsync`. `CustomSchemeBrowser.InvokeAsync`.
@ -61,8 +64,8 @@ pas vers un serveur HTTP.
| `Services/CustomSchemeBrowser` | `IBrowser` OidcClient qui ouvre le système + attend le pipe. | | `Services/CustomSchemeBrowser` | `IBrowser` OidcClient qui ouvre le système + attend le pipe. |
| `Services/SchemeUrlDetector` | Détection pure, testable, du `postit://callback` dans argv. | | `Services/SchemeUrlDetector` | Détection pure, testable, du `postit://callback` dans argv. |
| `Services/TokenStore` | Persiste `RefreshTokenRecord` (access/refresh/id + expiry). Mode 0600 sur POSIX. | | `Services/TokenStore` | Persiste `RefreshTokenRecord` (access/refresh/id + expiry). Mode 0600 sur POSIX. |
| `ViewModels/SessionStatusViewModel` | VM du bandeau persistant Connecté/Déconnecté + Logout. | | `ViewModels/SessionStatusViewModel` | État partagé de session, démarrage automatique, login/logout et liens de compte. |
| `Views/SessionStatusBanner` | Bandeau affiché en haut de `MainWindow`, visible sur toutes les pages. | | `Views/Layout/MainView` | Modale d'authentification superposée à la navigation, sans barre d'état persistante. |
## Plateformes (`PostIt.Desktop`, `PostIt.Android`, `PostIt.Browser`) ## Plateformes (`PostIt.Desktop`, `PostIt.Android`, `PostIt.Browser`)
@ -78,8 +81,9 @@ Chaque plateforme injecte son propre `IBrowser` via
## UX observable ## UX observable
`LoginPage` affiche en continu la **phase** courante du flow La modale affiche l'attente du navigateur et les erreurs de connexion.
(badge `PhaseLabel`) en plus du `StatusMessage` textuel : Les actions sont désactivées pendant le login pour éviter les ouvertures
concurrentes. Le client expose aussi les phases suivantes à ses appelants :
| Phase | Signification | | Phase | Signification |
|--------------------|------------------------------------------------------------------| |--------------------|------------------------------------------------------------------|
@ -89,7 +93,7 @@ Chaque plateforme injecte son propre `IBrowser` via
| `ExchangingCode` | Trade du `code` contre les tokens à `/connect/token`. | | `ExchangingCode` | Trade du `code` contre les tokens à `/connect/token`. |
| `Success` / `Error`| Issue du flow. | | `Success` / `Error`| Issue du flow. |
Si le badge reste bloqué sur `OpeningBrowser`, **l'OS n'a jamais Si le flow reste bloqué sur `OpeningBrowser`, **l'OS n'a jamais
relancé PostIt avec l'URL `postit://callback`** : le scheme relancé PostIt avec l'URL `postit://callback`** : le scheme
handler n'est pas enregistré correctement. handler n'est pas enregistré correctement.
@ -100,19 +104,42 @@ Au boot, `App.OnFrameworkInitializationCompleted` :
1. Construit le `TokenStore` (~/.config/PostIt/tokens.json) et 1. Construit le `TokenStore` (~/.config/PostIt/tokens.json) et
`YavscApiClient`. Ce dernier charge `_tokens = store.Load()` `YavscApiClient`. Ce dernier charge `_tokens = store.Load()`
dans son constructeur. dans son constructeur.
2. Ouvre `MainWindow` avec `HomePage` comme racine. 2. Crée la racine `MainView` et démarre la maintenance de session.
3. Sur l'événement `Opened`, appelle `TrySilentLoginAsync` : 3. À l'initialisation de la racine, appelle `TrySilentLoginAsync` une
seule fois par processus :
- si l'access token a encore `> RefreshSkew` (60 s) de vie → - si l'access token a encore `> RefreshSkew` (60 s) de vie →
`Success` immédiat, push `MainPage`. `Success` immédiat.
- sinon, tente un refresh via le refresh token. Si l'IdP - sinon, tente un refresh via le refresh token. Si l'IdP
accepte → push `MainPage`. Si l'IdP rejette (révocation, accepte → la session est restaurée. Un rejet permanent
vol, expiration du refresh) → `_store.Clear()`, retour à (`invalid_grant` / `invalid_client`) purge le store ; une erreur
`HomePage`. temporaire conserve les jetons pour une nouvelle tentative.
- sans session restaurée, lance immédiatement le login interactif.
4. Initialise la messagerie et affiche `HomePage` si la pile est vide.
Le bandeau `SessionStatusBanner` reflète `Api.HasValidSession` La maintenance renouvelle les jetons 60 secondes avant expiration,
en continu et expose le bouton **Se déconnecter**, qui appelle sans attendre un appel API. Les échecs temporaires sont retentés après
`Api.LogoutAsync()` (purge du store) puis `PopToRootAsync` 30 secondes ; la reprise d'activité réveille également la maintenance.
pour ramener sur `HomePage`. L'option Android de maintien en arrière-plan conserve son comportement.
Un échec de login ou de renouvellement, l'expiration sans refresh token,
une déconnexion explicite ou un 401 authentifié persistant après la
tentative de refresh affiche la modale de `MainView`. La navigation en
dessous est désactivée et le clavier reste dans la modale. Celle-ci
défile sur les petits écrans et propose :
- **Se connecter** : nouveau flow OIDC/PKCE ;
- **Créer un compte** : navigateur sur `Account/Register` de l'autorité ;
- **Mot de passe oublié** : navigateur sur `Account/ForgotPassword`
de la même autorité configurée.
Les liens conservent l'éventuel préfixe de chemin de l'autorité.
L'ouverture d'un lien de compte ne valide pas une session : l'utilisateur
revient ensuite sur **Se connecter**. Un renouvellement silencieux réussi
ferme la modale sans changer la page ni les brouillons.
**Paramètres**, **À propos** et **Se déconnecter** sont dans le menu
secondaire de l'accueil. La déconnexion purge le store puis ramène la
navigation à l'accueil ; elle ne relance pas le navigateur automatiquement.
## Garanties testées ## Garanties testées
@ -125,9 +152,13 @@ pour ramener sur `HomePage`.
case-insensitive, refuse les faux positifs (`postit-…://`), case-insensitive, refuse les faux positifs (`postit-…://`),
retourne le premier match de manière déterministe. retourne le premier match de manière déterministe.
Le chemin "refresh token rejeté → purge du store" est testé - Démarrage sans session, avec session valide et après refresh silencieux.
manuellement ; le stub `OidcStubAuthority` ne sait pas encore - Rejet du refresh token, erreur temporaire puis reprise, expiration sans
rejeter un refresh token précis — extension future. refresh token, refus 401 persistant et déconnexion explicite.
- Modale en portrait compact et paysage bas : actions accessibles par
défilement, navigation bloquée, restauration du focus et de la page.
- Liens de création de compte et de récupération du mot de passe sur
l'autorité configurée, y compris avec un préfixe de chemin.
## Voir aussi ## Voir aussi

View file

@ -124,7 +124,7 @@ La taille maximale par fichier et les quotas podcast restent inchangés.
L'accueil présente un seul accès **Administration**, visible et exécutable L'accueil présente un seul accès **Administration**, visible et exécutable
uniquement pour le rôle exact `Administrator`. `SessionStatusViewModel.RefreshAsync` uniquement pour le rôle exact `Administrator`. `SessionStatusViewModel.RefreshAsync`
lit les rôles dans `GET account/me` après le rafraîchissement de session ; lit les rôles dans `GET account/me` après le rafraîchissement de session ;
une erreur de lecture masque l'accès et affiche une erreur dans la bannière. une erreur de lecture masque l'accès et affiche une erreur sur l'accueil.
La déconnexion invalide aussi les vérifications de droits encore en vol. La déconnexion invalide aussi les vérifications de droits encore en vol.
`AdministrationPage` regroupe sept onglets : utilisateurs, usages globaux, `AdministrationPage` regroupe sept onglets : utilisateurs, usages globaux,
@ -430,7 +430,7 @@ le DI est construit. Ordre, dans cet ordre :
| `SettingsPage` | **Singleton** | Une seule instance pour la vie de l'app : le `DataContext` est câblé une fois au boot, le push est idempotent (cf. section *Garde anti-empilement* ci-dessous). | | `SettingsPage` | **Singleton** | Une seule instance pour la vie de l'app : le `DataContext` est câblé une fois au boot, le push est idempotent (cf. section *Garde anti-empilement* ci-dessous). |
| `MainPage` / `HomePage` / `SignaturePage` | Transient | Résolution à la demande par le `ViewLocator`. | | `MainPage` / `HomePage` / `SignaturePage` | Transient | Résolution à la demande par le `ViewLocator`. |
| `MainPageViewModel` / `HomePageViewModel` / `SignaturePageViewModel` | Transient | VM reconstruites à chaque navigation ; pas d'état partagé à conserver. | | `MainPageViewModel` / `HomePageViewModel` / `SignaturePageViewModel` | Transient | VM reconstruites à chaque navigation ; pas d'état partagé à conserver. |
| `SessionStatusViewModel` + `SessionStatusBanner` | Singleton + Transient | Le VM est un singleton (survit à la navigation), le bandeau est transient (réinstancié quand la fenêtre le recrée). | | `SessionStatusViewModel` | Singleton | État partagé de session ; la modale de `MainView` survit fonctionnellement à la navigation et à la recréation d'activité via ce VM. |
> **Invariant** : `Settings` est **uniquement** un singleton. Un > **Invariant** : `Settings` est **uniquement** un singleton. Un
> `AddTransient<Settings>()` supplémentaire (qui réécrase le > `AddTransient<Settings>()` supplémentaire (qui réécrase le
@ -621,7 +621,7 @@ pour `[RelayCommand]`".
| Page | DataContext | Rôle | | Page | DataContext | Rôle |
|----------------------------|--------------------------|-----------------------------------------------------------------------| |----------------------------|--------------------------|-----------------------------------------------------------------------|
| `MainWindow` | `HomePageViewModel` (initial) | Host de la `NavigationPage`. | | `MainWindow` | `HomePageViewModel` (initial) | Host de la `NavigationPage`. |
| `SessionStatusBanner` | `SessionStatusViewModel` | Bandeau persistant en haut de la fenêtre, visible sur toutes les pages. Boutons Login / Logout / Paramètres. | | Modale de `MainView` | `SessionStatusViewModel` | Connexion requise : login, inscription et mot de passe oublié. Navigation bloquée jusqu'à la reprise de session ; aucune barre d'état persistante. |
| `HomePage` | `HomePageViewModel` | Page d'accueil publique. | | `HomePage` | `HomePageViewModel` | Page d'accueil publique. |
| `MainPage` | `MainPageViewModel` | Éditeur de post de blog (après login). | | `MainPage` | `MainPageViewModel` | Éditeur de post de blog (après login). |
| `SignaturePage` | `SignaturePageViewModel` | Capture de signature (estimateur). | | `SignaturePage` | `SignaturePageViewModel` | Capture de signature (estimateur). |

View file

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

View file

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

View file

@ -44,7 +44,7 @@ public class MarkdownEditorScrollTests
window.UpdateLayout(); window.UpdateLayout();
Assert.True(page.DraftTitleTextBox.IsVisible); Assert.True(page.DraftTitleTextBox.IsVisible);
Assert.True(page.AttachmentsBorder.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.DraftTitleTextBox));
Assert.Equal(1, Grid.GetColumn(page.AttachmentsBorder)); Assert.Equal(1, Grid.GetColumn(page.AttachmentsBorder));
Assert.True(page.StatusBar.IsVisible); Assert.True(page.StatusBar.IsVisible);
@ -60,7 +60,7 @@ public class MarkdownEditorScrollTests
window.UpdateLayout(); window.UpdateLayout();
Assert.True(page.DraftTitleTextBox.IsVisible); Assert.True(page.DraftTitleTextBox.IsVisible);
Assert.True(page.AttachmentsBorder.IsVisible); Assert.True(page.AttachmentsBorder.IsVisible);
Assert.True(root.SessionBanner.IsVisible); Assert.False(root.AuthenticationModal.IsVisible);
Assert.Equal(0, Grid.GetColumn(page.DraftTitleTextBox)); Assert.Equal(0, Grid.GetColumn(page.DraftTitleTextBox));
Assert.Same(document, source.Document); Assert.Same(document, source.Document);
Assert.True(source.TextArea.IsFocused); Assert.True(source.TextArea.IsFocused);
@ -98,10 +98,10 @@ public class MarkdownEditorScrollTests
window.UpdateLayout(); window.UpdateLayout();
Assert.Equal(new Thickness(20, 26, 22, 32), root.Padding); Assert.Equal(new Thickness(20, 26, 22, 32), root.Padding);
var navigationTop = root.NavRoot.TranslatePoint(new Point(), window)!.Value.Y; 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(navigationTop >= 26);
Assert.True(bannerBottom <= 768); Assert.True(navigationBottom <= 768);
Assert.True(root.SessionBanner.IsVisible); Assert.False(root.AuthenticationModal.IsVisible);
} }
finally 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")] [Trait("Category", "non-reg")]
public class YavscApiClientTests 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] [Theory]
[InlineData(600, true, false, 540)] [InlineData(600, true, false, 540)]
[InlineData(3600, false, true, 3540)] [InlineData(3600, false, true, 3540)]
@ -792,6 +816,7 @@ internal sealed class StubApiServer : IAsyncDisposable, IDisposable
public List<string> SeenBearers { get; } = new(); public List<string> SeenBearers { get; } = new();
public int RequestCount => _requestCount; public int RequestCount => _requestCount;
public string? RejectedBearer { get; set; } public string? RejectedBearer { get; set; }
public bool AlwaysUnauthorized { get; set; }
public StubApiServer(bool forceFirstRequest = false) public StubApiServer(bool forceFirstRequest = false)
{ {
@ -824,7 +849,7 @@ internal sealed class StubApiServer : IAsyncDisposable, IDisposable
if (!string.IsNullOrEmpty(auth)) if (!string.IsNullOrEmpty(auth))
SeenBearers.Add(auth!); SeenBearers.Add(auth!);
if ((_forceFirstRequest && _requestCount == 1) if (AlwaysUnauthorized || (_forceFirstRequest && _requestCount == 1)
|| (RejectedBearer is not null && auth == RejectedBearer)) || (RejectedBearer is not null && auth == RejectedBearer))
{ {
ctx.Response.StatusCode = 401; ctx.Response.StatusCode = 401;

View file

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

View file

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

View file

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

View file

@ -2,6 +2,8 @@ using System;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -11,19 +13,7 @@ using PostIt.Services;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
/// <summary> /// <summary>
/// Persistent session banner VM, hosted in /// Shared authentication state and commands for the modal and home menu.
/// <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.
/// </summary> /// </summary>
public partial class SessionStatusViewModel : ViewModelBase 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> /// <c>App.axaml.cs</c> listens and swaps the navigation root.</summary>
public event System.Action? LogoutCompleted; public event System.Action? LogoutCompleted;
/// <summary>Raised after <see cref="LoginAsync"/> acquired a valid session; /// <summary>Raised after an interactive login acquired a valid session.</summary>
/// <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>
public event System.Action? LoginSucceeded; public event System.Action? LoginSucceeded;
[ObservableProperty] [ObservableProperty]
@ -44,27 +32,62 @@ public partial class SessionStatusViewModel : ViewModelBase
private int _accessVersion; 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] [ObservableProperty]
public partial bool IsLoggedOut { get; private set; } = true; public partial bool IsLoggedOut { get; private set; } = true;
[ObservableProperty]
public partial bool IsAuthenticationRequired { get; private set; }
[ObservableProperty] [ObservableProperty]
public partial string SessionLabel { get; private set; } = "Déconnecté"; public partial string SessionLabel { get; private set; } = "Déconnecté";
/// <summary>True while a Login flow is in flight; the Login button [ObservableProperty]
/// binds <c>IsEnabled</c> to <c>!IsBusy</c> via public partial string? ProfileError { get; private set; }
/// <see cref="LoginCommand"/>'s <c>CanExecute</c>.</summary>
[ObservableProperty] [ObservableProperty]
public partial bool IsBusy { get; private set; } public partial bool IsBusy { get; private set; }
/// <summary>The API client backing the banner. Set once at startup; private YavscApiClient? _api;
/// the banner polls <c>HasValidSession</c> on demand rather than public YavscApiClient? Api
/// subscribing to a stream — the session state only changes at {
/// login, logout, and silent refresh, all of which already get => _api;
/// re-evaluate from the same <c>_tokens</c> snapshot.</summary> set
public YavscApiClient? Api { get; 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 public override bool CanNavigateNext
{ {
@ -85,6 +108,8 @@ public partial class SessionStatusViewModel : ViewModelBase
var has = Api?.HasValidSession ?? false; var has = Api?.HasValidSession ?? false;
IsLoggedIn = has; IsLoggedIn = has;
IsLoggedOut = !has; IsLoggedOut = !has;
IsAuthenticationRequired = !has;
ProfileError = null;
SessionLabel = has ? "Connecté" : "Déconnecté"; SessionLabel = has ? "Connecté" : "Déconnecté";
} }
@ -108,44 +133,40 @@ public partial class SessionStatusViewModel : ViewModelBase
catch (Exception ex) catch (Exception ex)
{ {
if (version == _accessVersion) if (version == _accessVersion)
{
SessionLabel = $"Impossible de vérifier les droits : {ex.Message}"; 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) public void SetError(string message)
{ {
++_accessVersion; ++_accessVersion;
IsAdministrator = false; IsAdministrator = false;
IsLoggedIn = false; IsLoggedIn = false;
IsLoggedOut = true; IsLoggedOut = true;
IsAuthenticationRequired = true;
ProfileError = null;
SessionLabel = message; 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))] [RelayCommand(CanExecute = nameof(CanLogin))]
public async Task LoginAsync() public async Task LoginAsync()
{ {
if (Api is null) return; if (IsBusy) return;
var api = Api;
IsBusy = true; IsBusy = true;
SessionLabel = "Connexion en cours dans le navigateur…";
try 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) catch (Exception ex)
{ {
SetError($"Login failed: {ex.Message}"); SetError($"Connexion impossible : {ex.Message}");
return; return;
} }
finally finally
@ -154,13 +175,41 @@ public partial class SessionStatusViewModel : ViewModelBase
} }
await RefreshAsync(); await RefreshAsync();
if (Api.HasValidSession) if (IsLoggedIn)
LoginSucceeded?.Invoke(); LoginSucceeded?.Invoke();
} }
private bool CanLogin() => !IsBusy; 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] [RelayCommand]
public async System.Threading.Tasks.Task LogoutAsync() public async System.Threading.Tasks.Task LogoutAsync()

View file

@ -26,6 +26,15 @@
Label="Podcasts : directs et replays" /> Label="Podcasts : directs et replays" />
</CommandBar.PrimaryCommands> </CommandBar.PrimaryCommands>
<CommandBar.SecondaryCommands> <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 <CommandBarButton
Command="{Binding OpenContacts}" Command="{Binding OpenContacts}"
IsEnabled="{Binding SessionStatus.IsLoggedIn}" IsEnabled="{Binding SessionStatus.IsLoggedIn}"
@ -99,6 +108,11 @@
FontWeight="SemiBold" FontWeight="SemiBold"
Text="{x:Static lang:Resources.GreetingText}" /> Text="{x:Static lang:Resources.GreetingText}" />
<TextBlock
Foreground="{DynamicResource SystemControlErrorTextForegroundBrush}"
Text="{Binding SessionStatus.ProfileError}"
TextWrapping="Wrap" />
<Grid ColumnDefinitions="*,Auto"> <Grid ColumnDefinitions="*,Auto">
<TextBlock <TextBlock
VerticalAlignment="Center" VerticalAlignment="Center"

View file

@ -3,7 +3,6 @@
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:PostIt.Views"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="PostIt.Views.MainView" x:Class="PostIt.Views.MainView"
x:DataType="vm:HomePageViewModel"> x:DataType="vm:HomePageViewModel">
@ -13,11 +12,38 @@
<vm:HomePageViewModel /> <vm:HomePageViewModel />
</Design.DataContext> </Design.DataContext>
<DockPanel LastChildFill="True"> <Grid>
<views:SessionStatusBanner
x:Name="SessionBanner"
DataContext="{Binding SessionStatus}"
DockPanel.Dock="Bottom"/>
<NavigationPage x:Name="NavRoot"/> <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> </UserControl>

View file

@ -2,6 +2,8 @@ using System;
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Platform; using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Threading;
namespace PostIt.Views; namespace PostIt.Views;
@ -11,11 +13,43 @@ public partial class MainView : UserControl
private IInsetsManager? _insetsManager; private IInsetsManager? _insetsManager;
private Thickness _safeArea; private Thickness _safeArea;
private Rect? _keyboardRect; private Rect? _keyboardRect;
private IInputElement? _previousFocus;
internal bool IsSoftKeyboardOpen { get; private set; } internal bool IsSoftKeyboardOpen { get; private set; }
public MainView() public MainView()
{ {
InitializeComponent(); 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); TopLevel.SetAutoSafeAreaPadding(this, false);
AttachedToVisualTree += (_, _) => AttachedToVisualTree += (_, _) =>
{ {
@ -46,6 +80,12 @@ public partial class MainView : UserControl
SizeChanged += (_, _) => ApplyKeyboardOcclusion(_keyboardRect); SizeChanged += (_, _) => ApplyKeyboardOcclusion(_keyboardRect);
} }
private void FocusAuthentication()
{
if (AuthenticationModal.IsVisible)
LoginButton.Focus();
}
private void InputPaneStateChanged(object? sender, InputPaneStateEventArgs e) private void InputPaneStateChanged(object? sender, InputPaneStateEventArgs e)
=> ApplyKeyboardOcclusion(e.NewState == InputPaneState.Open ? e.EndRect : null); => 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();
}
}