mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-28 17:08:29 +01:00
Edit the user's email via allauth's endpoints
This commit is contained in:
@@ -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<PowerSyncDatabase> 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<PowerSyncDatabase> 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<void> _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<SyncStatus?>((ref) {
|
||||
|
||||
@@ -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<String, String> 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<Map<String, dynamic>> 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) {
|
||||
|
||||
@@ -68,8 +68,7 @@ class DjangoConnector extends PowerSyncBackendConnector {
|
||||
/// Resets on app restart.
|
||||
final Set<String> _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
|
||||
|
||||
@@ -32,10 +32,11 @@ class AccountNotifier extends _$AccountNotifier {
|
||||
return _repo.fetchAccount();
|
||||
}
|
||||
|
||||
/// Triggers the server's verification email flow.
|
||||
Future<void> verifyEmail() async {
|
||||
await _repo.verifyEmail();
|
||||
}
|
||||
/// Starts an email-change flow; see [AccountRepository.requestEmailChange].
|
||||
Future<void> requestEmailChange(String newEmail) => _repo.requestEmailChange(newEmail);
|
||||
|
||||
/// Re-sends the verification mail for [email].
|
||||
Future<void> resendVerification(String email) => _repo.resendVerification(email);
|
||||
|
||||
/// Clears the cached account (e.g. on logout).
|
||||
void clear() {
|
||||
|
||||
@@ -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<AccountRepository>((ref) {
|
||||
final base = ref.read(wgerBaseProvider);
|
||||
@@ -46,9 +46,21 @@ class AccountRepository {
|
||||
return Account.fromJson(data);
|
||||
}
|
||||
|
||||
/// Triggers the server's verification email flow.
|
||||
Future<void> 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<void> 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<void> resendVerification(String email) async {
|
||||
_logger.finer('Re-sending email verification');
|
||||
await _base.put({'email': email}, _base.makeHeadlessUrl(_HEADLESS_ACCOUNT_EMAIL));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider<AuthNotifier, Au
|
||||
AuthNotifier create() => AuthNotifier();
|
||||
}
|
||||
|
||||
String _$authNotifierHash() => r'4e24dbdc7c2aec17081352a14a193a1bd7369d95';
|
||||
String _$authNotifierHash() => r'254a5d552a1bac64c520d8a45c94fadc4f1bed07';
|
||||
|
||||
abstract class _$AuthNotifier extends $AsyncNotifier<AuthState> {
|
||||
FutureOr<AuthState> build();
|
||||
|
||||
@@ -71,6 +71,9 @@ class WgerBaseProvider {
|
||||
return makeUri(serverUrl!, path, id: id, objectMethod: objectMethod, query: query);
|
||||
}
|
||||
|
||||
/// Builds a `/_allauth/app/v1/<path>` 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<dynamic> fetch(
|
||||
@@ -164,6 +167,17 @@ class WgerBaseProvider {
|
||||
return json.decode(response.body);
|
||||
}
|
||||
|
||||
/// PUTs to the given URI.
|
||||
Future<Map<String, dynamic>> put(Map<String, dynamic> 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<Map<String, dynamic>> patch(Map<String, dynamic> data, Uri uri) async {
|
||||
final response = await client.patch(
|
||||
|
||||
@@ -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<UserProfileForm> {
|
||||
final _form = GlobalKey<FormState>();
|
||||
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<UserProfileForm> {
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -100,9 +100,18 @@ class MockAccountRepository extends _i1.Mock implements _i7.AccountRepository {
|
||||
as _i4.Future<_i2.Account>);
|
||||
|
||||
@override
|
||||
_i4.Future<void> verifyEmail() =>
|
||||
_i4.Future<void> requestEmailChange(String? newEmail) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#verifyEmail, []),
|
||||
Invocation.method(#requestEmailChange, [newEmail]),
|
||||
returnValue: _i4.Future<void>.value(),
|
||||
returnValueForMissingStub: _i4.Future<void>.value(),
|
||||
)
|
||||
as _i4.Future<void>);
|
||||
|
||||
@override
|
||||
_i4.Future<void> resendVerification(String? email) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#resendVerification, [email]),
|
||||
returnValue: _i4.Future<void>.value(),
|
||||
returnValueForMissingStub: _i4.Future<void>.value(),
|
||||
)
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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<void> seedUserPrefs(Map<String, dynamic> 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<String, String>;
|
||||
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<String, String>;
|
||||
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<String, String>;
|
||||
expect(captured.containsKey(HttpHeaders.authorizationHeader), isFalse);
|
||||
});
|
||||
|
||||
test('update PATCHes the JSON-encoded record', () async {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<String>(
|
||||
this,
|
||||
Invocation.getter(#token),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
set token(String? value) => super.noSuchMethod(
|
||||
Invocation.setter(#token, value),
|
||||
returnValueForMissingStub: null,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, String> getHeaders() =>
|
||||
(super.noSuchMethod(
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -291,6 +302,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i5.WgerBaseProvider {
|
||||
)
|
||||
as _i4.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i4.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i4.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i4.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i4.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -440,6 +451,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i7.WgerBaseProvider {
|
||||
)
|
||||
as _i6.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i6.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i6.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i6.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i6.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,9 +47,18 @@ class MockAccountRepository extends _i1.Mock implements _i3.AccountRepository {
|
||||
as _i4.Future<_i2.Account>);
|
||||
|
||||
@override
|
||||
_i4.Future<void> verifyEmail() =>
|
||||
_i4.Future<void> requestEmailChange(String? newEmail) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#verifyEmail, []),
|
||||
Invocation.method(#requestEmailChange, [newEmail]),
|
||||
returnValue: _i4.Future<void>.value(),
|
||||
returnValueForMissingStub: _i4.Future<void>.value(),
|
||||
)
|
||||
as _i4.Future<void>);
|
||||
|
||||
@override
|
||||
_i4.Future<void> resendVerification(String? email) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#resendVerification, [email]),
|
||||
returnValue: _i4.Future<void>.value(),
|
||||
returnValueForMissingStub: _i4.Future<void>.value(),
|
||||
)
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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<dynamic> fetch(
|
||||
Uri? uri, {
|
||||
@@ -151,6 +162,16 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider {
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> put(Map<String, dynamic>? data, Uri? uri) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#put, [data, uri]),
|
||||
returnValue: _i5.Future<Map<String, dynamic>>.value(
|
||||
<String, dynamic>{},
|
||||
),
|
||||
)
|
||||
as _i5.Future<Map<String, dynamic>>);
|
||||
|
||||
@override
|
||||
_i5.Future<Map<String, dynamic>> patch(
|
||||
Map<String, dynamic>? data,
|
||||
|
||||
Reference in New Issue
Block a user