From a7e30fcf8ccdb2224e82bdf14a91659a5a0b50cf Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 24 May 2026 20:14:25 +0200 Subject: [PATCH] Refactor auth screen This has been split up into several individual widgets and (hopefully) made more user friendly --- lib/core/validators.dart | 24 +- lib/l10n/app_de.arb | 2 +- lib/l10n/app_en.arb | 48 ++- lib/screens/auth_screen.dart | 373 +------------------ lib/widgets/auth/advanced_footer.dart | 98 +++++ lib/widgets/auth/advanced_sheet.dart | 308 ++++++++++++++++ lib/widgets/auth/auth_card.dart | 382 ++++++++++++++++++++ lib/widgets/auth/auth_mode_switch_link.dart | 67 ++++ lib/widgets/auth/web_handoff_link.dart | 76 ++++ pubspec.lock | 2 +- pubspec.yaml | 2 + test/auth/auth_screen_test.dart | 198 +++++++++- test/core/validators_test.dart | 7 + 13 files changed, 1176 insertions(+), 411 deletions(-) create mode 100644 lib/widgets/auth/advanced_footer.dart create mode 100644 lib/widgets/auth/advanced_sheet.dart create mode 100644 lib/widgets/auth/auth_card.dart create mode 100644 lib/widgets/auth/auth_mode_switch_link.dart create mode 100644 lib/widgets/auth/web_handoff_link.dart diff --git a/lib/core/validators.dart b/lib/core/validators.dart index c9e3e8357..914cdcf69 100644 --- a/lib/core/validators.dart +++ b/lib/core/validators.dart @@ -1,3 +1,21 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import 'package:wger/l10n/generated/app_localizations.dart'; String? validateUrl(String? value, AppLocalizations i18n, {bool required = true}) { @@ -15,10 +33,12 @@ String? validateUrl(String? value, AppLocalizations i18n, {bool required = true} return i18n.invalidUrl; } - // Try to parse as URI + // Try to parse as URI. The earlier startsWith check guarantees a scheme + // and the `//` authority delimiter, but `Uri.parse('http://')` still + // succeeds with an empty host which we reject explicitly try { final uri = Uri.parse(value); - if (!uri.hasScheme || !uri.hasAuthority) { + if (uri.host.isEmpty) { return i18n.invalidUrl; } } catch (e) { diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 8bc7b3030..58635e630 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -158,7 +158,7 @@ "@reset": { "description": "Button text allowing the user to reset the entered values to the default" }, - "customServerHint": "Geben Sie die Adresse deines eigenen Servers ein, ansonsten wird die Standardadresse verwendet", + "customServerHint": "Gebe die Adresse deines eigenen Servers ein, ansonsten wird die Standardadresse verwendet", "@customServerHint": { "description": "Hint text for the form where the users can enter their own wger instance" }, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 5442fa1ff..be23cf89b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -13,14 +13,6 @@ "@register": { "description": "Text for registration button" }, - "useDefaultServer": "Use default server", - "@useDefaultServer": { - "description": "Toggle button allowing users to switch between the default and a custom wger server" - }, - "useCustomServer": "Use custom server", - "@useCustomServer": { - "description": "Toggle button allowing users to switch between the default and a custom wger server" - }, "invalidUrl": "Please enter a valid URL", "@invalidUrl": { "description": "Error message when the user enters an invalid URL, e.g. in the login form" @@ -56,12 +48,6 @@ "@invalidUsername": { "description": "Error message when the user enters an invalid username" }, - "useRefreshToken": "Use refresh token", - "useUsernameAndPassword": "Use username and password", - "loginViaWeb": "Log in via web", - "@loginViaWeb": { - "description": "Button that opens the system browser so the user authenticates on the server (including social or SSO providers) and is handed back to the app via a deep link" - }, "refreshToken": "Refresh token", "@refreshToken": {}, "invalidRefreshToken": "Please enter a valid refresh token", @@ -132,10 +118,36 @@ "@reset": { "description": "Button text allowing the user to reset the entered values to the default" }, - "registerInstead": "Don't have an account? Register now", - "@registerInstead": {}, - "loginInstead": "Already have an account? Login", - "@loginInstead": {}, + "advanced": "Advanced", + "@advanced": {}, + "advancedSubtitle": "Server and authentication options", + "@advancedSubtitle": {}, + "serverSectionLabel": "Server", + "@serverSectionLabel": {}, + "signInMethodSectionLabel": "Sign-in method", + "@signInMethodSectionLabel": {}, + "serverOptionDefaultDetail": "The official server", + "@serverOptionDefaultDetail": {}, + "serverOptionSelfHostedTitle": "Self-hosted", + "@serverOptionSelfHostedTitle": {}, + "serverOptionSelfHostedDetail": "Connect to your own instance", + "@serverOptionSelfHostedDetail": {}, + "authOptionPasswordTitle": "Username and password", + "@authOptionPasswordTitle": {}, + "signInWithToken": "Sign in with token", + "@signInWithToken": {}, + "tokenSubtitle": "Generate one on the wger website", + "@tokenSubtitle": {}, + "newToWger": "New to wger?", + "@newToWger": {}, + "alreadyHaveAccount": "Already have an account?", + "@alreadyHaveAccount": {}, + "tokenLabel": "Token", + "@tokenLabel": {}, + "webHandoffLinkLabel": "Other sign-in options", + "@webHandoffLinkLabel": {}, + "webHandoffLinkSubtitle": "Social login, passkey, SSO", + "@webHandoffLinkSubtitle": {}, "labelBottomNavWorkout": "Workout", "@labelBottomNavWorkout": { "description": "Label used in bottom navigation, use a short word" diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index 7a3ee1b32..c8c57e6d1 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -16,34 +16,9 @@ * along with this program. If not, see . */ -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:url_launcher/url_launcher.dart'; -import 'package:wger/core/error_dialogs.dart'; -import 'package:wger/core/exceptions/http_exception.dart'; -import 'package:wger/core/exceptions/mfa_required_exception.dart'; -import 'package:wger/helpers/consts.dart'; -import 'package:wger/helpers/errors.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/providers/app_link_router.dart'; -import 'package:wger/providers/auth_notifier.dart'; -import 'package:wger/providers/auth_state.dart'; -import 'package:wger/providers/network_provider.dart'; -import 'package:wger/screens/mfa_challenge_screen.dart'; import 'package:wger/theme/theme.dart'; -import 'package:wger/widgets/auth/confirm_password_field.dart'; -import 'package:wger/widgets/auth/email_field.dart'; -import 'package:wger/widgets/auth/password_field.dart'; -import 'package:wger/widgets/auth/refresh_token_field.dart'; -import 'package:wger/widgets/auth/server_field.dart'; -import 'package:wger/widgets/auth/username_field.dart'; -import 'package:wger/widgets/core/server_config_warning_dialog.dart'; - -enum AuthMode { - register, - login, -} +import 'package:wger/widgets/auth/auth_card.dart'; class AuthScreen extends StatelessWidget { const AuthScreen(); @@ -105,349 +80,3 @@ class AuthScreen extends StatelessWidget { ); } } - -class AuthCard extends ConsumerStatefulWidget { - const AuthCard(); - - @override - _AuthCardState createState() => _AuthCardState(); -} - -class _AuthCardState extends ConsumerState { - WgerHttpException? _httpError; - bool _showNetworkError = false; - - final GlobalKey _formKey = GlobalKey(); - AuthMode _authMode = AuthMode.login; - bool _hideCustomServer = true; - bool _useUsernameAndPassword = true; - var _isLoading = false; - final _usernameController = TextEditingController(); - final _passwordController = TextEditingController(); - final _password2Controller = TextEditingController(); - final _emailController = TextEditingController(); - final _serverUrlController = TextEditingController( - text: kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD, - ); - final _refreshTokenController = TextEditingController(); - - @override - void dispose() { - _usernameController.dispose(); - _passwordController.dispose(); - _password2Controller.dispose(); - _emailController.dispose(); - _serverUrlController.dispose(); - _refreshTokenController.dispose(); - super.dispose(); - } - - @override - void initState() { - super.initState(); - AuthNotifier.getServerUrlFromPrefs().then((value) { - if (mounted) { - _serverUrlController.text = value; - } - }); - - _preFillTextfields(); - } - - /// Opens the server's web-handoff page in the system browser. The user - /// authenticates there (password, social, SSO, …) and the server redirects - /// back via `wger://app-auth#token=…`, which the app_link_router picks up - /// and feeds into the existing refresh-token login path. - Future _launchWebHandoff() async { - var serverUrl = _serverUrlController.text.trim(); - if (serverUrl.endsWith('/')) { - serverUrl = serverUrl.substring(0, serverUrl.length - 1); - } - if (serverUrl.isEmpty) { - serverUrl = kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD; - } - final state = await issueAppAuthState(); - await launchUrl( - Uri.parse('$serverUrl/user/app-auth/?state=$state'), - mode: LaunchMode.externalApplication, - ); - } - - void _preFillTextfields() { - if (kDebugMode && _authMode == AuthMode.login) { - setState(() { - _usernameController.text = TESTSERVER_USER_NAME; - _passwordController.text = TESTSERVER_PASSWORD; - }); - } - } - - void _resetTextfields() { - _usernameController.clear(); - _passwordController.clear(); - _refreshTokenController.clear(); - } - - Future _submit(BuildContext context) async { - if (!_formKey.currentState!.validate()) { - return; - } - setState(() { - _isLoading = true; - }); - - var serverUrl = _serverUrlController.text; - if (serverUrl.endsWith('/')) { - serverUrl = serverUrl.substring(0, serverUrl.length - 1); - } - - try { - final authNotifier = ref.read(authProvider.notifier); - // Login existing user - late LoginActions res; - if (_authMode == AuthMode.login) { - res = await authNotifier.login( - _usernameController.text, - _passwordController.text, - serverUrl, - _refreshTokenController.text, - ); - - // Register new user - } else { - res = await authNotifier.register( - username: _usernameController.text, - password: _passwordController.text, - email: _emailController.text, - serverUrl: serverUrl, - locale: Localizations.localeOf(context).languageCode, - ); - } - - // The "update required" screens are handled reactively by main.dart's - // _getHomeScreen, which swaps the home screen on the auth status. - if (context.mounted && res == LoginActions.proceed) { - final showWarning = ref.read(authProvider).value?.serverConfigWarning ?? false; - if (showWarning && context.mounted) { - showServerConfigWarning(context); - ref.read(authProvider.notifier).clearServerConfigWarning(); - } - } - } on MfaRequiredException catch (e) { - if (context.mounted) { - await Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => MfaChallengeScreen( - sessionToken: e.sessionToken, - serverUrl: serverUrl, - availableFactors: e.availableFactors, - ), - ), - ); - } - } on WgerHttpException catch (error) { - if (context.mounted) { - setState(() { - _httpError = error; - _showNetworkError = false; - }); - } - } catch (error) { - // Login is inherently online, but surface an unreachable server as a - // friendly message instead of crashing to the red error screen. - if (isNetworkError(error) && context.mounted) { - setState(() { - _showNetworkError = true; - _httpError = null; - }); - } else { - rethrow; - } - } finally { - if (mounted) { - setState(() => _isLoading = false); - } - } - } - - void _switchAuthMode() { - if (_authMode == AuthMode.login) { - setState(() { - _authMode = AuthMode.register; - _useUsernameAndPassword = true; - }); - _resetTextfields(); - } else { - setState(() { - _authMode = AuthMode.login; - }); - _preFillTextfields(); - } - } - - @override - Widget build(BuildContext context) { - final i18n = AppLocalizations.of(context); - final deviceSize = MediaQuery.sizeOf(context); - // Login/registration both need the server, so disable the action while - // there is no connectivity. - final isOnline = ref.watch(networkStatusProvider); - - Widget errorMessage = const SizedBox.shrink(); - if (_httpError != null) { - errorMessage = FormHttpErrorsWidget(_httpError!); - } else if (_showNetworkError) { - errorMessage = Padding( - padding: const EdgeInsets.only(bottom: 10), - child: Text( - i18n.errorCouldNotConnectToServer, - textAlign: TextAlign.center, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - ); - } - - return Card( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(15.0), - ), - elevation: 8.0, - child: Container( - width: deviceSize.width * 0.9, - padding: EdgeInsets.symmetric( - horizontal: 15.0, - vertical: 0.025 * deviceSize.height, - ), - child: Form( - key: _formKey, - child: SingleChildScrollView( - child: AutofillGroup( - child: Column( - children: [ - errorMessage, - if (_useUsernameAndPassword) UsernameField(controller: _usernameController), - if (_authMode == AuthMode.register) EmailField(controller: _emailController), - if (_useUsernameAndPassword) - PasswordField( - controller: _passwordController, - enforceMinLength: _authMode == AuthMode.register, - ), - - if (_authMode == AuthMode.register) - ConfirmPasswordField( - controller: _password2Controller, - passwordController: _passwordController, - ), - - if (_authMode == AuthMode.login && !_useUsernameAndPassword) - RefreshTokenField(controller: _refreshTokenController), - if (!_hideCustomServer) ServerField(controller: _serverUrlController), - if (!_hideCustomServer) - TextButton( - key: const ValueKey('toggleRefreshTokenButton'), - onPressed: _authMode == AuthMode.login - ? () => setState(() => _useUsernameAndPassword = !_useUsernameAndPassword) - : null, - child: Text( - _useUsernameAndPassword - ? i18n.useRefreshToken - : i18n.useUsernameAndPassword, - ), - ), - - if (_authMode == AuthMode.login) - TextButton.icon( - key: const Key('loginViaWebButton'), - onPressed: _isLoading ? null : _launchWebHandoff, - icon: const Icon(Icons.open_in_browser), - label: Text(i18n.loginViaWeb), - ), - - const SizedBox(height: 20), - SizedBox( - width: double.infinity, - height: 45, - child: ElevatedButton( - key: const Key('actionButton'), - onPressed: isOnline - ? () { - if (!_isLoading) { - _submit(context); - } - } - : null, - style: ElevatedButton.styleFrom( - backgroundColor: Theme.of(context).colorScheme.primary, - ), - child: _isLoading - ? const CircularProgressIndicator( - valueColor: AlwaysStoppedAnimation(Colors.white), - ) - : Text( - _authMode == AuthMode.login ? i18n.login : i18n.register, - style: const TextStyle( - color: Colors.white, - fontWeight: FontWeight.w600, - ), - ), - ), - ), - - const SizedBox(height: 20), - Builder( - key: const Key('toggleActionButton'), - builder: (context) { - final String text = _authMode != AuthMode.register - ? i18n.registerInstead - : i18n.loginInstead; - - return GestureDetector( - onTap: () => _switchAuthMode(), - child: Container( - color: Colors.transparent, - child: Column( - children: [ - // TODO: i18n! - Text( - text.substring(0, text.lastIndexOf('?') + 1), - ), - Text( - text.substring( - text.lastIndexOf('?') + 1, - text.length, - ), - style: const TextStyle( - //color: wgerPrimaryColor, - fontWeight: FontWeight.w700, - ), - ), - ], - ), - ), - ); - }, - ), - const SizedBox(height: 15), - TextButton( - key: const Key('toggleCustomServerButton'), - onPressed: () { - setState(() { - _hideCustomServer = !_hideCustomServer; - if (_hideCustomServer) { - _useUsernameAndPassword = true; - } - }); - }, - child: Text( - _hideCustomServer ? i18n.useCustomServer : i18n.useDefaultServer, - ), - ), - ], - ), - ), - ), - ), - ), - ); - } -} diff --git a/lib/widgets/auth/advanced_footer.dart b/lib/widgets/auth/advanced_footer.dart new file mode 100644 index 000000000..c91804388 --- /dev/null +++ b/lib/widgets/auth/advanced_footer.dart @@ -0,0 +1,98 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// "ADVANCED" footer line opening the advanced sheet. Shows an indicator dot +/// plus a suffix ("{host}" or "Token") when the selection deviates from +/// the default. +class AdvancedFooter extends StatelessWidget { + final bool isCustomServer; + final bool isTokenMode; + final String serverUrl; + final VoidCallback onTap; + + const AdvancedFooter({ + required this.isCustomServer, + required this.isTokenMode, + required this.serverUrl, + required this.onTap, + super.key, + }); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + String? suffix; + if (isCustomServer) { + suffix = serverUrl.trim().replaceFirst(RegExp(r'^https?://'), ''); + } else if (isTokenMode) { + suffix = i18n.tokenLabel; + } + final active = suffix != null; + return TextButton( + key: const Key('advancedButton'), + onPressed: onTap, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (active) ...[ + Container( + width: 6, + height: 6, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 8), + ], + Text( + i18n.advanced.toUpperCase(), + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.outline, + letterSpacing: 0.6, + fontWeight: FontWeight.w600, + ), + ), + if (active) ...[ + const SizedBox(width: 6), + Flexible( + child: Text( + '· $suffix', + overflow: TextOverflow.ellipsis, + maxLines: 1, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.primary, + ), + ), + ), + ], + const SizedBox(width: 4), + Icon( + Icons.keyboard_arrow_down, + size: 14, + color: theme.colorScheme.outline, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/auth/advanced_sheet.dart b/lib/widgets/auth/advanced_sheet.dart new file mode 100644 index 000000000..8f8388894 --- /dev/null +++ b/lib/widgets/auth/advanced_sheet.dart @@ -0,0 +1,308 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/widgets/auth/server_field.dart'; + +/// Opens the advanced bottom sheet (server + sign-in-method selection). +/// +/// [onChanged] fires whenever the user picks a different option so the +/// parent screen can reflect the choice live behind the sheet. +Future showAdvancedSheet({ + required BuildContext context, + required bool initialHideCustomServer, + required bool initialUsePassword, + required bool loginMode, + required TextEditingController serverUrlController, + required void Function(bool hideCustomServer, bool usePassword) onChanged, +}) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + builder: (_) => AdvancedSheet( + initialHideCustomServer: initialHideCustomServer, + initialUsePassword: initialUsePassword, + loginMode: loginMode, + serverUrlController: serverUrlController, + onChanged: onChanged, + ), + ); +} + +class AdvancedSheet extends StatefulWidget { + final bool initialHideCustomServer; + final bool initialUsePassword; + final bool loginMode; + final TextEditingController serverUrlController; + final void Function(bool hideCustomServer, bool usePassword) onChanged; + + const AdvancedSheet({ + required this.initialHideCustomServer, + required this.initialUsePassword, + required this.loginMode, + required this.serverUrlController, + required this.onChanged, + super.key, + }); + + @override + State createState() => _AdvancedSheetState(); +} + +class _AdvancedSheetState extends State { + late bool _hideCustomServer; + late bool _usePassword; + final _formKey = GlobalKey(); + + @override + void initState() { + super.initState(); + _hideCustomServer = widget.initialHideCustomServer; + _usePassword = widget.initialUsePassword; + } + + void _set(VoidCallback change) { + setState(change); + widget.onChanged(_hideCustomServer, _usePassword); + } + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + final defaultServerName = Uri.parse(DEFAULT_SERVER_PROD).host; + + return SingleChildScrollView( + child: Padding( + padding: EdgeInsets.fromLTRB( + 22, + 0, + 22, + 26 + MediaQuery.viewInsetsOf(context).bottom, + ), + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(i18n.advanced, style: theme.textTheme.titleLarge), + Text( + i18n.advancedSubtitle, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + key: const Key('advancedCloseButton'), + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(context), + ), + ], + ), + _SectionLabel(text: i18n.serverSectionLabel), + _OptionRow( + icon: Icons.public_outlined, + title: defaultServerName, + detail: i18n.serverOptionDefaultDetail, + selected: _hideCustomServer, + onTap: () => _set(() => _hideCustomServer = true), + ), + _OptionRow( + icon: Icons.dns_outlined, + title: i18n.serverOptionSelfHostedTitle, + detail: i18n.serverOptionSelfHostedDetail, + selected: !_hideCustomServer, + onTap: () => _set(() => _hideCustomServer = false), + ), + if (!_hideCustomServer) + Padding( + padding: const EdgeInsets.only(top: 2, bottom: 4), + child: ServerField(controller: widget.serverUrlController), + ), + if (widget.loginMode) ...[ + _SectionLabel(text: i18n.signInMethodSectionLabel), + _OptionRow( + icon: Icons.person_outline, + title: i18n.authOptionPasswordTitle, + selected: _usePassword, + onTap: () => _set(() => _usePassword = true), + ), + _OptionRow( + icon: Icons.key_outlined, + title: i18n.refreshToken, + detail: i18n.tokenSubtitle, + selected: !_usePassword, + onTap: () => _set(() => _usePassword = false), + ), + ], + const SizedBox(height: 16), + SizedBox( + height: 45, + child: ElevatedButton( + key: const Key('advancedDoneButton'), + onPressed: () { + if (_formKey.currentState?.validate() ?? true) { + Navigator.pop(context); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: theme.colorScheme.primary, + ), + child: Text( + i18n.done, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _SectionLabel extends StatelessWidget { + final String text; + const _SectionLabel({required this.text}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.only(top: 14, bottom: 8), + child: Text( + text.toUpperCase(), + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.outline, + letterSpacing: 0.6, + fontWeight: FontWeight.w600, + ), + ), + ); + } +} + +class _OptionRow extends StatelessWidget { + final IconData icon; + final String title; + final String? detail; + final bool selected; + final VoidCallback onTap; + + const _OptionRow({ + required this.icon, + required this.title, + this.detail, + required this.selected, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Ink( + decoration: BoxDecoration( + color: selected ? scheme.primaryContainer : scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: selected ? scheme.primary : Colors.transparent, + width: 1, + ), + ), + child: InkWell( + borderRadius: BorderRadius.circular(14), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Row( + children: [ + Container( + width: 36, + height: 36, + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? scheme.primary : scheme.surface, + borderRadius: BorderRadius.circular(10), + border: selected ? null : Border.all(color: scheme.outlineVariant), + ), + child: Icon( + icon, + size: 18, + color: selected ? scheme.onPrimary : scheme.primary, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: textTheme.titleSmall), + const SizedBox(height: 2), + if (detail != null) + Text( + detail!, + style: textTheme.bodySmall?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + width: 20, + height: 20, + alignment: Alignment.center, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: selected ? scheme.primary : Colors.transparent, + border: Border.all( + color: selected ? scheme.primary : scheme.outline, + width: 2, + ), + ), + child: selected ? Icon(Icons.check, size: 12, color: scheme.onPrimary) : null, + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/auth/auth_card.dart b/lib/widgets/auth/auth_card.dart new file mode 100644 index 000000000..b9ef2bcb3 --- /dev/null +++ b/lib/widgets/auth/auth_card.dart @@ -0,0 +1,382 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:wger/core/error_dialogs.dart'; +import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/core/exceptions/mfa_required_exception.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/errors.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/app_link_router.dart'; +import 'package:wger/providers/auth_notifier.dart'; +import 'package:wger/providers/auth_state.dart'; +import 'package:wger/providers/network_provider.dart'; +import 'package:wger/screens/mfa_challenge_screen.dart'; +import 'package:wger/widgets/auth/advanced_sheet.dart'; +import 'package:wger/widgets/core/server_config_warning_dialog.dart'; + +import 'advanced_footer.dart'; +import 'auth_mode_switch_link.dart'; +import 'confirm_password_field.dart'; +import 'email_field.dart'; +import 'password_field.dart'; +import 'refresh_token_field.dart'; +import 'username_field.dart'; +import 'web_handoff_link.dart'; + +enum AuthMode { + register, + login, +} + +class AuthCard extends ConsumerStatefulWidget { + const AuthCard(); + + @override + _AuthCardState createState() => _AuthCardState(); +} + +class _AuthCardState extends ConsumerState { + WgerHttpException? _httpError; + final GlobalKey _formKey = GlobalKey(); + + AuthMode _authMode = AuthMode.login; + + bool _showNetworkError = false; + // Live validation is suppressed until the user taps submit at least once. + // Otherwise programmatic controller writes (debug prefill, _resetTextfields + // on mode switch) trip the FormFields' "interacted by user" flag and + // immediately surface error messages on a form the user hasn't touched. + bool _autoValidate = false; + bool _hideCustomServer = true; + bool _useUsernameAndPassword = true; + var _isLoading = false; + + final _usernameController = TextEditingController(); + final _passwordController = TextEditingController(); + final _password2Controller = TextEditingController(); + final _emailController = TextEditingController(); + final _serverUrlController = TextEditingController( + text: kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD, + ); + final _refreshTokenController = TextEditingController(); + + @override + void dispose() { + _usernameController.dispose(); + _passwordController.dispose(); + _password2Controller.dispose(); + _emailController.dispose(); + _serverUrlController.dispose(); + _refreshTokenController.dispose(); + super.dispose(); + } + + @override + void initState() { + super.initState(); + AuthNotifier.getServerUrlFromPrefs().then((value) { + if (mounted) { + _serverUrlController.text = value; + } + }); + + _preFillTextfields(); + } + + /// Opens the server's web-handoff page in the system browser. The user + /// authenticates there (password, social, SSO, …) and the server redirects + /// back via `wger://app-auth#token=…`, which the app_link_router picks up + /// and feeds into the existing refresh-token login path. + Future _launchWebHandoff() async { + var serverUrl = _serverUrlController.text.trim(); + if (serverUrl.endsWith('/')) { + serverUrl = serverUrl.substring(0, serverUrl.length - 1); + } + if (serverUrl.isEmpty) { + serverUrl = kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD; + } + final state = await issueAppAuthState(); + await launchUrl( + Uri.parse('$serverUrl/user/app-auth/?state=$state'), + mode: LaunchMode.externalApplication, + ); + } + + void _preFillTextfields() { + if (kDebugMode && _authMode == AuthMode.login) { + setState(() { + _usernameController.text = TESTSERVER_USER_NAME; + _passwordController.text = TESTSERVER_PASSWORD; + }); + } + } + + void _resetTextfields() { + _usernameController.clear(); + _passwordController.clear(); + _refreshTokenController.clear(); + } + + Future _submit(BuildContext context) async { + // From the first submit attempt on, validators run live as the user fixes + // each field — but not before. + setState(() { + _autoValidate = true; + }); + if (!_formKey.currentState!.validate()) { + return; + } + setState(() { + _isLoading = true; + }); + + var serverUrl = _serverUrlController.text; + if (serverUrl.endsWith('/')) { + serverUrl = serverUrl.substring(0, serverUrl.length - 1); + } + + try { + final authNotifier = ref.read(authProvider.notifier); + // Login existing user + late LoginActions res; + if (_authMode == AuthMode.login) { + res = await authNotifier.login( + _usernameController.text, + _passwordController.text, + serverUrl, + _refreshTokenController.text, + ); + + // Register new user + } else { + res = await authNotifier.register( + username: _usernameController.text, + password: _passwordController.text, + email: _emailController.text, + serverUrl: serverUrl, + locale: Localizations.localeOf(context).languageCode, + ); + } + + // The "update required" screens are handled reactively by main.dart's + // _getHomeScreen, which swaps the home screen on the auth status. + if (context.mounted && res == LoginActions.proceed) { + final showWarning = ref.read(authProvider).value?.serverConfigWarning ?? false; + if (showWarning && context.mounted) { + showServerConfigWarning(context); + ref.read(authProvider.notifier).clearServerConfigWarning(); + } + } + } on MfaRequiredException catch (e) { + if (context.mounted) { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => MfaChallengeScreen( + sessionToken: e.sessionToken, + serverUrl: serverUrl, + availableFactors: e.availableFactors, + ), + ), + ); + } + } on WgerHttpException catch (error) { + if (context.mounted) { + setState(() { + _httpError = error; + _showNetworkError = false; + }); + } + } catch (error) { + // Login is inherently online, but surface an unreachable server as a + // friendly message instead of crashing to the red error screen. + if (isNetworkError(error) && context.mounted) { + setState(() { + _showNetworkError = true; + _httpError = null; + }); + } else { + rethrow; + } + } finally { + if (mounted) { + setState(() => _isLoading = false); + } + } + } + + void _switchAuthMode() { + if (_authMode == AuthMode.login) { + setState(() { + _authMode = AuthMode.register; + _useUsernameAndPassword = true; + _autoValidate = false; + }); + _resetTextfields(); + } else { + setState(() { + _authMode = AuthMode.login; + _autoValidate = false; + }); + _preFillTextfields(); + } + } + + /// Opens the advanced bottom sheet (server + sign-in-method selection). + void _showAdvancedSheet() { + showAdvancedSheet( + context: context, + initialHideCustomServer: _hideCustomServer, + initialUsePassword: _useUsernameAndPassword, + loginMode: _authMode == AuthMode.login, + serverUrlController: _serverUrlController, + onChanged: (hideCustomServer, usePassword) { + setState(() { + _hideCustomServer = hideCustomServer; + _useUsernameAndPassword = usePassword; + }); + }, + ).then((_) { + if (mounted) { + setState(() {}); + } + }); + } + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + final deviceSize = MediaQuery.sizeOf(context); + // Login/registration both need the server, so disable the action while + // there is no connectivity. + final isOnline = ref.watch(networkStatusProvider); + + Widget errorMessage = const SizedBox.shrink(); + if (_httpError != null) { + errorMessage = FormHttpErrorsWidget(_httpError!); + } else if (_showNetworkError) { + errorMessage = Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Text( + i18n.errorCouldNotConnectToServer, + textAlign: TextAlign.center, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ); + } + + return Card( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15.0), + ), + elevation: 8.0, + child: Container( + width: deviceSize.width * 0.9, + padding: EdgeInsets.symmetric( + horizontal: 15.0, + vertical: 0.025 * deviceSize.height, + ), + child: Form( + key: _formKey, + autovalidateMode: _autoValidate + ? AutovalidateMode.onUserInteraction + : AutovalidateMode.disabled, + child: SingleChildScrollView( + child: AutofillGroup( + child: Column( + children: [ + errorMessage, + if (_useUsernameAndPassword) UsernameField(controller: _usernameController), + if (_authMode == AuthMode.register) EmailField(controller: _emailController), + if (_useUsernameAndPassword) + PasswordField( + controller: _passwordController, + enforceMinLength: _authMode == AuthMode.register, + ), + + if (_authMode == AuthMode.register) + ConfirmPasswordField( + controller: _password2Controller, + passwordController: _passwordController, + ), + + if (_authMode == AuthMode.login && !_useUsernameAndPassword) + RefreshTokenField(controller: _refreshTokenController), + + if (_authMode == AuthMode.login) + WebHandoffLink( + onTap: _isLoading ? null : _launchWebHandoff, + ), + + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 45, + child: ElevatedButton( + key: const Key('actionButton'), + onPressed: isOnline + ? () { + if (!_isLoading) { + _submit(context); + } + } + : null, + style: ElevatedButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.primary, + ), + child: _isLoading + ? const CircularProgressIndicator( + valueColor: AlwaysStoppedAnimation(Colors.white), + ) + : Text( + _authMode == AuthMode.register + ? i18n.register + : (_useUsernameAndPassword ? i18n.login : i18n.signInWithToken), + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + + const SizedBox(height: 12), + AuthModeSwitchLink( + isLogin: _authMode == AuthMode.login, + onTap: _switchAuthMode, + ), + const SizedBox(height: 4), + AdvancedFooter( + isCustomServer: !_hideCustomServer, + isTokenMode: _authMode == AuthMode.login && !_useUsernameAndPassword, + serverUrl: _serverUrlController.text, + onTap: _showAdvancedSheet, + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/auth/auth_mode_switch_link.dart b/lib/widgets/auth/auth_mode_switch_link.dart new file mode 100644 index 000000000..9aec589c7 --- /dev/null +++ b/lib/widgets/auth/auth_mode_switch_link.dart @@ -0,0 +1,67 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Footer line that switches between login and register modes +class AuthModeSwitchLink extends StatelessWidget { + final bool isLogin; + final VoidCallback onTap; + + const AuthModeSwitchLink({ + required this.isLogin, + required this.onTap, + super.key, + }); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + final prompt = isLogin ? i18n.newToWger : i18n.alreadyHaveAccount; + final action = isLogin ? i18n.register : i18n.login; + return InkWell( + key: const Key('toggleActionButton'), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: '$prompt ', + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + TextSpan( + text: action, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + textAlign: TextAlign.center, + ), + ), + ); + } +} diff --git a/lib/widgets/auth/web_handoff_link.dart b/lib/widgets/auth/web_handoff_link.dart new file mode 100644 index 000000000..7bab64503 --- /dev/null +++ b/lib/widgets/auth/web_handoff_link.dart @@ -0,0 +1,76 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Two-line link that hands the login off to the browser. The browser path +/// covers every method allauth supports server-side (social login, passkey, +/// SSO), which the app does not reimplement natively +class WebHandoffLink extends StatelessWidget { + final VoidCallback? onTap; + + const WebHandoffLink({this.onTap, super.key}); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + final isEnabled = onTap != null; + return InkWell( + key: const Key('loginViaWebButton'), + onTap: onTap, + child: Opacity( + opacity: isEnabled ? 1.0 : 0.5, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.open_in_new, + size: 14, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Text( + i18n.webHandoffLinkLabel, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + const SizedBox(height: 2), + Text( + i18n.webHandoffLinkSubtitle, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index 7af7162ae..4bf5c0b26 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1618,7 +1618,7 @@ packages: source: hosted version: "3.2.5" url_launcher_platform_interface: - dependency: transitive + dependency: "direct dev" description: name: url_launcher_platform_interface sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" diff --git a/pubspec.yaml b/pubspec.yaml index 074ea3950..91ef894f6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -83,6 +83,8 @@ dev_dependencies: cider: ^0.2.9 # Used to stub the connectivity_plus platform interface connectivity_plus_platform_interface: ^2.1.0 + # Used to stub the url_launcher platform interface for the web-handoff test + url_launcher_platform_interface: ^2.3.2 drift_dev: ^2.33.0 xml: ^6.6.1 flutter_lints: ^6.0.0 diff --git a/test/auth/auth_screen_test.dart b/test/auth/auth_screen_test.dart index e404ba825..cfa23ddbf 100644 --- a/test/auth/auth_screen_test.dart +++ b/test/auth/auth_screen_test.dart @@ -26,9 +26,11 @@ import 'package:http/http.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:package_info_plus/package_info_plus.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:shared_preferences/shared_preferences.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:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/network_provider.dart'; @@ -38,6 +40,19 @@ import 'package:wger/screens/auth_screen.dart'; import '../fake_connectivity.dart'; import 'auth_screen_test.mocks.dart'; +/// Captures `launchUrl(...)` calls so the web-handoff test can inspect the +/// URL the app would hand off to the system browser, without actually +/// opening one. +class _FakeUrlLauncher extends Fake with MockPlatformInterfaceMixin implements UrlLauncherPlatform { + String? launchedUrl; + + @override + Future launchUrl(String url, LaunchOptions options) async { + launchedUrl = url; + return true; + } +} + @GenerateMocks([http.Client, SecureTokenStorage]) void main() { // The auth screen watches networkStatusProvider to gate the action button. @@ -144,7 +159,7 @@ void main() { // Assert expect(find.text('wger'), findsOneWidget); - expect(find.textContaining("Don't have an account?"), findsOneWidget); + expect(find.textContaining('New to wger?'), findsOneWidget); expect(find.textContaining('Already have an account?'), findsNothing); expect(find.byKey(const Key('inputUsername')), findsOneWidget); @@ -154,8 +169,7 @@ void main() { expect(find.byKey(const Key('inputPassword2')), findsNothing); expect(find.byKey(const Key('actionButton')), findsOneWidget); expect(find.byKey(const Key('toggleActionButton')), findsOneWidget); - expect(find.byKey(const Key('toggleCustomServerButton')), findsOneWidget); - expect(find.byKey(const ValueKey('toggleRefreshTokenButton')), findsNothing); + expect(find.byKey(const Key('advancedButton')), findsOneWidget); }); testWidgets('Login - with username & password - happy path', (WidgetTester tester) async { @@ -312,10 +326,12 @@ void main() { await tester.pumpAndSettle(); // Act - await tester.tap(find.byKey(const ValueKey('toggleCustomServerButton'))); - await tester.pump(); - await tester.tap(find.byKey(const ValueKey('toggleRefreshTokenButton'))); - await tester.pump(); + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Refresh token')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); await tester.enterText(find.byKey(const ValueKey('inputRefreshToken')), validJwt); // Assert that refresh-token mode is active before submitting. @@ -358,10 +374,12 @@ void main() { await tester.pumpAndSettle(); // Act - await tester.tap(find.byKey(const ValueKey('toggleCustomServerButton'))); - await tester.pump(); - await tester.tap(find.byKey(const ValueKey('toggleRefreshTokenButton'))); - await tester.pump(); + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Refresh token')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); await tester.enterText(find.byKey(const ValueKey('inputRefreshToken')), validJwt); await tester.tap(find.byKey(const Key('actionButton'))); await tester.pumpAndSettle(); @@ -408,9 +426,13 @@ void main() { await tester.pumpAndSettle(); // Act - await tester.tap(find.byKey(const Key('toggleCustomServerButton'))); - await tester.pump(); + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); await tester.enterText(find.byKey(const Key('inputServer')), 'https://my.server/'); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); await tester.enterText(find.byKey(const Key('inputUsername')), 'testuser'); await tester.enterText(find.byKey(const Key('inputPassword')), '123456789'); await tester.tap(find.byKey(const Key('actionButton'))); @@ -486,6 +508,123 @@ void main() { // Assert expect(find.text('Server Configuration Issue'), findsOneWidget); }); + + testWidgets('Sheet round-trip: Self-hosted → default server', (WidgetTester tester) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + + // Self-hosted → server field appears in the sheet. + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('inputServer')), findsOneWidget); + + // Back to wger.de → server field disappears again. + await tester.tap(find.text('wger.de')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('inputServer')), findsNothing); + }); + + testWidgets('Sheet round-trip: Refresh token → Username & password', ( + WidgetTester tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + // Refresh token → close → main screen shows JWT field. + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Refresh token')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('inputRefreshToken')), findsOneWidget); + expect(find.byKey(const Key('inputUsername')), findsNothing); + + // Re-open sheet, pick Username & password → close → username/password + // visible again, JWT field gone. + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Username and password')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('inputRefreshToken')), findsNothing); + expect(find.byKey(const Key('inputUsername')), findsOneWidget); + expect(find.byKey(const Key('inputPassword')), findsOneWidget); + }); + + testWidgets('Web handoff link launches app-auth URL with state in prefs', ( + WidgetTester tester, + ) async { + // Intercept url_launcher so no real browser opens. + final original = UrlLauncherPlatform.instance; + final fake = _FakeUrlLauncher(); + UrlLauncherPlatform.instance = fake; + addTearDown(() => UrlLauncherPlatform.instance = original); + + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('loginViaWebButton'))); + await tester.pumpAndSettle(); + + // The handoff URL points at the configured server's app-auth page and + // carries a non-empty state nonce. State persistence to prefs is + // covered by issueAppAuthState's own tests in app_link_router_test. + expect(fake.launchedUrl, isNotNull); + final launched = Uri.parse(fake.launchedUrl!); + expect(launched.scheme, 'https'); + expect(launched.host, 'wger.de'); + expect(launched.path, '/user/app-auth/'); + final state = launched.queryParameters['state']; + expect(state, isNotNull); + expect(state, isNotEmpty); + }); + + testWidgets('Advanced footer shows indicator suffix for custom server', ( + WidgetTester tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + // No indicator while on the default server. + expect(find.textContaining('my.example.com'), findsNothing); + + // Pick Self-hosted with a custom URL. + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('inputServer')), + 'https://my.example.com', + ); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); + + // Footer now carries the scheme-stripped suffix. + expect(find.text('· my.example.com'), findsOneWidget); + + // Reset to wger.de → suffix gone again. + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('wger.de')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedDoneButton'))); + await tester.pumpAndSettle(); + expect(find.textContaining('my.example.com'), findsNothing); + }); }); group('Registration mode', () { @@ -501,7 +640,7 @@ void main() { await tester.pump(); // Assert - expect(find.textContaining("Don't have an account?"), findsNothing); + expect(find.textContaining('New to wger?'), findsNothing); expect(find.textContaining('Already have an account?'), findsOneWidget); expect(find.byKey(const Key('inputUsername')), findsOneWidget); @@ -512,9 +651,11 @@ void main() { expect(find.byKey(const Key('actionButton')), findsOneWidget); expect(find.byKey(const Key('toggleActionButton')), findsOneWidget); - // Act - show custom server - await tester.tap(find.byKey(const Key('toggleCustomServerButton'))); - await tester.pump(); + // Act - show advanced sheet, pick self-hosted, server field appears + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); expect(find.byKey(const Key('inputServer')), findsOneWidget); }); @@ -679,5 +820,28 @@ void main() { mockClient.post(tHeadlessSignup, headers: anyNamed('headers'), body: anyNamed('body')), ); }); + + testWidgets('Mode switch round-trip: login → register → login', ( + WidgetTester tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + // Login → register. + await tester.tap(find.byKey(const Key('toggleActionButton'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('inputEmail')), findsOneWidget); + expect(find.byKey(const Key('inputPassword2')), findsOneWidget); + expect(find.textContaining('Already have an account?'), findsOneWidget); + + // Register → login. + await tester.tap(find.byKey(const Key('toggleActionButton'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('inputEmail')), findsNothing); + expect(find.byKey(const Key('inputPassword2')), findsNothing); + expect(find.textContaining('New to wger?'), findsOneWidget); + }); }); } diff --git a/test/core/validators_test.dart b/test/core/validators_test.dart index ffa4cdf17..c29b472d8 100644 --- a/test/core/validators_test.dart +++ b/test/core/validators_test.dart @@ -46,4 +46,11 @@ void main() { final result = validateUrl('https://example.com', mockI18n); expect(result, isNull); }); + + test('Scheme-only URL with empty host returns error', () { + // Uri.parse('http://') succeeds with an empty host; the validator must + // still reject it. + expect(validateUrl('http://', mockI18n), isNotNull); + expect(validateUrl('https://', mockI18n), isNotNull); + }); }