Files
sure/mobile/lib/services/auth_service.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

499 lines
15 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../models/auth_tokens.dart';
import '../models/user.dart';
import 'api_config.dart';
import 'log_service.dart';
class AuthService {
final FlutterSecureStorage _storage = const FlutterSecureStorage();
static const String _tokenKey = 'auth_tokens';
static const String _userKey = 'user_data';
static const String _apiKeyKey = 'api_key';
static const String _authModeKey = 'auth_mode';
Future<Map<String, dynamic>> login({
required String email,
required String password,
required Map<String, String> deviceInfo,
String? otpCode,
}) async {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/auth/login');
final body = {
'email': email,
'password': password,
'device': deviceInfo,
};
if (otpCode != null) {
body['otp_code'] = otpCode;
}
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode(body),
).timeout(const Duration(seconds: 30));
LogService.instance.debug('AuthService', 'Login response status: ${response.statusCode}');
LogService.instance.debug('AuthService', 'Login response body: ${response.body}');
final responseData = jsonDecode(response.body);
if (response.statusCode == 200) {
// Store tokens
final tokens = AuthTokens.fromJson(responseData);
await _saveTokens(tokens);
// Store user data - parse once and reuse
User? user;
if (responseData['user'] != null) {
user = User.fromJson(responseData['user']);
await _saveUser(user);
}
return {
'success': true,
'tokens': tokens,
'user': user,
};
} else if (response.statusCode == 401 && responseData['mfa_required'] == true) {
return {
'success': false,
'mfa_required': true,
'error': responseData['error'],
};
} else {
return {
'success': false,
'error': responseData['error'] ?? responseData['errors']?.join(', ') ?? 'Login failed',
};
}
} on SocketException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Login SocketException: $e\n$stackTrace');
return {
'success': false,
'error': 'Network unavailable',
};
} on TimeoutException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Login TimeoutException: $e\n$stackTrace');
return {
'success': false,
'error': 'Request timed out',
};
} on HttpException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Login HttpException: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} on FormatException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Login FormatException: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} on TypeError catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Login TypeError: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Login unexpected error: $e\n$stackTrace');
return {
'success': false,
'error': 'An unexpected error occurred',
};
}
}
Future<Map<String, dynamic>> signup({
required String email,
required String password,
required String firstName,
required String lastName,
required Map<String, String> deviceInfo,
String? inviteCode,
}) async {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/auth/signup');
final Map<String, Object> body = {
'user': {
'email': email,
'password': password,
'first_name': firstName,
'last_name': lastName,
},
'device': deviceInfo,
};
if (inviteCode != null) {
body['invite_code'] = inviteCode;
}
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode(body),
).timeout(const Duration(seconds: 30));
final responseData = jsonDecode(response.body);
if (response.statusCode == 201) {
// Store tokens
final tokens = AuthTokens.fromJson(responseData);
await _saveTokens(tokens);
// Store user data - parse once and reuse
User? user;
if (responseData['user'] != null) {
user = User.fromJson(responseData['user']);
await _saveUser(user);
}
return {
'success': true,
'tokens': tokens,
'user': user,
};
} else {
return {
'success': false,
'error': responseData['error'] ?? responseData['errors']?.join(', ') ?? 'Signup failed',
};
}
} on SocketException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Signup SocketException: $e\n$stackTrace');
return {
'success': false,
'error': 'Network unavailable',
};
} on TimeoutException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Signup TimeoutException: $e\n$stackTrace');
return {
'success': false,
'error': 'Request timed out',
};
} on HttpException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Signup HttpException: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} on FormatException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Signup FormatException: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} on TypeError catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Signup TypeError: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} catch (e, stackTrace) {
LogService.instance.error('AuthService', 'Signup unexpected error: $e\n$stackTrace');
return {
'success': false,
'error': 'An unexpected error occurred',
};
}
}
Future<Map<String, dynamic>> refreshToken({
required String refreshToken,
required Map<String, String> deviceInfo,
}) async {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/auth/refresh');
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode({
'refresh_token': refreshToken,
'device': deviceInfo,
}),
).timeout(const Duration(seconds: 30));
final responseData = jsonDecode(response.body);
if (response.statusCode == 200) {
final tokens = AuthTokens.fromJson(responseData);
await _saveTokens(tokens);
return {
'success': true,
'tokens': tokens,
};
} else {
return {
'success': false,
'error': responseData['error'] ?? 'Token refresh failed',
};
}
} on SocketException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'RefreshToken SocketException: $e\n$stackTrace');
return {
'success': false,
'error': 'Network unavailable',
};
} on TimeoutException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'RefreshToken TimeoutException: $e\n$stackTrace');
return {
'success': false,
'error': 'Request timed out',
};
} on HttpException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'RefreshToken HttpException: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} on FormatException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'RefreshToken FormatException: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} on TypeError catch (e, stackTrace) {
LogService.instance.error('AuthService', 'RefreshToken TypeError: $e\n$stackTrace');
return {
'success': false,
'error': 'Invalid response from server',
};
} catch (e, stackTrace) {
LogService.instance.error('AuthService', 'RefreshToken unexpected error: $e\n$stackTrace');
return {
'success': false,
'error': 'An unexpected error occurred',
};
}
}
Future<Map<String, dynamic>> loginWithApiKey({
required String apiKey,
}) async {
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/accounts');
final response = await http.get(
url,
headers: {
'X-Api-Key': apiKey,
'Accept': 'application/json',
},
).timeout(const Duration(seconds: 30));
LogService.instance.debug('AuthService', 'API key login response status: ${response.statusCode}');
if (response.statusCode == 200) {
await _saveApiKey(apiKey);
return {
'success': true,
};
} else if (response.statusCode == 401) {
return {
'success': false,
'error': 'Invalid API key',
};
} else {
return {
'success': false,
'error': 'Login failed (status ${response.statusCode})',
};
}
} on SocketException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'API key login SocketException: $e\n$stackTrace');
return {
'success': false,
'error': 'Network unavailable',
};
} on TimeoutException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'API key login TimeoutException: $e\n$stackTrace');
return {
'success': false,
'error': 'Request timed out',
};
} catch (e, stackTrace) {
LogService.instance.error('AuthService', 'API key login unexpected error: $e\n$stackTrace');
return {
'success': false,
'error': 'An unexpected error occurred',
};
}
}
String buildSsoUrl({
required String provider,
required Map<String, String> deviceInfo,
}) {
final params = {
'device_id': deviceInfo['device_id']!,
'device_name': deviceInfo['device_name']!,
'device_type': deviceInfo['device_type']!,
'os_version': deviceInfo['os_version']!,
'app_version': deviceInfo['app_version']!,
};
final uri = Uri.parse('${ApiConfig.baseUrl}/auth/mobile/$provider')
.replace(queryParameters: params);
return uri.toString();
}
Future<Map<String, dynamic>> handleSsoCallback(Uri uri) async {
final params = uri.queryParameters;
if (params.containsKey('error')) {
return {
'success': false,
'error': params['message'] ?? params['error'] ?? 'SSO login failed',
};
}
final code = params['code'];
if (code == null || code.isEmpty) {
return {
'success': false,
'error': 'Invalid SSO callback response',
};
}
// Exchange authorization code for tokens via secure POST
try {
final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/auth/sso_exchange');
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode({'code': code}),
).timeout(const Duration(seconds: 30));
if (response.statusCode != 200) {
final errorData = jsonDecode(response.body);
return {
'success': false,
'error': errorData['message'] ?? 'Token exchange failed',
};
}
final data = jsonDecode(response.body);
final tokens = AuthTokens.fromJson({
'access_token': data['access_token'],
'refresh_token': data['refresh_token'],
'token_type': data['token_type'] ?? 'Bearer',
'expires_in': data['expires_in'] ?? 0,
'created_at': data['created_at'] ?? 0,
});
await _saveTokens(tokens);
final user = User.fromJson(data['user']);
await _saveUser(user);
return {
'success': true,
'tokens': tokens,
'user': user,
};
} on SocketException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'SSO exchange SocketException: $e\n$stackTrace');
return {
'success': false,
'error': 'Network unavailable',
};
} on TimeoutException catch (e, stackTrace) {
LogService.instance.error('AuthService', 'SSO exchange TimeoutException: $e\n$stackTrace');
return {
'success': false,
'error': 'Request timed out',
};
} catch (e, stackTrace) {
LogService.instance.error('AuthService', 'SSO exchange unexpected error: $e\n$stackTrace');
return {
'success': false,
'error': 'Failed to exchange authorization code',
};
}
}
Future<void> logout() async {
await _storage.delete(key: _tokenKey);
await _storage.delete(key: _userKey);
await _storage.delete(key: _apiKeyKey);
await _storage.delete(key: _authModeKey);
}
Future<AuthTokens?> getStoredTokens() async {
final tokensJson = await _storage.read(key: _tokenKey);
if (tokensJson == null) return null;
try {
return AuthTokens.fromJson(jsonDecode(tokensJson));
} catch (e) {
return null;
}
}
Future<User?> getStoredUser() async {
final userJson = await _storage.read(key: _userKey);
if (userJson == null) return null;
try {
return User.fromJson(jsonDecode(userJson));
} catch (e) {
return null;
}
}
Future<void> _saveTokens(AuthTokens tokens) async {
await _storage.write(
key: _tokenKey,
value: jsonEncode(tokens.toJson()),
);
}
Future<void> _saveUser(User user) async {
await _storage.write(
key: _userKey,
value: jsonEncode({
'id': user.id,
'email': user.email,
'first_name': user.firstName,
'last_name': user.lastName,
}),
);
}
Future<void> _saveApiKey(String apiKey) async {
await _storage.write(key: _apiKeyKey, value: apiKey);
await _storage.write(key: _authModeKey, value: 'api_key');
}
Future<String?> getStoredApiKey() async {
return await _storage.read(key: _apiKeyKey);
}
Future<String?> getStoredAuthMode() async {
return await _storage.read(key: _authModeKey);
}
}