diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index 4fcfafcd1..5b6e1e4e9 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -18,13 +18,16 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:powersync/powersync.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:stream_transform/stream_transform.dart'; +import 'package:wger/powersync/api_client.dart'; import 'package:wger/powersync/connector.dart'; import 'package:wger/powersync/schema.dart'; +import 'package:wger/providers/auth_http_client.dart'; import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/wger_base.dart'; @@ -40,6 +43,8 @@ Future powerSyncInstance(Ref ref) async { await db.initialize(); await _createRawTables(db); + final client = ref.read(authenticatedHttpClientProvider); + // Connect to the sync service only while the device is online. PowerSync's // own retry loop would otherwise log a credential error on every iteration // against an unreachable backend @@ -47,7 +52,7 @@ Future powerSyncInstance(Ref ref) async { if (isOnline) { final serverUrl = ref.read(wgerBaseProvider).serverUrl; if (serverUrl != null) { - connectPowerSync(db, serverUrl); + connectPowerSync(db, serverUrl, client); } } else { db.disconnect(); @@ -129,9 +134,17 @@ Future _createRawTables(PowerSyncDatabase db) async { /// Creates a fresh [DjangoConnector] for [baseUrl] and connects [db] to it. /// Used both at initial creation and after a logout/login cycle to pick up -/// the new user's server URL / credentials. -void connectPowerSync(PowerSyncDatabase db, String baseUrl) { - db.connect(connector: DjangoConnector(baseUrl: baseUrl)); +/// the new user's server URL / credentials. [client] is the authenticated +/// HTTP client (see [authenticatedHttpClientProvider]); the connector reuses +/// it for its REST calls so the same `Authorization` injection and +/// pre-emptive refresh apply. +void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client) { + db.connect( + connector: DjangoConnector( + baseUrl: baseUrl, + apiClient: ApiClient(baseUrl, client: client), + ), + ); } final _syncStatusInternal = StreamProvider((ref) { diff --git a/lib/powersync/api_client.dart b/lib/powersync/api_client.dart index 891d3ddbd..16fda0243 100644 --- a/lib/powersync/api_client.dart +++ b/lib/powersync/api_client.dart @@ -20,44 +20,34 @@ import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; -import 'package:wger/helpers/shared_preferences.dart'; - -import '../helpers/consts.dart'; +/// Thin REST client used by the PowerSync connector. +/// +/// In production the [http.Client] passed in is the project-wide +/// `AuthHttpClient`, which injects the right `Authorization` header +/// (`Bearer` for headless JWT, `Token` for legacy permanent tokens) and +/// runs pre-emptive refresh ahead of token expiry. This class itself +/// therefore stays auth-agnostic: it only sets `Content-Type` and lets +/// the client own everything else. class ApiClient { late final uri = Uri.parse('$serverUrl/api/v2/upload-powersync-data'); final String serverUrl; final http.Client _client; - String token = ''; ApiClient(this.serverUrl, {http.Client? client}) : _client = client ?? http.Client(); Map getHeaders() { - return { - HttpHeaders.contentTypeHeader: 'application/json', - HttpHeaders.authorizationHeader: 'Token $token', - }; + return {HttpHeaders.contentTypeHeader: 'application/json'}; } - /// Returns a powersync JWT token token - /// - /// Note that at the moment we use the permanent API token for authentication - /// but this should be probably changed to the wger API JWT tokens in the - /// future since they are not permanent and could be easily revoked. + /// Fetches a short-lived PowerSync JWT and its endpoint URL from the + /// wger backend. The `Authorization` header for this request is set + /// by the underlying [AuthHttpClient] based on the current auth state. Future> getPowersyncToken() async { - final prefs = PreferenceHelper.asyncPref; - - final apiData = json.decode((await prefs.getString(PREFS_USER))!); - // _logger.info('posting our token "${apiData["token"]}" to $baseUrl/api/v2/powersync-token'); - - token = apiData['token']; final response = await _client.get( Uri.parse('$serverUrl/api/v2/powersync-token'), - headers: { - HttpHeaders.contentTypeHeader: 'application/json', - HttpHeaders.authorizationHeader: 'Token ${apiData["token"]}', - }, + headers: getHeaders(), ); if (response.statusCode == 200) { diff --git a/lib/powersync/connector.dart b/lib/powersync/connector.dart index ddaa2124e..5a56c4e08 100644 --- a/lib/powersync/connector.dart +++ b/lib/powersync/connector.dart @@ -68,8 +68,7 @@ class DjangoConnector extends PowerSyncBackendConnector { /// Resets on app restart. final Set _reportedFailedOps = {}; - DjangoConnector({required this.baseUrl, ApiClient? apiClient}) - : apiClient = apiClient ?? ApiClient(baseUrl); + DjangoConnector({required this.baseUrl, required this.apiClient}); /// Get a token to authenticate against the PowerSync instance. @override diff --git a/lib/providers/account_notifier.dart b/lib/providers/account_notifier.dart index 8d3c53213..0f56f1b59 100644 --- a/lib/providers/account_notifier.dart +++ b/lib/providers/account_notifier.dart @@ -32,10 +32,11 @@ class AccountNotifier extends _$AccountNotifier { return _repo.fetchAccount(); } - /// Triggers the server's verification email flow. - Future verifyEmail() async { - await _repo.verifyEmail(); - } + /// Starts an email-change flow; see [AccountRepository.requestEmailChange]. + Future requestEmailChange(String newEmail) => _repo.requestEmailChange(newEmail); + + /// Re-sends the verification mail for [email]. + Future resendVerification(String email) => _repo.resendVerification(email); /// Clears the cached account (e.g. on logout). void clear() { diff --git a/lib/providers/account_repository.dart b/lib/providers/account_repository.dart index a3ebb3a5e..1280e68a7 100644 --- a/lib/providers/account_repository.dart +++ b/lib/providers/account_repository.dart @@ -23,7 +23,7 @@ import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/wger_base.dart'; const _PROFILE_URL = 'userprofile'; -const _VERIFY_EMAIL = 'verify-email'; +const _HEADLESS_ACCOUNT_EMAIL = 'account/email'; final accountRepositoryProvider = Provider((ref) { final base = ref.read(wgerBaseProvider); @@ -46,9 +46,21 @@ class AccountRepository { return Account.fromJson(data); } - /// Triggers the server's verification email flow. - Future verifyEmail() async { - _logger.finer('Requesting email verification'); - await _base.fetch(_base.makeUrl(_PROFILE_URL, objectMethod: _VERIFY_EMAIL)); + /// Starts an email-change flow against `allauth.headless`. + /// + /// Posting a new address queues it as a pending change: the server mails a + /// verification link to [newEmail], and the new address only replaces the + /// current one once the user clicks that link. Until then the account email + /// is unchanged. + Future requestEmailChange(String newEmail) async { + _logger.finer('Requesting email change'); + await _base.post({'email': newEmail}, _base.makeHeadlessUrl(_HEADLESS_ACCOUNT_EMAIL)); + } + + /// Asks the server to re-send the verification mail for [email]. Useful for + /// users who signed up but never clicked the original link. + Future resendVerification(String email) async { + _logger.finer('Re-sending email verification'); + await _base.put({'email': email}, _base.makeHeadlessUrl(_HEADLESS_ACCOUNT_EMAIL)); } } diff --git a/lib/providers/auth_notifier.dart b/lib/providers/auth_notifier.dart index 082ab387e..b664f5534 100644 --- a/lib/providers/auth_notifier.dart +++ b/lib/providers/auth_notifier.dart @@ -33,6 +33,7 @@ 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_http_client.dart'; import 'package:wger/providers/auth_state.dart'; import 'package:wger/providers/gallery_notifier.dart'; import 'package:wger/providers/helpers.dart'; @@ -819,7 +820,7 @@ class AuthNotifier extends _$AuthNotifier { } try { final db = await ref.read(powerSyncInstanceProvider.future); - connectPowerSync(db, serverUrl); + connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider)); } catch (e, s) { _logger.warning('PowerSync reconnect failed', e, s); } diff --git a/lib/providers/auth_notifier.g.dart b/lib/providers/auth_notifier.g.dart index a80ff95be..cd7f53f9d 100644 --- a/lib/providers/auth_notifier.g.dart +++ b/lib/providers/auth_notifier.g.dart @@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider AuthNotifier(); } -String _$authNotifierHash() => r'4e24dbdc7c2aec17081352a14a193a1bd7369d95'; +String _$authNotifierHash() => r'254a5d552a1bac64c520d8a45c94fadc4f1bed07'; abstract class _$AuthNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index b29eda7b7..1ea831c16 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -71,6 +71,9 @@ class WgerBaseProvider { return makeUri(serverUrl!, path, id: id, objectMethod: objectMethod, query: query); } + /// Builds a `/_allauth/app/v1/` URL for the headless API. + Uri makeHeadlessUrl(String path) => makeHeadlessUri(serverUrl!, path); + /// Fetch and retrieve the overview list of objects, returns the JSON parsed response /// with a simple retry mechanism for transient errors. Future fetch( @@ -164,6 +167,17 @@ class WgerBaseProvider { return json.decode(response.body); } + /// PUTs to the given URI. + Future> put(Map data, Uri uri) async { + final response = await client.put(uri, headers: getDefaultHeaders(), body: json.encode(data)); + + if (response.statusCode >= 400) { + throw WgerHttpException(response); + } + + return response.body.isEmpty ? {} : json.decode(response.body); + } + /// PATCHEs an existing object Future> patch(Map data, Uri uri) async { final response = await client.patch( diff --git a/lib/widgets/user/forms.dart b/lib/widgets/user/forms.dart index c795a7daf..f4cc92317 100644 --- a/lib/widgets/user/forms.dart +++ b/lib/widgets/user/forms.dart @@ -18,16 +18,21 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:wger/helpers/misc.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/user/user_profile.dart'; import 'package:wger/providers/account_notifier.dart'; +import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/user_profile_notifier.dart'; import 'package:wger/theme/theme.dart'; -/// Shows the user's account data (read-only) and lets them edit the profile -/// preferences. The weight-unit preference is persisted through PowerSync, so -/// saving works offline; the e-mail verification action still needs the server. +/// Shows the user's account data and lets them edit the profile preferences. +/// +/// The weight-unit preference is persisted through PowerSync, so saving works +/// offline. The e-mail actions (change address, resend verification) go through +/// `allauth.headless` and therefore need the server. class UserProfileForm extends ConsumerStatefulWidget { const UserProfileForm({super.key}); @@ -36,9 +41,22 @@ class UserProfileForm extends ConsumerStatefulWidget { } class _UserProfileFormState extends ConsumerState { + final _form = GlobalKey(); + final _emailController = TextEditingController(); + /// Pending weight-unit edit, null while it still mirrors the synced value. String? _weightUnitStr; + /// The email field is seeded from the loaded account exactly once; later + /// rebuilds must not clobber what the user typed. + bool _emailInitialised = false; + + @override + void dispose() { + _emailController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); @@ -50,70 +68,138 @@ class _UserProfileFormState extends ConsumerState { return const Center(child: CircularProgressIndicator()); } + if (!_emailInitialised) { + _emailController.text = account.email; + _emailInitialised = true; + } + final weightUnitStr = _weightUnitStr ?? profile.weightUnitStr; final isMetric = weightUnitStr == 'kg'; - return Column( - children: [ - ListTile( - leading: const Icon(Icons.person, color: wgerPrimaryColor), - title: Text(i18n.username), - subtitle: Text(account.username), - ), - ListTile( - leading: const Icon(Icons.email_rounded, color: wgerPrimaryColor), - title: Text( - account.emailVerified ? i18n.verifiedEmail : i18n.unVerifiedEmail, + return Form( + key: _form, + child: Column( + children: [ + ListTile( + leading: const Icon(Icons.person, color: wgerPrimaryColor), + title: Text(i18n.username), + subtitle: Text(account.username), ), - subtitle: Text(account.email), - trailing: account.emailVerified - ? const Icon(Icons.check_circle, color: Colors.green) - : null, - ), - SwitchListTile( - title: Text(i18n.useMetric), - subtitle: Text(weightUnitStr), - value: isMetric, - onChanged: (_) { - setState(() { - _weightUnitStr = isMetric ? i18n.lb : i18n.kg; - }); - }, - dense: true, - ), - if (!account.emailVerified) - OutlinedButton( - onPressed: isOnline - ? () async { - await ref.read(accountProvider.notifier).verifyEmail(); - if (context.mounted) { + SwitchListTile( + title: Text(i18n.useMetric), + subtitle: Text(weightUnitStr), + value: isMetric, + onChanged: (_) { + setState(() { + _weightUnitStr = isMetric ? i18n.lb : i18n.kg; + }); + }, + dense: true, + ), + ListTile( + leading: const Icon(Icons.email_rounded, color: wgerPrimaryColor), + title: TextFormField( + decoration: InputDecoration( + labelText: account.emailVerified + ? i18n.verifiedEmail + : i18n.unVerifiedEmail, + suffixIcon: account.emailVerified + ? const Icon(Icons.check_circle, color: Colors.green) + : null, + ), + controller: _emailController, + keyboardType: TextInputType.emailAddress, + // Email changes go through the server; disable editing offline. + enabled: isOnline, + validator: (value) { + if (value != null && value.isNotEmpty && !value.contains('@')) { + return i18n.invalidEmail; + } + return null; + }, + ), + ), + if (!account.emailVerified) + OutlinedButton( + onPressed: isOnline + ? () async { + await ref + .read(accountProvider.notifier) + .resendVerification(account.email); + if (!context.mounted) { + return; + } ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(i18n.verifiedEmailInfo(account.email)), ), ); } - } - : null, - child: Text(i18n.verify), + : null, + child: Text(i18n.verify), + ), + const Divider(height: 32), + ListTile( + key: const Key('manageAccountOnWebTile'), + leading: const Icon(Icons.open_in_new, color: wgerPrimaryColor), + title: Text(i18n.manageAccountOnWeb), + subtitle: Text(i18n.manageAccountOnWebSubtitle), + enabled: isOnline, + onTap: () { + final serverUrl = ref.read(authProvider).value?.serverUrl; + if (serverUrl == null) { + return; + } + launchURL( + '$serverUrl/user/preferences', + context, + mode: LaunchMode.externalApplication, + ); + }, ), - ElevatedButton( - onPressed: () async { - await ref - .read(userProfileProvider.notifier) - .updateProfile( - UserProfile(id: profile.id, weightUnitStr: weightUnitStr), - ); - if (context.mounted) { + const Divider(height: 32), + ElevatedButton( + onPressed: () async { + if (!_form.currentState!.validate()) { + return; + } + + // The weight unit is synced through PowerSync and saves offline. + await ref + .read(userProfileProvider.notifier) + .updateProfile( + UserProfile(id: profile.id, weightUnitStr: weightUnitStr), + ); + + // Changing the email needs the server: a verification mail is + // sent and the new address only takes effect once confirmed. The + // field is disabled offline, so this never runs without a server. + final newEmail = _emailController.text.trim(); + final emailChanged = newEmail.isNotEmpty && newEmail != account.email; + if (emailChanged) { + await ref.read(accountProvider.notifier).requestEmailChange(newEmail); + // Keep showing the old address until the server confirms it. + _emailController.text = account.email; + } + + if (!context.mounted) { + return; + } Navigator.of(context).pop(); ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(i18n.successfullySaved)), + SnackBar( + content: Text( + emailChanged + ? i18n.verifiedEmailInfo(newEmail) + : i18n.successfullySaved, + ), + ), ); - } - }, - child: Text(i18n.save), - ), - ], + }, + child: Text(i18n.save), + ), + ], + ), ); } } diff --git a/test/exercises/add_exercise_repository_test.mocks.dart b/test/exercises/add_exercise_repository_test.mocks.dart index e3e43d6c8..d437afe16 100644 --- a/test/exercises/add_exercise_repository_test.mocks.dart +++ b/test/exercises/add_exercise_repository_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data, diff --git a/test/exercises/contribute_exercise_test.mocks.dart b/test/exercises/contribute_exercise_test.mocks.dart index ccafc120d..487a503e2 100644 --- a/test/exercises/contribute_exercise_test.mocks.dart +++ b/test/exercises/contribute_exercise_test.mocks.dart @@ -100,9 +100,18 @@ class MockAccountRepository extends _i1.Mock implements _i7.AccountRepository { as _i4.Future<_i2.Account>); @override - _i4.Future verifyEmail() => + _i4.Future requestEmailChange(String? newEmail) => (super.noSuchMethod( - Invocation.method(#verifyEmail, []), + Invocation.method(#requestEmailChange, [newEmail]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future resendVerification(String? email) => + (super.noSuchMethod( + Invocation.method(#resendVerification, [email]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) diff --git a/test/exercises/exercise_repository_test.mocks.dart b/test/exercises/exercise_repository_test.mocks.dart index d8ad91eaa..7e14a2d54 100644 --- a/test/exercises/exercise_repository_test.mocks.dart +++ b/test/exercises/exercise_repository_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data, diff --git a/test/gallery/gallery_repository_test.mocks.dart b/test/gallery/gallery_repository_test.mocks.dart index aa605be14..cd2329e27 100644 --- a/test/gallery/gallery_repository_test.mocks.dart +++ b/test/gallery/gallery_repository_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data, diff --git a/test/nutrition/ingredient_repository_test.mocks.dart b/test/nutrition/ingredient_repository_test.mocks.dart index 119792b73..d5947b0f1 100644 --- a/test/nutrition/ingredient_repository_test.mocks.dart +++ b/test/nutrition/ingredient_repository_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data, diff --git a/test/powersync/api_client_test.dart b/test/powersync/api_client_test.dart index 049bfee0c..3ef08aca4 100644 --- a/test/powersync/api_client_test.dart +++ b/test/powersync/api_client_test.dart @@ -24,10 +24,6 @@ import 'package:http/http.dart' as http; import 'package:http/http.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; -import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; -import 'package:shared_preferences_platform_interface/types.dart'; -import 'package:wger/helpers/consts.dart'; import 'package:wger/powersync/api_client.dart'; import 'api_client_test.mocks.dart'; @@ -40,25 +36,15 @@ void main() { late ApiClient apiClient; const baseUrl = 'https://server.example'; - setUp(() async { + setUp(() { mockClient = MockClient(); apiClient = ApiClient(baseUrl, client: mockClient); - SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); }); - Future seedUserPrefs(Map apiData) async { - await SharedPreferencesAsyncPlatform.instance!.setString( - PREFS_USER, - jsonEncode(apiData), - const SharedPreferencesOptions(), - ); - } - group('getPowersyncToken', () { final tokenUri = Uri.parse('$baseUrl/api/v2/powersync-token'); - test('reads the API token from prefs and GETs the powersync-token endpoint', () async { - await seedUserPrefs({'token': 'abc123'}); + test('GETs the powersync-token endpoint and returns the JSON body', () async { when(mockClient.get(tokenUri, headers: anyNamed('headers'))).thenAnswer( (_) async => Response( jsonEncode({'token': 'jwt-token', 'powersync_url': 'https://ps.example.com'}), @@ -70,31 +56,25 @@ void main() { expect(result['token'], 'jwt-token'); expect(result['powersync_url'], 'https://ps.example.com'); - // The Token header must use the *user's* permanent API token, not the - // returned JWT, that's the auth model for the powersync-token endpoint. - final captured = - verify( - mockClient.get(tokenUri, headers: captureAnyNamed('headers')), - ).captured.single - as Map; - expect(captured[HttpHeaders.authorizationHeader], 'Token abc123'); }); - test('caches the API token on the instance for subsequent CRUD ops', () async { - await seedUserPrefs({'token': 'abc123'}); + test('does not set its own Authorization header (the auth client owns it)', () async { when(mockClient.get(tokenUri, headers: anyNamed('headers'))).thenAnswer( (_) async => Response(jsonEncode({'token': 'jwt'}), 200), ); await apiClient.getPowersyncToken(); - expect(apiClient.token, 'abc123'); - // getHeaders() then uses the cached token. - expect(apiClient.getHeaders()[HttpHeaders.authorizationHeader], 'Token abc123'); + final captured = + verify( + mockClient.get(tokenUri, headers: captureAnyNamed('headers')), + ).captured.single + as Map; + expect(captured.containsKey(HttpHeaders.authorizationHeader), isFalse); + expect(captured[HttpHeaders.contentTypeHeader], contains('application/json')); }); test('throws when the server responds non-200', () async { - await seedUserPrefs({'token': 'abc'}); when( mockClient.get(tokenUri, headers: anyNamed('headers')), ).thenAnswer((_) async => Response('forbidden', 403)); @@ -110,28 +90,23 @@ void main() { 'data': {'id': '5', 'name': 'Push'}, }; - setUp(() { - // Pre-populate the token so getHeaders builds a complete Authorization. - apiClient.token = 'cached-token'; - }); - - test('upsert PUTs the JSON-encoded record', () async { + test('upsert PUTs the JSON-encoded record, no Authorization built locally', () async { when( mockClient.put(uploadUri, headers: anyNamed('headers'), body: anyNamed('body')), ).thenAnswer((_) async => Response('', 200)); await apiClient.upsert(record); - verify( - mockClient.put( - uploadUri, - headers: argThat( - containsPair(HttpHeaders.authorizationHeader, 'Token cached-token'), - named: 'headers', - ), - body: jsonEncode(record), - ), - ).called(1); + final captured = + verify( + mockClient.put( + uploadUri, + headers: captureAnyNamed('headers'), + body: jsonEncode(record), + ), + ).captured.single + as Map; + expect(captured.containsKey(HttpHeaders.authorizationHeader), isFalse); }); test('update PATCHes the JSON-encoded record', () async { diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index d7ea83818..1b87d95e9 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -32,7 +32,7 @@ void main() { late DjangoConnector connector; setUp(() { - connector = DjangoConnector(baseUrl: 'http://example.invalid'); + connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: MockApiClient()); }); /// Builds a JWT-shaped string with the given payload (signature is a sham, diff --git a/test/powersync/connector_test.mocks.dart b/test/powersync/connector_test.mocks.dart index 3fbf9038f..a6a96776d 100644 --- a/test/powersync/connector_test.mocks.dart +++ b/test/powersync/connector_test.mocks.dart @@ -60,23 +60,6 @@ class MockApiClient extends _i1.Mock implements _i3.ApiClient { ) as String); - @override - String get token => - (super.noSuchMethod( - Invocation.getter(#token), - returnValue: _i4.dummyValue( - this, - Invocation.getter(#token), - ), - ) - as String); - - @override - set token(String? value) => super.noSuchMethod( - Invocation.setter(#token, value), - returnValueForMissingStub: null, - ); - @override Map getHeaders() => (super.noSuchMethod( diff --git a/test/providers/media_url_prefix_notifier_test.mocks.dart b/test/providers/media_url_prefix_notifier_test.mocks.dart index 6df21a355..bb844f214 100644 --- a/test/providers/media_url_prefix_notifier_test.mocks.dart +++ b/test/providers/media_url_prefix_notifier_test.mocks.dart @@ -242,6 +242,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i5.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i4.Future fetch( Uri? uri, { @@ -291,6 +302,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i5.WgerBaseProvider { ) as _i4.Future>); + @override + _i4.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i4.Future>.value( + {}, + ), + ) + as _i4.Future>); + @override _i4.Future> patch( Map? data, diff --git a/test/routine/routines_provider_repository_test.mocks.dart b/test/routine/routines_provider_repository_test.mocks.dart index 90979b42f..a0606d12c 100644 --- a/test/routine/routines_provider_repository_test.mocks.dart +++ b/test/routine/routines_provider_repository_test.mocks.dart @@ -391,6 +391,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i7.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i6.Future fetch( Uri? uri, { @@ -440,6 +451,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i7.WgerBaseProvider { ) as _i6.Future>); + @override + _i6.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + @override _i6.Future> patch( Map? data, diff --git a/test/routine/routines_repository_test.mocks.dart b/test/routine/routines_repository_test.mocks.dart index 5b6bc3376..939c66174 100644 --- a/test/routine/routines_repository_test.mocks.dart +++ b/test/routine/routines_repository_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data, diff --git a/test/trophies/provider/trophies_provider_test.mocks.dart b/test/trophies/provider/trophies_provider_test.mocks.dart index c42a81089..8a51b64f9 100644 --- a/test/trophies/provider/trophies_provider_test.mocks.dart +++ b/test/trophies/provider/trophies_provider_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data, diff --git a/test/user/account_notifier_test.dart b/test/user/account_notifier_test.dart index 21bb49258..e0fe70be5 100644 --- a/test/user/account_notifier_test.dart +++ b/test/user/account_notifier_test.dart @@ -67,13 +67,23 @@ void main() { expect(container.read(accountProvider).value, isNull); }); - test('verifyEmail delegates to the repository', () async { + test('requestEmailChange delegates to the repository', () async { final container = makeContainer(); await container.read(accountProvider.future); - when(mockRepo.verifyEmail()).thenAnswer((_) async {}); + when(mockRepo.requestEmailChange(any)).thenAnswer((_) async {}); - await container.read(accountProvider.notifier).verifyEmail(); + await container.read(accountProvider.notifier).requestEmailChange('new@example.com'); - verify(mockRepo.verifyEmail()).called(1); + verify(mockRepo.requestEmailChange('new@example.com')).called(1); + }); + + test('resendVerification delegates to the repository', () async { + final container = makeContainer(); + await container.read(accountProvider.future); + when(mockRepo.resendVerification(any)).thenAnswer((_) async {}); + + await container.read(accountProvider.notifier).resendVerification('me@example.com'); + + verify(mockRepo.resendVerification('me@example.com')).called(1); }); } diff --git a/test/user/account_notifier_test.mocks.dart b/test/user/account_notifier_test.mocks.dart index c1c780811..31d5a8464 100644 --- a/test/user/account_notifier_test.mocks.dart +++ b/test/user/account_notifier_test.mocks.dart @@ -47,9 +47,18 @@ class MockAccountRepository extends _i1.Mock implements _i3.AccountRepository { as _i4.Future<_i2.Account>); @override - _i4.Future verifyEmail() => + _i4.Future requestEmailChange(String? newEmail) => (super.noSuchMethod( - Invocation.method(#verifyEmail, []), + Invocation.method(#requestEmailChange, [newEmail]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future resendVerification(String? email) => + (super.noSuchMethod( + Invocation.method(#resendVerification, [email]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) diff --git a/test/user/account_repository_test.dart b/test/user/account_repository_test.dart index 34eed98e2..e0351d6e4 100644 --- a/test/user/account_repository_test.dart +++ b/test/user/account_repository_test.dart @@ -56,17 +56,25 @@ void main() { }); }); - group('verifyEmail', () { - test('hits the verify-email subpath of userprofile', () async { - final uri = Uri.https('localhost', 'api/v2/userprofile/verify-email/'); - when( - mockBase.makeUrl('userprofile', objectMethod: 'verify-email'), - ).thenReturn(uri); - when(mockBase.fetch(uri)).thenAnswer((_) async => {}); + group('email management via headless', () { + final emailUri = Uri.https('localhost', '/_allauth/app/v1/account/email'); - await repo.verifyEmail(); + test('requestEmailChange POSTs the new address to account/email', () async { + when(mockBase.makeHeadlessUrl('account/email')).thenReturn(emailUri); + when(mockBase.post(any, emailUri)).thenAnswer((_) async => {}); - verify(mockBase.fetch(uri)).called(1); + await repo.requestEmailChange('new@example.com'); + + verify(mockBase.post({'email': 'new@example.com'}, emailUri)).called(1); + }); + + test('resendVerification PUTs the address to account/email', () async { + when(mockBase.makeHeadlessUrl('account/email')).thenReturn(emailUri); + when(mockBase.put(any, emailUri)).thenAnswer((_) async => {}); + + await repo.resendVerification('old@example.com'); + + verify(mockBase.put({'email': 'old@example.com'}, emailUri)).called(1); }); }); } diff --git a/test/user/account_repository_test.mocks.dart b/test/user/account_repository_test.mocks.dart index 584a54cf4..b12fb3378 100644 --- a/test/user/account_repository_test.mocks.dart +++ b/test/user/account_repository_test.mocks.dart @@ -102,6 +102,17 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as Uri); + @override + Uri makeHeadlessUrl(String? path) => + (super.noSuchMethod( + Invocation.method(#makeHeadlessUrl, [path]), + returnValue: _FakeUri_1( + this, + Invocation.method(#makeHeadlessUrl, [path]), + ), + ) + as Uri); + @override _i5.Future fetch( Uri? uri, { @@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { ) as _i5.Future>); + @override + _i5.Future> put(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#put, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + @override _i5.Future> patch( Map? data,