Files
sure/mobile/lib/providers/auth_provider.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

329 lines
9.2 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/user.dart';
import '../models/auth_tokens.dart';
import '../services/auth_service.dart';
import '../services/device_service.dart';
import '../services/api_config.dart';
import '../services/log_service.dart';
class AuthProvider with ChangeNotifier {
final AuthService _authService = AuthService();
final DeviceService _deviceService = DeviceService();
User? _user;
AuthTokens? _tokens;
String? _apiKey;
bool _isApiKeyAuth = false;
bool _isLoading = true;
bool _isInitializing = true; // Track initial auth check separately
String? _errorMessage;
bool _mfaRequired = false;
bool _showMfaInput = false; // Track if we should show MFA input field
User? get user => _user;
AuthTokens? get tokens => _tokens;
bool get isLoading => _isLoading;
bool get isInitializing => _isInitializing; // Expose initialization state
bool get isApiKeyAuth => _isApiKeyAuth;
bool get isAuthenticated =>
(_isApiKeyAuth && _apiKey != null) ||
(_tokens != null && !_tokens!.isExpired);
String? get errorMessage => _errorMessage;
bool get mfaRequired => _mfaRequired;
bool get showMfaInput => _showMfaInput; // Expose MFA input state
AuthProvider() {
_loadStoredAuth();
}
Future<void> _loadStoredAuth() async {
_isLoading = true;
_isInitializing = true;
notifyListeners();
try {
final authMode = await _authService.getStoredAuthMode();
if (authMode == 'api_key') {
_apiKey = await _authService.getStoredApiKey();
if (_apiKey != null) {
_isApiKeyAuth = true;
ApiConfig.setApiKeyAuth(_apiKey!);
}
} else {
_tokens = await _authService.getStoredTokens();
_user = await _authService.getStoredUser();
// If tokens exist but are expired, try to refresh
if (_tokens != null && _tokens!.isExpired) {
await _refreshToken();
}
}
} catch (e) {
_tokens = null;
_user = null;
_apiKey = null;
_isApiKeyAuth = false;
}
_isLoading = false;
_isInitializing = false;
notifyListeners();
}
Future<bool> login({
required String email,
required String password,
String? otpCode,
}) async {
_errorMessage = null;
_mfaRequired = false;
_isLoading = true;
// Don't reset _showMfaInput if we're submitting OTP code
if (otpCode == null) {
_showMfaInput = false;
}
notifyListeners();
try {
final deviceInfo = await _deviceService.getDeviceInfo();
final result = await _authService.login(
email: email,
password: password,
deviceInfo: deviceInfo,
otpCode: otpCode,
);
LogService.instance.debug('AuthProvider', 'Login result: $result');
if (result['success'] == true) {
_tokens = result['tokens'] as AuthTokens?;
_user = result['user'] as User?;
_mfaRequired = false;
_showMfaInput = false; // Reset on successful login
_isLoading = false;
notifyListeners();
return true;
} else {
if (result['mfa_required'] == true) {
_mfaRequired = true;
_showMfaInput = true; // Show MFA input field
LogService.instance.debug('AuthProvider', 'MFA required! Setting _showMfaInput to true');
// If user already submitted an OTP code, this is likely an invalid OTP error
// Show the error message so user knows the code was wrong
if (otpCode != null && otpCode.isNotEmpty) {
// Backend returns "Two-factor authentication required" for both cases
// Replace with clearer message when OTP was actually submitted
_errorMessage = 'Invalid authentication code. Please try again.';
} else {
// First time requesting MFA - don't show error message, it's a normal flow
_errorMessage = null;
}
} else {
_errorMessage = result['error'] as String?;
// If user submitted an OTP (is in MFA flow) but got error, keep MFA input visible
if (otpCode != null) {
_showMfaInput = true;
}
}
_isLoading = false;
notifyListeners();
return false;
}
} catch (e) {
_errorMessage = 'Connection error: ${e.toString()}';
_isLoading = false;
notifyListeners();
return false;
}
}
Future<bool> loginWithApiKey({
required String apiKey,
}) async {
_errorMessage = null;
_isLoading = true;
notifyListeners();
try {
final result = await _authService.loginWithApiKey(apiKey: apiKey);
LogService.instance.debug('AuthProvider', 'API key login result: $result');
if (result['success'] == true) {
_apiKey = apiKey;
_isApiKeyAuth = true;
ApiConfig.setApiKeyAuth(apiKey);
_isLoading = false;
notifyListeners();
return true;
} else {
_errorMessage = result['error'] as String?;
_isLoading = false;
notifyListeners();
return false;
}
} catch (e, stackTrace) {
LogService.instance.error('AuthProvider', 'API key login error: $e\n$stackTrace');
_errorMessage = 'Unable to connect. Please check your network and try again.';
_isLoading = false;
notifyListeners();
return false;
}
}
Future<bool> signup({
required String email,
required String password,
required String firstName,
required String lastName,
String? inviteCode,
}) async {
_errorMessage = null;
_isLoading = true;
notifyListeners();
try {
final deviceInfo = await _deviceService.getDeviceInfo();
final result = await _authService.signup(
email: email,
password: password,
firstName: firstName,
lastName: lastName,
deviceInfo: deviceInfo,
inviteCode: inviteCode,
);
if (result['success'] == true) {
_tokens = result['tokens'] as AuthTokens?;
_user = result['user'] as User?;
_isLoading = false;
notifyListeners();
return true;
} else {
_errorMessage = result['error'] as String?;
_isLoading = false;
notifyListeners();
return false;
}
} catch (e) {
_errorMessage = 'Connection error: ${e.toString()}';
_isLoading = false;
notifyListeners();
return false;
}
}
Future<void> startSsoLogin(String provider) async {
_errorMessage = null;
_isLoading = true;
notifyListeners();
try {
final deviceInfo = await _deviceService.getDeviceInfo();
final ssoUrl = _authService.buildSsoUrl(
provider: provider,
deviceInfo: deviceInfo,
);
final launched = await launchUrl(Uri.parse(ssoUrl), mode: LaunchMode.externalApplication);
if (!launched) {
_errorMessage = 'Unable to open browser for sign-in.';
}
} catch (e, stackTrace) {
LogService.instance.error('AuthProvider', 'SSO launch error: $e\n$stackTrace');
_errorMessage = 'Unable to start sign-in. Please try again.';
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<bool> handleSsoCallback(Uri uri) async {
_errorMessage = null;
_isLoading = true;
notifyListeners();
try {
final result = await _authService.handleSsoCallback(uri);
if (result['success'] == true) {
_tokens = result['tokens'] as AuthTokens?;
_user = result['user'] as User?;
_isLoading = false;
notifyListeners();
return true;
} else {
_errorMessage = result['error'] as String?;
_isLoading = false;
notifyListeners();
return false;
}
} catch (e, stackTrace) {
LogService.instance.error('AuthProvider', 'SSO callback error: $e\n$stackTrace');
_errorMessage = 'Sign-in failed. Please try again.';
_isLoading = false;
notifyListeners();
return false;
}
}
Future<void> logout() async {
await _authService.logout();
_tokens = null;
_user = null;
_apiKey = null;
_isApiKeyAuth = false;
_errorMessage = null;
_mfaRequired = false;
ApiConfig.clearApiKeyAuth();
notifyListeners();
}
Future<bool> _refreshToken() async {
if (_tokens == null) return false;
try {
final deviceInfo = await _deviceService.getDeviceInfo();
final result = await _authService.refreshToken(
refreshToken: _tokens!.refreshToken,
deviceInfo: deviceInfo,
);
if (result['success'] == true) {
_tokens = result['tokens'] as AuthTokens?;
return true;
} else {
// Token refresh failed, clear auth state
await logout();
return false;
}
} catch (e) {
await logout();
return false;
}
}
Future<String?> getValidAccessToken() async {
if (_isApiKeyAuth && _apiKey != null) {
return _apiKey;
}
if (_tokens == null) return null;
if (_tokens!.isExpired) {
final refreshed = await _refreshToken();
if (!refreshed) return null;
}
return _tokens?.accessToken;
}
void clearError() {
_errorMessage = null;
notifyListeners();
}
}