Files
sure/mobile/lib/main.dart
Dream ca3abd5d8b Add Google Sign-In (SSO) support to Flutter mobile app (#860)
* Add mobile SSO support to sessions controller

Add /auth/mobile/:provider route and mobile_sso_start action that
captures device params in session and renders an auto-submitting POST
form to OmniAuth (required by omniauth-rails_csrf_protection).

Modify openid_connect callback to detect mobile_sso session, issue
Doorkeeper tokens via MobileDevice, and redirect to sureapp://oauth/callback
with tokens. Handles MFA users and unlinked accounts with error redirects.

Validates provider name against configured SSO providers and device info
before proceeding.

* Add SSO auth flow to Flutter service and provider

Add buildSsoUrl() and handleSsoCallback() to AuthService for
constructing the mobile SSO URL and parsing tokens from the deep
link callback.

Add startSsoLogin() and handleSsoCallback() to AuthProvider for
launching browser-based SSO and processing the redirect.

* Register deep link listener for SSO callback

Listen for sureapp://oauth/* deep links via app_links package,
handling both cold start (getInitialLink) and warm (uriLinkStream)
scenarios. Routes callbacks to AuthProvider.handleSsoCallback().

* Add Google Sign-In button to Flutter login screen

Add "or" divider and outlined Google Sign-In button that triggers
browser-based SSO via startSsoLogin('google_oauth2').

Add app_links and url_launcher dependencies to pubspec.yaml.

* Fix mobile SSO failure handling to redirect back to app

When OmniAuth fails during mobile SSO flow, redirect to
sureapp://oauth/callback with the error instead of the web login page.
Cleans up mobile_sso session data on failure.

* Address PR review feedback for mobile SSO flow

- Use strong params for device info in mobile_sso_start
- Guard against nil session data in handle_mobile_sso_callback
- Add error handling for AppLinks initialization and stream
- Handle launchUrl false return value in SSO login
- Use user-friendly error messages instead of exposing exceptions
- Reject empty token strings in SSO callback validation

* Consolidate mobile device token logic into MobileDevice model

Extract duplicated device upsert and token issuance code from
AuthController and SessionsController into MobileDevice. Add
CALLBACK_URL constant and URL builder helpers to eliminate repeated
deep-link strings. Add mobile SSO integration tests covering the
full flow, MFA rejection, unlinked accounts, and failure handling.

* Fix CI: resolve Brakeman redirect warnings and rubocop empty line

Move mobile SSO redirect into a private controller method with an
inline string literal so Brakeman can statically verify the target.
Remove unused URL builder helpers from MobileDevice. Fix extra empty
line at end of AuthController class body.

* Use authorization code exchange for mobile SSO and add signup error handling

Replace passing plaintext tokens in mobile SSO redirect URLs with a
one-time authorization code pattern. Tokens are now stored server-side
in Rails.cache (5min TTL) and exchanged via a secure POST to
/api/v1/auth/sso_exchange. Also wraps device/token creation in the
signup action with error handling and sanitizes device error messages.

* Add error handling for login device registration and blank SSO code guard

* Address PR #860 review: fix SSO race condition, add OpenAPI spec, and cleanup

- Fix race condition in sso_exchange by checking Rails.cache.delete return
  value to ensure only one request can consume an authorization code
- Use strong parameters (params.require) for sso_exchange code param
- Move inline HTML from mobile_sso_start to a proper view template
- Clear stale session[:mobile_sso] flag on web login paths to prevent
  abandoned mobile flows from hijacking subsequent web SSO logins
- Add OpenAPI/rswag spec for all auth API endpoints

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix mobile SSO test to match authorization code exchange pattern

The test was asserting tokens directly in the callback URL, but the code
uses an authorization code exchange pattern. Updated to exchange the code
via the sso_exchange API endpoint. Also swaps in a MemoryStore for this
test since the test environment uses null_store which discards writes.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Refactor mobile OAuth to use single shared application

Replace per-device Doorkeeper::Application creation with a shared
"Sure Mobile" OAuth app. Device tracking uses mobile_device_id on
access tokens instead of oauth_application_id on mobile_devices.

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 00:45:11 +01:00

253 lines
7.3 KiB
Dart

import 'dart:async';
import 'package:app_links/app_links.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'providers/auth_provider.dart';
import 'providers/accounts_provider.dart';
import 'providers/transactions_provider.dart';
import 'providers/chat_provider.dart';
import 'screens/backend_config_screen.dart';
import 'screens/login_screen.dart';
import 'screens/main_navigation_screen.dart';
import 'services/api_config.dart';
import 'services/connectivity_service.dart';
import 'services/log_service.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ApiConfig.initialize();
// Add initial log entry
LogService.instance.info('App', 'Sure Finance app starting...');
runApp(const SureApp());
}
class SureApp extends StatelessWidget {
const SureApp({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => LogService.instance),
ChangeNotifierProvider(create: (_) => ConnectivityService()),
ChangeNotifierProvider(create: (_) => AuthProvider()),
ChangeNotifierProvider(create: (_) => ChatProvider()),
ChangeNotifierProxyProvider<ConnectivityService, AccountsProvider>(
create: (_) => AccountsProvider(),
update: (_, connectivityService, accountsProvider) {
if (accountsProvider == null) {
final provider = AccountsProvider();
provider.setConnectivityService(connectivityService);
return provider;
} else {
accountsProvider.setConnectivityService(connectivityService);
return accountsProvider;
}
},
),
ChangeNotifierProxyProvider<ConnectivityService, TransactionsProvider>(
create: (_) => TransactionsProvider(),
update: (_, connectivityService, transactionsProvider) {
if (transactionsProvider == null) {
final provider = TransactionsProvider();
provider.setConnectivityService(connectivityService);
return provider;
} else {
transactionsProvider.setConnectivityService(connectivityService);
return transactionsProvider;
}
},
),
],
child: MaterialApp(
title: 'Sure Finance',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF6366F1),
brightness: Brightness.light,
),
useMaterial3: true,
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
),
cardTheme: CardThemeData(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
filled: true,
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
minimumSize: const Size(double.infinity, 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF6366F1),
brightness: Brightness.dark,
),
useMaterial3: true,
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
),
cardTheme: CardThemeData(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
filled: true,
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
minimumSize: const Size(double.infinity, 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
themeMode: ThemeMode.system,
routes: {
'/config': (context) => const BackendConfigScreen(),
'/login': (context) => const LoginScreen(),
'/home': (context) => const MainNavigationScreen(),
},
home: const AppWrapper(),
),
);
}
}
class AppWrapper extends StatefulWidget {
const AppWrapper({super.key});
@override
State<AppWrapper> createState() => _AppWrapperState();
}
class _AppWrapperState extends State<AppWrapper> {
bool _isCheckingConfig = true;
bool _hasBackendUrl = false;
late final AppLinks _appLinks;
StreamSubscription<Uri>? _linkSubscription;
@override
void initState() {
super.initState();
_checkBackendConfig();
_initDeepLinks();
}
@override
void dispose() {
_linkSubscription?.cancel();
super.dispose();
}
void _initDeepLinks() {
_appLinks = AppLinks();
// Handle deep link that launched the app (cold start)
_appLinks.getInitialLink().then((uri) {
if (uri != null) _handleDeepLink(uri);
}).catchError((e, stackTrace) {
LogService.instance.error('DeepLinks', 'Initial link error: $e\n$stackTrace');
});
// Listen for deep links while app is running
_linkSubscription = _appLinks.uriLinkStream.listen(
(uri) => _handleDeepLink(uri),
onError: (e, stackTrace) {
LogService.instance.error('DeepLinks', 'Link stream error: $e\n$stackTrace');
},
);
}
void _handleDeepLink(Uri uri) {
if (uri.scheme == 'sureapp' && uri.host == 'oauth') {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
authProvider.handleSsoCallback(uri);
}
}
Future<void> _checkBackendConfig() async {
final hasUrl = await ApiConfig.initialize();
if (mounted) {
setState(() {
_hasBackendUrl = hasUrl;
_isCheckingConfig = false;
});
}
}
void _onBackendConfigSaved() {
setState(() {
_hasBackendUrl = true;
});
}
void _goToBackendConfig() {
setState(() {
_hasBackendUrl = false;
});
}
@override
Widget build(BuildContext context) {
if (_isCheckingConfig) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
if (!_hasBackendUrl) {
return BackendConfigScreen(
onConfigSaved: _onBackendConfigSaved,
);
}
return Consumer<AuthProvider>(
builder: (context, authProvider, _) {
// Only show loading spinner during initial auth check
if (authProvider.isInitializing) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
if (authProvider.isAuthenticated) {
return const MainNavigationScreen();
}
return LoginScreen(
onGoToSettings: _goToBackendConfig,
);
},
);
}
}