mirror of
https://github.com/we-promise/sure.git
synced 2026-04-19 03:54:08 +00:00
* 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>
456 lines
17 KiB
Dart
456 lines
17 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:provider/provider.dart';
|
|
import '../providers/auth_provider.dart';
|
|
import '../services/api_config.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>();
|
|
final _emailController = TextEditingController();
|
|
final _passwordController = TextEditingController();
|
|
final _otpController = TextEditingController();
|
|
bool _obscurePassword = true;
|
|
|
|
@override
|
|
void dispose() {
|
|
_emailController.dispose();
|
|
_passwordController.dispose();
|
|
_otpController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
void _showApiKeyDialog() {
|
|
final apiKeyController = TextEditingController();
|
|
final outerContext = context;
|
|
bool isLoading = false;
|
|
|
|
showDialog(
|
|
context: context,
|
|
builder: (dialogContext) {
|
|
return StatefulBuilder(
|
|
builder: (_, setDialogState) {
|
|
return AlertDialog(
|
|
title: const Text('API Key Login'),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(
|
|
'Enter your API key to sign in.',
|
|
style: Theme.of(outerContext).textTheme.bodyMedium?.copyWith(
|
|
color: Theme.of(outerContext).colorScheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
TextField(
|
|
controller: apiKeyController,
|
|
decoration: const InputDecoration(
|
|
labelText: 'API Key',
|
|
prefixIcon: Icon(Icons.vpn_key_outlined),
|
|
),
|
|
obscureText: true,
|
|
maxLines: 1,
|
|
enabled: !isLoading,
|
|
),
|
|
],
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: isLoading
|
|
? null
|
|
: () {
|
|
apiKeyController.dispose();
|
|
Navigator.of(dialogContext).pop();
|
|
},
|
|
child: const Text('Cancel'),
|
|
),
|
|
ElevatedButton(
|
|
onPressed: isLoading
|
|
? null
|
|
: () async {
|
|
final apiKey = apiKeyController.text.trim();
|
|
if (apiKey.isEmpty) return;
|
|
|
|
setDialogState(() {
|
|
isLoading = true;
|
|
});
|
|
|
|
final authProvider = Provider.of<AuthProvider>(
|
|
outerContext,
|
|
listen: false,
|
|
);
|
|
final success = await authProvider.loginWithApiKey(
|
|
apiKey: apiKey,
|
|
);
|
|
|
|
if (!dialogContext.mounted) return;
|
|
|
|
final errorMsg = authProvider.errorMessage;
|
|
apiKeyController.dispose();
|
|
Navigator.of(dialogContext).pop();
|
|
|
|
if (!success && mounted) {
|
|
ScaffoldMessenger.of(outerContext).showSnackBar(
|
|
SnackBar(
|
|
content: Text(
|
|
errorMsg ?? 'Invalid API key',
|
|
),
|
|
backgroundColor:
|
|
Theme.of(outerContext).colorScheme.error,
|
|
),
|
|
);
|
|
}
|
|
},
|
|
child: isLoading
|
|
? const SizedBox(
|
|
height: 20,
|
|
width: 20,
|
|
child: CircularProgressIndicator(strokeWidth: 2),
|
|
)
|
|
: const Text('Sign In'),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
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;
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: const Text(''),
|
|
actions: [
|
|
IconButton(
|
|
icon: const Icon(Icons.settings_outlined),
|
|
tooltip: 'Backend Settings',
|
|
onPressed: widget.onGoToSettings,
|
|
),
|
|
],
|
|
),
|
|
body: SafeArea(
|
|
child: SingleChildScrollView(
|
|
padding: const EdgeInsets.all(24),
|
|
child: Form(
|
|
key: _formKey,
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
const SizedBox(height: 48),
|
|
// Logo/Title
|
|
Icon(
|
|
Icons.account_balance_wallet,
|
|
size: 80,
|
|
color: colorScheme.primary,
|
|
),
|
|
const SizedBox(height: 16),
|
|
Text(
|
|
'Sure Finance',
|
|
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
|
fontWeight: FontWeight.bold,
|
|
color: colorScheme.primary,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
'Sign in to manage your finances',
|
|
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
|
|
color: colorScheme.onSurfaceVariant,
|
|
),
|
|
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,
|
|
keyboardType: TextInputType.emailAddress,
|
|
autocorrect: false,
|
|
textInputAction: TextInputAction.next,
|
|
decoration: const InputDecoration(
|
|
labelText: 'Email',
|
|
prefixIcon: Icon(Icons.email_outlined),
|
|
),
|
|
validator: (value) {
|
|
if (value == null || value.isEmpty) {
|
|
return 'Please enter your email';
|
|
}
|
|
if (!value.contains('@')) {
|
|
return 'Please enter a valid email';
|
|
}
|
|
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,
|
|
obscureText: _obscurePassword,
|
|
textInputAction: showOtp
|
|
? TextInputAction.next
|
|
: TextInputAction.done,
|
|
decoration: InputDecoration(
|
|
labelText: 'Password',
|
|
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 'Please enter your password';
|
|
}
|
|
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(
|
|
'Two-factor authentication is enabled. Enter your code.',
|
|
style: TextStyle(color: colorScheme.onSurface),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
TextFormField(
|
|
controller: _otpController,
|
|
keyboardType: TextInputType.number,
|
|
textInputAction: TextInputAction.done,
|
|
decoration: const InputDecoration(
|
|
labelText: 'Authentication Code',
|
|
prefixIcon: Icon(Icons.pin_outlined),
|
|
),
|
|
validator: (value) {
|
|
if (showOtp && (value == null || value.isEmpty)) {
|
|
return 'Please enter your authentication code';
|
|
}
|
|
return null;
|
|
},
|
|
onFieldSubmitted: (_) => _handleLogin(),
|
|
),
|
|
],
|
|
],
|
|
);
|
|
},
|
|
),
|
|
|
|
const SizedBox(height: 24),
|
|
|
|
// Login Button
|
|
Consumer<AuthProvider>(
|
|
builder: (context, authProvider, _) {
|
|
return ElevatedButton(
|
|
onPressed: authProvider.isLoading ? null : _handleLogin,
|
|
child: authProvider.isLoading
|
|
? const SizedBox(
|
|
height: 20,
|
|
width: 20,
|
|
child: CircularProgressIndicator(strokeWidth: 2),
|
|
)
|
|
: const Text('Sign In'),
|
|
);
|
|
},
|
|
),
|
|
|
|
const SizedBox(height: 12),
|
|
|
|
// API Key Login Button
|
|
TextButton.icon(
|
|
onPressed: _showApiKeyDialog,
|
|
icon: const Icon(Icons.vpn_key_outlined, size: 18),
|
|
label: const Text('Via API Key Login'),
|
|
),
|
|
|
|
const SizedBox(height: 16),
|
|
|
|
// Divider with "or"
|
|
Row(
|
|
children: [
|
|
Expanded(child: Divider(color: colorScheme.outlineVariant)),
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
child: Text(
|
|
'or',
|
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
|
),
|
|
),
|
|
Expanded(child: Divider(color: colorScheme.outlineVariant)),
|
|
],
|
|
),
|
|
|
|
const SizedBox(height: 16),
|
|
|
|
// Google Sign-In button
|
|
Consumer<AuthProvider>(
|
|
builder: (context, authProvider, _) {
|
|
return OutlinedButton.icon(
|
|
onPressed: authProvider.isLoading
|
|
? null
|
|
: () => authProvider.startSsoLogin('google_oauth2'),
|
|
icon: const Icon(Icons.g_mobiledata, size: 24),
|
|
label: const Text('Sign in with Google'),
|
|
style: OutlinedButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 50),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
|
|
const SizedBox(height: 24),
|
|
|
|
// Backend URL info
|
|
Container(
|
|
padding: const EdgeInsets.all(12),
|
|
decoration: BoxDecoration(
|
|
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
|
|
borderRadius: BorderRadius.circular(8),
|
|
),
|
|
child: Column(
|
|
children: [
|
|
Text(
|
|
'Backend URL:',
|
|
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: 8),
|
|
Text(
|
|
'Connect to your Sure Finance server to manage your accounts.',
|
|
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
|
color: colorScheme.onSurfaceVariant,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|