Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
23.8 KB
Raw Blame
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../models/sso_provider.dart';
import '../providers/auth_provider.dart';
import '../services/api_config.dart';
import '../widgets/sure_button.dart';
import '../widgets/sure_logo.dart';
import 'backend_config_screen.dart';
import '../l10n/app_localizations.dart';

class LoginScreen extends StatefulWidget {
  final VoidCallback? onGoToSettings;

  const LoginScreen({super.key, this.onGoToSettings});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  static const _emailPlaceholder = '[email protected]';
  static const _passwordPlaceholder = 'Password1!';
  final _emailController = TextEditingController(text: _emailPlaceholder);
  final _passwordController = TextEditingController(text: _passwordPlaceholder);
  final _otpController = TextEditingController();
  final _emailFocus = FocusNode();
  final _passwordFocus = FocusNode();
  bool _obscurePassword = true;
  late final TapGestureRecognizer _signUpTapRecognizer;
  static const _legacyProviders = [
    SsoProvider(name: 'google_oauth2', strategy: 'google_oauth2', label: ''),
  ];
  Future<List<SsoProvider>?>? _ssoProvidersFuture;
  String? _ssoProvidersBaseUrl;

  @override
  void initState() {
    super.initState();
    _signUpTapRecognizer = TapGestureRecognizer()..onTap = _openSignUpPage;
    _emailFocus.addListener(() => _clearPlaceholderOnFocus(
          _emailFocus, _emailController, _emailPlaceholder));
    _passwordFocus.addListener(() => _clearPlaceholderOnFocus(
          _passwordFocus, _passwordController, _passwordPlaceholder));
  }

  Future<void> _openSettings() async {
    if (widget.onGoToSettings != null) {
      widget.onGoToSettings!();
      return;
    }
    await Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (routeContext) => BackendConfigScreen(
          onConfigSaved: () => Navigator.of(routeContext).pop(),
        ),
      ),
    );
    // Rebuild so the backend URL card and SSO providers reflect the new server.
    if (mounted) setState(() {});
  }

  /// Refetches when the backend URL changes (e.g. after editing settings).
  Future<List<SsoProvider>?> _ssoProviders(AuthProvider authProvider) {
    if (_ssoProvidersFuture == null ||
        _ssoProvidersBaseUrl != ApiConfig.baseUrl) {
      _ssoProvidersBaseUrl = ApiConfig.baseUrl;
      // A failed fetch isn't cached, so the next rebuild (e.g. returning from
      // settings) retries instead of keeping the Google fallback.
      late final Future<List<SsoProvider>?> future;
      future = authProvider.fetchSsoProviders().then((providers) {
        if (providers == null && identical(_ssoProvidersFuture, future)) {
          _ssoProvidersFuture = null;
        }
        return providers;
      });
      _ssoProvidersFuture = future;
    }
    return _ssoProvidersFuture!;
  }

  void _clearPlaceholderOnFocus(
      FocusNode node, TextEditingController controller, String placeholder) {
    if (node.hasFocus && controller.text == placeholder) {
      controller.clear();
    }
  }

  @override
  void dispose() {
    _signUpTapRecognizer.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _otpController.dispose();
    _emailFocus.dispose();
    _passwordFocus.dispose();
    super.dispose();
  }

  Future<void> _openSignUpPage() async {
    final l = AppLocalizations.of(context);
    final signUpUrl = Uri.parse('${ApiConfig.defaultBaseUrl}/registration/new');
    final launched = await launchUrl(
      signUpUrl,
      mode: LaunchMode.externalApplication,
    );

    if (!launched && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l.loginSignUpOpenError)),
      );
    }
  }

  Future<void> _showApiKeyDialog() async {
    // The dialog owns its TextEditingController and disposes it in its own
    // State.dispose(), so the controller's lifecycle is tied to the dialog's
    // widget tree: no leak on barrier/back dismissal, and it is never disposed
    // out from under a still-mounted TextField during the exit transition.
    final result = await showDialog<bool>(
      context: context,
      builder: (_) => const ApiKeyLoginDialog(),
    );

    // result: true = signed in, false = login attempt failed, null = dismissed.
    if (result == false && mounted) {
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            authProvider.errorMessage ??
                AppLocalizations.of(context).loginApiKeyInvalid,
          ),
          backgroundColor: Theme.of(context).colorScheme.error,
        ),
      );
    }
  }

  Future<void> _handleLogin() async {
    if (!_formKey.currentState!.validate()) return;

    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final hadOtpCode =
        authProvider.showMfaInput && _otpController.text.isNotEmpty;

    final success = await authProvider.login(
      email: _emailController.text.trim(),
      password: _passwordController.text,
      otpCode: authProvider.showMfaInput ? _otpController.text.trim() : null,
    );

    // Check if widget is still mounted after async operation
    if (!mounted) return;

    // Clear OTP field if login failed and user had entered an OTP code
    // This allows user to easily try again with a new code
    if (!success && hadOtpCode && authProvider.errorMessage != null) {
      _otpController.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final l = AppLocalizations.of(context);

    return Scaffold(
      body: SafeArea(
        child: Stack(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(24),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    const SizedBox(height: 48),
                    // Logo/Title
                    const SureLogo(size: 80),
                    const SizedBox(height: 24),
                    Text.rich(
                      TextSpan(
                        style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                              color: colorScheme.onSurfaceVariant,
                            ),
                        children: [
                          TextSpan(text: l.loginDemoOrSignUpPrefix),
                          TextSpan(
                            text: l.loginSignUpLink,
                            style: TextStyle(
                              color: colorScheme.primary,
                              fontWeight: FontWeight.w600,
                            ),
                            recognizer: _signUpTapRecognizer,
                          ),
                          TextSpan(text: l.loginSignUpSuffix),
                        ],
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 48),

                    // Error Message
                    Consumer<AuthProvider>(
                      builder: (context, authProvider, _) {
                        if (authProvider.errorMessage != null) {
                          return Container(
                            padding: const EdgeInsets.all(12),
                            margin: const EdgeInsets.only(bottom: 16),
                            decoration: BoxDecoration(
                              color: colorScheme.errorContainer,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.error_outline,
                                  color: colorScheme.error,
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Text(
                                    authProvider.errorMessage!,
                                    style: TextStyle(
                                        color: colorScheme.onErrorContainer),
                                  ),
                                ),
                                IconButton(
                                  icon: const Icon(Icons.close),
                                  onPressed: () => authProvider.clearError(),
                                  iconSize: 20,
                                ),
                              ],
                            ),
                          );
                        }
                        return const SizedBox.shrink();
                      },
                    ),

                    // Email Field
                    TextFormField(
                      controller: _emailController,
                      focusNode: _emailFocus,
                      keyboardType: TextInputType.emailAddress,
                      autocorrect: false,
                      textInputAction: TextInputAction.next,
                      decoration: InputDecoration(
                        labelText: l.loginEmailLabel,
                        prefixIcon: const Icon(Icons.email_outlined),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return l.loginEmailRequired;
                        }
                        if (!value.contains('@')) {
                          return l.loginEmailInvalid;
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),

                    // Password and OTP Fields with Consumer
                    Consumer<AuthProvider>(
                      builder: (context, authProvider, _) {
                        final showOtp = authProvider.showMfaInput;

                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            // Password Field
                            TextFormField(
                              controller: _passwordController,
                              focusNode: _passwordFocus,
                              obscureText: _obscurePassword,
                              textInputAction: showOtp
                                  ? TextInputAction.next
                                  : TextInputAction.done,
                              decoration: InputDecoration(
                                labelText: l.loginPasswordLabel,
                                prefixIcon: const Icon(Icons.lock_outlined),
                                suffixIcon: IconButton(
                                  icon: Icon(
                                    _obscurePassword
                                        ? Icons.visibility_outlined
                                        : Icons.visibility_off_outlined,
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      _obscurePassword = !_obscurePassword;
                                    });
                                  },
                                ),
                              ),
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return l.loginPasswordRequired;
                                }
                                return null;
                              },
                              onFieldSubmitted:
                                  showOtp ? null : (_) => _handleLogin(),
                            ),

                            // OTP Field (shown when MFA is required)
                            if (showOtp) ...[
                              const SizedBox(height: 16),
                              Container(
                                padding: const EdgeInsets.all(12),
                                decoration: BoxDecoration(
                                  color: colorScheme.primaryContainer
                                      .withValues(alpha: 0.3),
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: Row(
                                  children: [
                                    Icon(
                                      Icons.security,
                                      color: colorScheme.primary,
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: Text(
                                        l.loginMfaInfo,
                                        style: TextStyle(
                                            color: colorScheme.onSurface),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16),
                              TextFormField(
                                controller: _otpController,
                                keyboardType: TextInputType.number,
                                textInputAction: TextInputAction.done,
                                decoration: InputDecoration(
                                  labelText: l.loginMfaLabel,
                                  prefixIcon: const Icon(Icons.pin_outlined),
                                ),
                                validator: (value) {
                                  if (showOtp &&
                                      (value == null || value.isEmpty)) {
                                    return l.loginMfaCodeRequired;
                                  }
                                  return null;
                                },
                                onFieldSubmitted: (_) => _handleLogin(),
                              ),
                            ],
                          ],
                        );
                      },
                    ),

                    const SizedBox(height: 24),

                    // Login Button
                    Consumer<AuthProvider>(
                      builder: (context, authProvider, _) {
                        return SureButton(
                          label: l.loginSignIn,
                          size: SureButtonSize.lg,
                          fullWidth: true,
                          loading: authProvider.isLoading,
                          onPressed: _handleLogin,
                        );
                      },
                    ),

                    FutureBuilder<List<SsoProvider>?>(
                      future: _ssoProviders(
                          Provider.of<AuthProvider>(context, listen: false)),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState != ConnectionState.done) {
                          return const SizedBox.shrink();
                        }
                        // Servers without the providers endpoint only
                        // supported Google on mobile.
                        final providers = snapshot.data ?? _legacyProviders;
                        if (providers.isEmpty) return const SizedBox.shrink();

                        return Column(
                          children: [
                            const SizedBox(height: 16),
                            // Divider with "or"
                            Row(
                              children: [
                                Expanded(
                                    child: Divider(
                                        color: colorScheme.outlineVariant)),
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 16),
                                  child: Text(
                                    l.loginOrDivider,
                                    style: TextStyle(
                                        color: colorScheme.onSurfaceVariant),
                                  ),
                                ),
                                Expanded(
                                    child: Divider(
                                        color: colorScheme.outlineVariant)),
                              ],
                            ),
                            for (final provider in providers) ...[
                              const SizedBox(height: 16),
                              _SsoButton(provider: provider),
                            ],
                          ],
                        );
                      },
                    ),

                    const SizedBox(height: 24),

                    // Backend URL info
                    InkWell(
                      onTap: () => _openSettings(),
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: colorScheme.surfaceContainerHighest
                              .withValues(alpha: 0.3),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Column(
                          children: [
                            Text(
                              l.loginServerUrlHeading,
                              style:
                                  Theme.of(context).textTheme.bodySmall?.copyWith(
                                        color: colorScheme.onSurfaceVariant,
                                        fontWeight: FontWeight.bold,
                                      ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              ApiConfig.baseUrl,
                              style:
                                  Theme.of(context).textTheme.bodySmall?.copyWith(
                                        color: colorScheme.primary,
                                        fontFamily: 'monospace',
                                      ),
                              textAlign: TextAlign.center,
                            ),
                          ],
                        ),
                      ),
                    ),

                    const SizedBox(height: 12),

                    // API Key Login Button
                    Consumer<AuthProvider>(
                      builder: (context, authProvider, _) {
                        return SureButton(
                          label: l.loginApiKeyLoginButton,
                          variant: SureButtonVariant.ghost,
                          onPressed:
                              authProvider.isLoading ? null : _showApiKeyDialog,
                          leading:
                              const Icon(Icons.vpn_key_outlined, size: 18),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
              right: 8,
              top: 8,
              child: IconButton(
                icon: const Icon(Icons.settings_outlined),
                tooltip: l.loginBackendSettingsTooltip,
                onPressed: () => _openSettings(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// API-key login dialog. Owns its [TextEditingController] so it is disposed
/// with the dialog's State — never leaked (barrier/back dismissal) and never
/// disposed while the field is still mounted. Pops `true` on a successful
/// sign-in, `false` on a failed attempt, and `null` when dismissed.
@visibleForTesting
class ApiKeyLoginDialog extends StatefulWidget {
  const ApiKeyLoginDialog({super.key, this.controller});

  /// Test seam: a controller the dialog will adopt and dispose, so a test can
  /// assert disposal. Production passes none and the dialog creates its own.
  @visibleForTesting
  final TextEditingController? controller;

  @override
  State<ApiKeyLoginDialog> createState() => _ApiKeyLoginDialogState();
}

class _ApiKeyLoginDialogState extends State<ApiKeyLoginDialog> {
  late final TextEditingController _apiKeyController =
      widget.controller ?? TextEditingController();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _apiKeyController.addListener(_onTextChanged);
  }

  void _onTextChanged() => setState(() {});

  @override
  void dispose() {
    _apiKeyController.removeListener(_onTextChanged);
    _apiKeyController.dispose();
    super.dispose();
  }

  Future<void> _submit() async {
    final apiKey = _apiKeyController.text.trim();
    if (apiKey.isEmpty) return;

    setState(() => _isLoading = true);

    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final success = await authProvider.loginWithApiKey(apiKey: apiKey);

    if (!mounted) return;
    Navigator.of(context).pop(success);
  }

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context);
    return AlertDialog(
      title: Text(l.loginApiKeyDialogTitle),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            l.loginApiKeyDialogBody,
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: Theme.of(context).colorScheme.onSurfaceVariant,
                ),
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _apiKeyController,
            decoration: InputDecoration(
              labelText: l.loginApiKeyLabel,
              prefixIcon: const Icon(Icons.vpn_key_outlined),
            ),
            obscureText: true,
            maxLines: 1,
            enabled: !_isLoading,
            onSubmitted: (_) => _submit(),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
          child: Text(l.commonCancel),
        ),
        ElevatedButton(
          onPressed: _isLoading || _apiKeyController.text.trim().isEmpty ? null : _submit,
          child: _isLoading
              ? const SizedBox(
                  height: 20,
                  width: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : Text(l.loginApiKeySignIn),
        ),
      ],
    );
  }
}

class _SsoButton extends StatelessWidget {
  final SsoProvider provider;

  const _SsoButton({required this.provider});

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context);
    return Consumer<AuthProvider>(
      builder: (context, authProvider, _) {
        return SureButton(
          label: provider.isGoogle ? l.loginSignInWithGoogle : provider.label,
          variant: SureButtonVariant.outline,
          size: SureButtonSize.lg,
          fullWidth: true,
          leading: provider.isGoogle
              ? SvgPicture.asset(
                  'assets/images/google_g_logo.svg',
                  width: 18,
                  height: 18,
                )
              : const Icon(Icons.login, size: 18),
          onPressed: authProvider.isLoading
              ? null
              : () => authProvider.startSsoLogin(provider.name),
        );
      },
    );
  }
}