mirror of
https://github.com/we-promise/sure.git
synced 2026-04-07 14:31:25 +00:00
* Add Google SSO onboarding flow for Flutter mobile app Previously, mobile users attempting Google SSO without a linked OIDC identity received an error telling them to link from the web app first. This adds the same account linking/creation flow that exists on the PWA. Backend changes: - sessions_controller: Cache pending OIDC auth with a linking code and redirect back to the app instead of returning an error - api/v1/auth_controller: Add sso_link endpoint to link Google identity to an existing account via email/password, and sso_create_account endpoint to create a new SSO-only account (respects JIT config) - routes: Add POST auth/sso_link and auth/sso_create_account Flutter changes: - auth_service: Detect account_not_linked callback status, add ssoLink and ssoCreateAccount API methods - auth_provider: Track SSO onboarding state, expose linking/creation methods and cancelSsoOnboarding - sso_onboarding_screen: New screen with tabs to link existing account or create new account, pre-filled with Google profile data - main.dart: Show SsoOnboardingScreen when ssoOnboardingPending is true https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Fix broken SSO tests: use MemoryStore cache and correct redirect param - Sessions test: check `status` param instead of `error` since handle_mobile_sso_onboarding sends linking info with status key - API auth tests: swap null_store for MemoryStore so cache-based linking code validation works in test environment https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Delay linking-code consumption until SSO link/create succeeds Split validate_and_consume_linking_code into validate_linking_code (read-only) and consume_linking_code! (delete). The code is now only consumed after password verification (sso_link) or successful user save (sso_create_account), so recoverable errors no longer burn the one-time code and force a full Google SSO roundtrip. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Make linking-code consumption atomic to prevent race conditions Move consume_linking_code! (backed by Rails.cache.delete) to after recoverable checks (bad password, policy rejection) but before side-effecting operations (identity/user creation). Only the first caller to delete the cache key gets true, so concurrent requests with the same code cannot both succeed. - sso_link: consume after password auth, before OidcIdentity creation - sso_create_account: consume after allow_account_creation check, before User creation - Bad password still preserves the code for retry - Add single-use regression tests for both endpoints https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Add missing sso_create_account test coverage for blank code and validation failure - Test blank linking_code returns 400 (bad_request) with proper error - Test duplicate email triggers user.save failure → 422 with validation errors https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Verify cache payload in mobile SSO onboarding test with MemoryStore The test environment uses :null_store which silently discards cache writes, so handle_mobile_sso_onboarding's Rails.cache.write was never verified. Swap in a MemoryStore for this test and assert the full cached payload (provider, uid, email, name, device_info, allow_account_creation) at the linking_code key from the redirect URL. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Add rswag/OpenAPI specs for sso_link and sso_create_account endpoints POST /api/v1/auth/sso_link: documents linking_code + email/password params, 200 (tokens), 400 (missing code), 401 (invalid creds/expired). POST /api/v1/auth/sso_create_account: documents linking_code + optional first_name/last_name params, 200 (tokens), 400 (missing code), 401 (expired code), 403 (creation disabled), 422 (validation errors). Note: RAILS_ENV=test bundle exec rake rswag:specs:swaggerize should be run to regenerate docs/api/openapi.yaml once the runtime environment matches the Gemfile Ruby version. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Preserve OIDC issuer through mobile SSO onboarding flow handle_mobile_sso_onboarding now caches the issuer from auth.extra.raw_info.iss so it survives the linking-code round trip. build_omniauth_hash populates extra.raw_info.iss from the cached issuer so OidcIdentity.create_from_omniauth stores it correctly. Previously the issuer was always nil for mobile SSO-created identities because build_omniauth_hash passed an empty raw_info OpenStruct. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Block MFA users from bypassing second factor via sso_link sso_link authenticated with email/password but never checked user.otp_required?, allowing MFA users to obtain tokens without a second factor. The mobile SSO callback already rejects MFA users with "mfa_not_supported"; apply the same guard in sso_link before consuming the linking code or creating an identity. Returns 401 with mfa_required: true, consistent with the login action's MFA response shape. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Fix NoMethodError in SSO link MFA test Replace non-existent User.generate_otp_secret class method with ROTP::Base32.random(32), matching the pattern used in User#setup_mfa!. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c * Assert linking code survives rejected SSO create account Add cache persistence assertion to "should reject SSO create account when not allowed" test, verifying the linking code is not consumed on the 403 path. This mirrors the pattern used in the invalid-password sso_link test. The other rejection tests (expired/missing linking code) don't have a valid cached code to check, so no assertion is needed there. https://claude.ai/code/session_011ag1qSfriUg6j7TqFgbS5c --------- Co-authored-by: Claude <noreply@anthropic.com>
270 lines
7.7 KiB
Dart
270 lines
7.7 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 'screens/sso_onboarding_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 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 Finances',
|
|
debugShowCheckedModeBanner: false,
|
|
theme: ThemeData(
|
|
fontFamily: 'Geist',
|
|
fontFamilyFallback: const [
|
|
'Inter',
|
|
'Arial',
|
|
'sans-serif',
|
|
],
|
|
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(
|
|
fontFamily: 'Geist',
|
|
fontFamilyFallback: const [
|
|
'Inter',
|
|
'Arial',
|
|
'sans-serif',
|
|
],
|
|
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();
|
|
}
|
|
|
|
if (authProvider.ssoOnboardingPending) {
|
|
return const SsoOnboardingScreen();
|
|
}
|
|
|
|
return LoginScreen(
|
|
onGoToSettings: _goToBackendConfig,
|
|
);
|
|
},
|
|
);
|
|
}
|
|
}
|