From 225a689e7ea188894cd805116fc0a16716d2e831 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 15 May 2026 14:55:19 +0200 Subject: [PATCH] Implement refresh token logic --- lib/providers/auth_notifier.dart | 93 +++++++++++ lib/providers/helpers.dart | 14 ++ test/auth/auth_notifier_powersync_test.dart | 171 ++++++++++++++++++++ 3 files changed, 278 insertions(+) diff --git a/lib/providers/auth_notifier.dart b/lib/providers/auth_notifier.dart index 1e442a778..dc8ff83fa 100644 --- a/lib/providers/auth_notifier.dart +++ b/lib/providers/auth_notifier.dart @@ -30,6 +30,7 @@ import 'package:version/version.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/database/powersync/powersync.dart'; import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/jwt.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/providers/auth_state.dart'; import 'package:wger/providers/gallery_notifier.dart'; @@ -48,6 +49,10 @@ const REGISTRATION_URL = 'register'; const LOGIN_URL = 'login'; const USERPROFILE_URL = 'userprofile'; +/// `allauth.headless` `app` client refresh endpoint, relative to the +/// `/_allauth/app/v1/` base. +const HEADLESS_TOKENS_REFRESH_PATH = 'tokens/refresh'; + /// HTTP client used by the auth notifier. Override in tests. final authHttpClientProvider = Provider((ref) => http.Client()); @@ -56,6 +61,11 @@ class AuthNotifier extends _$AuthNotifier { final _logger = Logger('AuthNotifier'); late http.Client _client; + /// Holds the in-flight refresh future so concurrent callers share a single + /// network roundtrip. Cleared in `whenComplete` so the next refresh starts + /// a fresh request. + Future? _refreshInFlight; + @override Future build() async { _client = ref.read(authHttpClientProvider); @@ -530,6 +540,89 @@ class AuthNotifier extends _$AuthNotifier { ref.invalidate(galleryProvider); } + /// Exchanges the persisted refresh token for a fresh access/refresh pair. + /// + /// Single-flight: concurrent callers share one HTTP request. On any + /// failure (missing refresh token, missing serverUrl, network error, + /// non-200 response, malformed body) the user is logged out — there is + /// no usable session to fall back to once the refresh token is gone. + /// + /// On success: `state.accessToken` / `state.accessExpiresAt` are updated, + /// the rotated refresh token (when present) is written to secure storage, + /// and the new access token + its expiry are written to shared preferences. + Future refreshAccessToken() { + return _refreshInFlight ??= _runRefresh().whenComplete(() { + _refreshInFlight = null; + }); + } + + Future _runRefresh() async { + final current = _currentOrBlank(); + final serverUrl = current.serverUrl; + if (serverUrl == null) { + _logger.warning('refreshAccessToken: no serverUrl in state, logging out'); + await logout(); + return; + } + + final secureStorage = ref.read(secureTokenStorageProvider); + final refreshToken = await secureStorage.readRefreshToken(); + if (refreshToken == null || refreshToken.isEmpty) { + _logger.warning('refreshAccessToken: no refresh token in secure storage, logging out'); + await logout(); + return; + } + + final http.Response response; + try { + response = await _client.post( + makeHeadlessUri(serverUrl, HEADLESS_TOKENS_REFRESH_PATH), + headers: {HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8'}, + body: json.encode({'refresh_token': refreshToken}), + ); + } on Exception catch (e, s) { + _logger.warning('refreshAccessToken: network error, logging out', e, s); + await logout(); + return; + } + + if (response.statusCode != 200) { + _logger.warning('refreshAccessToken: status ${response.statusCode}, logging out'); + await logout(); + return; + } + + final String newAccess; + final String? newRefresh; + final DateTime? newExp; + try { + final body = json.decode(response.body) as Map; + final meta = body['meta'] as Map; + newAccess = meta['access_token'] as String; + newRefresh = meta['refresh_token'] as String?; + newExp = jwtExp(decodeJwtPayload(newAccess)); + } catch (e, s) { + _logger.warning('refreshAccessToken: malformed response body, logging out', e, s); + await logout(); + return; + } + + // Persist before mutating state so a crash mid-refresh leaves disk and + // state consistent: the next auto-login will read what we wrote here. + final prefs = PreferenceHelper.asyncPref; + await prefs.setString(PREFS_ACCESS_TOKEN, newAccess); + if (newExp != null) { + await prefs.setInt(PREFS_ACCESS_EXPIRES_AT, newExp.millisecondsSinceEpoch); + } else { + await prefs.remove(PREFS_ACCESS_EXPIRES_AT); + } + if (newRefresh != null) { + await secureStorage.writeRefreshToken(newRefresh); + } + + state = AsyncData(current.copyWith(accessToken: newAccess, accessExpiresAt: newExp)); + } + Future logout() async { _logger.fine('logging out'); diff --git a/lib/providers/helpers.dart b/lib/providers/helpers.dart index e80049e78..c5faec488 100644 --- a/lib/providers/helpers.dart +++ b/lib/providers/helpers.dart @@ -88,6 +88,20 @@ Uri makeUri( return uri; } +/// Builds a URL for the `allauth.headless` `app` client API at +/// `/_allauth/app/v1/`. Used by the auth notifier for login, +/// signup, MFA, refresh, etc. The headless API does not use a trailing +/// slash and lives on a separate URL prefix from the DRF data API. +Uri makeHeadlessUri(String serverUrl, String path) { + final Uri uriServer = Uri.parse(serverUrl); + return Uri( + scheme: uriServer.scheme, + host: uriServer.host, + port: uriServer.port, + path: [uriServer.path, '_allauth', 'app', 'v1', path].join('/'), + ); +} + /// Builds the absolute URL for a server-side media file given its /// [relativePath] (the raw value of a Django `ImageField` / `FileField` /// as stored in the DB, e.g. `ingredients/42/foo.jpg`). diff --git a/test/auth/auth_notifier_powersync_test.dart b/test/auth/auth_notifier_powersync_test.dart index cb3a99f2e..4d295bbdf 100644 --- a/test/auth/auth_notifier_powersync_test.dart +++ b/test/auth/auth_notifier_powersync_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -511,4 +512,174 @@ void main() { expect(captured[HttpHeaders.authorizationHeader], 'Token $token'); }); }); + + group('refreshAccessToken', () { + final tRefresh = Uri.parse('$serverUrl/_allauth/app/v1/tokens/refresh'); + + /// Builds a JWT-shaped string with the given payload (signature is a sham, + /// we only ever decode the middle segment). + String makeJwt(Map payload) { + String enc(Map m) => + base64Url.encode(utf8.encode(jsonEncode(m))).replaceAll('=', ''); + return '${enc({'alg': 'HS256', 'typ': 'JWT'})}.${enc(payload)}.signature'; + } + + Future seedHeadlessBundle() async { + final prefs = PreferenceHelper.asyncPref; + await prefs.remove(PREFS_USER); + await prefs.setString(PREFS_ACCESS_TOKEN, 'old-access'); + await prefs.setInt( + PREFS_ACCESS_EXPIRES_AT, + DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch, + ); + await prefs.setString(PREFS_TOKEN_TYPE, AuthTokenType.headlessJwt.name); + await prefs.setString(PREFS_SERVER_URL, serverUrl); + } + + test('happy path: persists rotated refresh + updates state with new access/exp', () async { + await seedHeadlessBundle(); + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + + const expSeconds = 1900000000; + final expectedExp = DateTime.fromMillisecondsSinceEpoch(expSeconds * 1000, isUtc: true); + final newAccess = makeJwt({'sub': '42', 'exp': expSeconds}); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': newAccess, 'refresh_token': 'new-refresh'}, + }), + 200, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).refreshAccessToken(); + + final state = container.read(authProvider).value!; + expect(state.accessToken, newAccess); + expect(state.accessExpiresAt, expectedExp); + + verify(mockSecureStorage.writeRefreshToken('new-refresh')).called(1); + expect(await PreferenceHelper.asyncPref.getString(PREFS_ACCESS_TOKEN), newAccess); + expect( + await PreferenceHelper.asyncPref.getInt(PREFS_ACCESS_EXPIRES_AT), + expectedExp.millisecondsSinceEpoch, + ); + }); + + test('response without rotated refresh leaves the stored refresh token alone', () async { + await seedHeadlessBundle(); + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + + final newAccess = makeJwt({'exp': 1900000000}); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': newAccess}, + }), + 200, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).refreshAccessToken(); + + verifyNever(mockSecureStorage.writeRefreshToken(any)); + }); + + test('no refresh token in secure storage → logout', () async { + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => null); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).refreshAccessToken(); + + expect(container.read(authProvider).value!.status, AuthStatus.loggedOut); + verifyNever(mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body'))); + }); + + test('non-200 response → logout', () async { + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) async => Response('Unauthorized', 401)); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).refreshAccessToken(); + + expect(container.read(authProvider).value!.status, AuthStatus.loggedOut); + }); + + test('network error → logout', () async { + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenThrow(http.ClientException('SocketException: connection refused')); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).refreshAccessToken(); + + expect(container.read(authProvider).value!.status, AuthStatus.loggedOut); + }); + + test('malformed body (no meta) → logout', () async { + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) async => Response(jsonEncode({'status': 200}), 200)); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).refreshAccessToken(); + + expect(container.read(authProvider).value!.status, AuthStatus.loggedOut); + }); + + test('single-flight: concurrent callers share one HTTP request', () async { + await seedHeadlessBundle(); + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + + // Hold the response so both calls overlap. + final completer = Completer(); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) => completer.future); + + final container = makeContainer(); + await container.read(authProvider.future); + final notifier = container.read(authProvider.notifier); + + final f1 = notifier.refreshAccessToken(); + final f2 = notifier.refreshAccessToken(); + + final newAccess = makeJwt({'exp': 1900000000}); + completer.complete( + Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': newAccess, 'refresh_token': 'new-refresh'}, + }), + 200, + ), + ); + await Future.wait([f1, f2]); + + verify( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).called(1); + }); + }); }