Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Show configured SSO providers on mobile login (#4595)

Marvello Onid732a73ae1c2
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rb
index d58fc01a5d..82665ff3a5 100644
--- a/app/controllers/api/v1/auth_controller.rb
+++ b/app/controllers/api/v1/auth_controller.rb
@@ -143,6 +143,29 @@ module Api
end
end
+ # Lists the providers GET /auth/mobile/:provider accepts, so clients can
+ # render one button per provider. Only display fields are exposed; the
+ # provider config also carries client secrets. Labels fall back the same
+ # way as the web sign-in page.
+ def sso_providers
+ providers = Rails.configuration.x.auth.sso_providers.map do |provider|
+ name = provider[:name].to_s
+ strategy = provider[:strategy].to_s
+ id = provider[:id].to_s
+ default_label = if id == "google" || strategy == "google_oauth2"
+ I18n.t("sessions.new.google_auth_connect")
+ elsif id.present?
+ I18n.t("sessions.new.#{id}", default: name.titleize)
+ else
+ name.titleize
+ end
+
+ { name: name, strategy: strategy, label: provider[:label].presence || default_label }
+ end
+
+ render json: { providers: providers }
+ end
+
def sso_exchange
code = sso_exchange_params
diff --git a/config/routes.rb b/config/routes.rb
index c94812ac58..0281b5fbfc 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -769,6 +769,7 @@ Rails.application.routes.draw do
post "auth/signup", to: "auth#signup"
post "auth/login", to: "auth#login"
post "auth/refresh", to: "auth#refresh"
+ get "auth/sso_providers", to: "auth#sso_providers"
post "auth/sso_exchange", to: "auth#sso_exchange"
post "auth/sso_link", to: "auth#sso_link"
post "auth/sso_create_account", to: "auth#sso_create_account"
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 12dd92ae50..303c6b3825 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -5008,6 +5008,42 @@ paths:
- password
- device
required: true
+ "/api/v1/auth/sso_providers":
+ get:
+ summary: List configured SSO providers
+ tags:
+ - Auth
+ description: Lists the SSO providers configured on this instance. Each name
+ can be used with GET /auth/mobile/{name} to start mobile SSO.
+ responses:
+ '200':
+ description: providers listed
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ providers:
+ type: array
+ items:
+ type: object
+ properties:
+ name:
+ type: string
+ description: Provider name used in /auth/mobile/{name}
+ strategy:
+ type: string
+ description: OmniAuth strategy, e.g. openid_connect, google_oauth2,
+ github, saml
+ label:
+ type: string
+ description: Button label
+ required:
+ - name
+ - strategy
+ - label
+ required:
+ - providers
"/api/v1/auth/sso_exchange":
post:
summary: Exchange mobile SSO authorization code for tokens
diff --git a/mobile/lib/models/sso_provider.dart b/mobile/lib/models/sso_provider.dart
new file mode 100644
index 0000000000..ed8592448f
--- /dev/null
+++ b/mobile/lib/models/sso_provider.dart
@@ -0,0 +1,24 @@
+class SsoProvider {
+ final String name;
+ final String strategy;
+ final String label;
+
+ const SsoProvider({
+ required this.name,
+ required this.strategy,
+ required this.label,
+ });
+
+ /// Google keeps its brand-compliant "Sign in with Google" button.
+ bool get isGoogle => strategy == 'google_oauth2';
+
+ factory SsoProvider.fromJson(Map<String, dynamic> json) {
+ final name = json['name'] as String;
+ final label = json['label'] as String? ?? '';
+ return SsoProvider(
+ name: name,
+ strategy: json['strategy'] as String? ?? '',
+ label: label.isEmpty ? name : label,
+ );
+ }
+}
diff --git a/mobile/lib/providers/auth_provider.dart b/mobile/lib/providers/auth_provider.dart
index d3d570d50b..706e39e3f4 100644
--- a/mobile/lib/providers/auth_provider.dart
+++ b/mobile/lib/providers/auth_provider.dart
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/user.dart';
import '../models/auth_tokens.dart';
+import '../models/sso_provider.dart';
import '../services/auth_service.dart';
import '../services/device_service.dart';
import '../services/api_config.dart';
@@ -322,6 +323,9 @@ class AuthProvider with ChangeNotifier {
}
}
+ Future<List<SsoProvider>?> fetchSsoProviders() =>
+ _authService.fetchSsoProviders();
+
Future<void> startSsoLogin(String provider) async {
_errorMessage = null;
_isLoading = true;
diff --git a/mobile/lib/screens/login_screen.dart b/mobile/lib/screens/login_screen.dart
index 61914dfcc6..95efba649a 100644
--- a/mobile/lib/screens/login_screen.dart
+++ b/mobile/lib/screens/login_screen.dart
@@ -3,6 +3,7 @@ import 'package:flutter/gestures.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_svg/flutter_svg.dart';
+import '../models/sso_provider.dart';
import '../providers/auth_provider.dart';
import '../services/api_config.dart';
import '../widgets/sure_button.dart';
@@ -15,20 +16,6 @@ class LoginScreen extends StatefulWidget {
const LoginScreen({super.key, this.onGoToSettings});
- void _openSettings(BuildContext context) {
- if (onGoToSettings != null) {
- onGoToSettings!();
- return;
- }
- Navigator.of(context).push(
- MaterialPageRoute<void>(
- builder: (routeContext) => BackendConfigScreen(
- onConfigSaved: () => Navigator.of(routeContext).pop(),
- ),
- ),
- );
- }
-
@override
State<LoginScreen> createState() => _LoginScreenState();
}
@@ -44,6 +31,11 @@ class _LoginScreenState extends State<LoginScreen> {
final _passwordFocus = FocusNode();
bool _obscurePassword = true;
late final TapGestureRecognizer _signUpTapRecognizer;
+ static const _legacyProviders = [
+ SsoProvider(name: 'google_oauth2', strategy: 'google_oauth2', label: ''),
+ ];
+ Future<List<SsoProvider>?>? _ssoProvidersFuture;
+ String? _ssoProvidersBaseUrl;
@override
void initState() {
@@ -55,6 +47,41 @@ class _LoginScreenState extends State<LoginScreen> {
_passwordFocus, _passwordController, _passwordPlaceholder));
}
+ Future<void> _openSettings() async {
+ if (widget.onGoToSettings != null) {
+ widget.onGoToSettings!();
+ return;
+ }
+ await Navigator.of(context).push(
+ MaterialPageRoute<void>(
+ builder: (routeContext) => BackendConfigScreen(
+ onConfigSaved: () => Navigator.of(routeContext).pop(),
+ ),
+ ),
+ );
+ // Rebuild so the backend URL card and SSO providers reflect the new server.
+ if (mounted) setState(() {});
+ }
+
+ /// Refetches when the backend URL changes (e.g. after editing settings).
+ Future<List<SsoProvider>?> _ssoProviders(AuthProvider authProvider) {
+ if (_ssoProvidersFuture == null ||
+ _ssoProvidersBaseUrl != ApiConfig.baseUrl) {
+ _ssoProvidersBaseUrl = ApiConfig.baseUrl;
+ // A failed fetch isn't cached, so the next rebuild (e.g. returning from
+ // settings) retries instead of keeping the Google fallback.
+ late final Future<List<SsoProvider>?> future;
+ future = authProvider.fetchSsoProviders().then((providers) {
+ if (providers == null && identical(_ssoProvidersFuture, future)) {
+ _ssoProvidersFuture = null;
+ }
+ return providers;
+ });
+ _ssoProvidersFuture = future;
+ }
+ return _ssoProvidersFuture!;
+ }
+
void _clearPlaceholderOnFocus(
FocusNode node, TextEditingController controller, String placeholder) {
if (node.hasFocus && controller.text == placeholder) {
@@ -347,45 +374,46 @@ class _LoginScreenState extends State<LoginScreen> {
},
),
- const SizedBox(height: 16),
-
- // Divider with "or"
- Row(
- children: [
- Expanded(
- child: Divider(color: colorScheme.outlineVariant)),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Text(
- l.loginOrDivider,
- style:
- TextStyle(color: colorScheme.onSurfaceVariant),
- ),
- ),
- Expanded(
- child: Divider(color: colorScheme.outlineVariant)),
- ],
- ),
-
- const SizedBox(height: 16),
+ FutureBuilder<List<SsoProvider>?>(
+ future: _ssoProviders(
+ Provider.of<AuthProvider>(context, listen: false)),
+ builder: (context, snapshot) {
+ if (snapshot.connectionState != ConnectionState.done) {
+ return const SizedBox.shrink();
+ }
+ // Servers without the providers endpoint only
+ // supported Google on mobile.
+ final providers = snapshot.data ?? _legacyProviders;
+ if (providers.isEmpty) return const SizedBox.shrink();
- // Google Sign-In button
- Consumer<AuthProvider>(
- builder: (context, authProvider, _) {
- return SureButton(
- label: l.loginSignInWithGoogle,
- variant: SureButtonVariant.outline,
- size: SureButtonSize.lg,
- fullWidth: true,
- leading: SvgPicture.asset(
- 'assets/images/google_g_logo.svg',
- width: 18,
- height: 18,
- ),
- onPressed: authProvider.isLoading
- ? null
- : () =>
- authProvider.startSsoLogin('google_oauth2'),
+ return Column(
+ children: [
+ const SizedBox(height: 16),
+ // Divider with "or"
+ Row(
+ children: [
+ Expanded(
+ child: Divider(
+ color: colorScheme.outlineVariant)),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16),
+ child: Text(
+ l.loginOrDivider,
+ style: TextStyle(
+ color: colorScheme.onSurfaceVariant),
+ ),
+ ),
+ Expanded(
+ child: Divider(
+ color: colorScheme.outlineVariant)),
+ ],
+ ),
+ for (final provider in providers) ...[
+ const SizedBox(height: 16),
+ _SsoButton(provider: provider),
+ ],
+ ],
);
},
),
@@ -394,7 +422,7 @@ class _LoginScreenState extends State<LoginScreen> {
// Backend URL info
InkWell(
- onTap: () => widget._openSettings(context),
+ onTap: () => _openSettings(),
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.all(12),
@@ -453,7 +481,7 @@ class _LoginScreenState extends State<LoginScreen> {
child: IconButton(
icon: const Icon(Icons.settings_outlined),
tooltip: l.loginBackendSettingsTooltip,
- onPressed: () => widget._openSettings(context),
+ onPressed: () => _openSettings(),
),
),
],
@@ -560,3 +588,34 @@ class _ApiKeyLoginDialogState extends State<ApiKeyLoginDialog> {
);
}
}
+
+class _SsoButton extends StatelessWidget {
+ final SsoProvider provider;
+
+ const _SsoButton({required this.provider});
+
+ @override
+ Widget build(BuildContext context) {
+ final l = AppLocalizations.of(context);
+ return Consumer<AuthProvider>(
+ builder: (context, authProvider, _) {
+ return SureButton(
+ label: provider.isGoogle ? l.loginSignInWithGoogle : provider.label,
+ variant: SureButtonVariant.outline,
+ size: SureButtonSize.lg,
+ fullWidth: true,
+ leading: provider.isGoogle
+ ? SvgPicture.asset(
+ 'assets/images/google_g_logo.svg',
+ width: 18,
+ height: 18,
+ )
+ : const Icon(Icons.login, size: 18),
+ onPressed: authProvider.isLoading
+ ? null
+ : () => authProvider.startSsoLogin(provider.name),
+ );
+ },
+ );
+ }
+}
diff --git a/mobile/lib/services/auth_service.dart b/mobile/lib/services/auth_service.dart
index a0dd4b4ae2..e5898b571e 100644
--- a/mobile/lib/services/auth_service.dart
+++ b/mobile/lib/services/auth_service.dart
@@ -4,6 +4,7 @@ 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/sso_provider.dart';
import '../models/user.dart';
import 'api_config.dart';
import 'log_service.dart';
@@ -400,6 +401,27 @@ class AuthService {
}
}
+ /// Returns the SSO providers configured on the server, or `null` when the
+ /// list can't be fetched (e.g. a server that predates the endpoint).
+ Future<List<SsoProvider>?> fetchSsoProviders() async {
+ try {
+ final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/auth/sso_providers');
+ final response = await http
+ .get(url, headers: ApiConfig.jsonHeaders())
+ .timeout(const Duration(seconds: 10));
+
+ if (response.statusCode != 200) return null;
+
+ final providers = jsonDecode(response.body)['providers'] as List;
+ return providers
+ .map((p) => SsoProvider.fromJson(p as Map<String, dynamic>))
+ .toList();
+ } catch (e) {
+ _logAuthException('SSO providers fetch', e);
+ return null;
+ }
+ }
+
String buildSsoUrl({
required String provider,
required Map<String, String> deviceInfo,
diff --git a/mobile/test/screens/login_screen_test.dart b/mobile/test/screens/login_screen_test.dart
new file mode 100644
index 0000000000..5c1d9714ff
--- /dev/null
+++ b/mobile/test/screens/login_screen_test.dart
@@ -0,0 +1,78 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_localizations/flutter_localizations.dart';
+import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:provider/provider.dart';
+import 'package:sure_mobile/l10n/app_localizations.dart';
+import 'package:sure_mobile/models/sso_provider.dart';
+import 'package:sure_mobile/providers/auth_provider.dart';
+import 'package:sure_mobile/screens/login_screen.dart';
+import 'package:sure_mobile/theme/sure_theme.dart';
+
+class _FakeAuthProvider extends AuthProvider {
+ final List<SsoProvider>? providers;
+
+ _FakeAuthProvider(this.providers);
+
+ @override
+ Future<List<SsoProvider>?> fetchSsoProviders() async => providers;
+}
+
+void main() {
+ setUp(() {
+ FlutterSecureStorage.setMockInitialValues({});
+ });
+
+ Future<void> pumpLogin(WidgetTester tester, List<SsoProvider>? providers) {
+ return tester.pumpWidget(
+ ChangeNotifierProvider<AuthProvider>(
+ create: (_) => _FakeAuthProvider(providers),
+ child: MaterialApp(
+ theme: SureTheme.light,
+ locale: const Locale('en'),
+ supportedLocales: AppLocalizations.supportedLocales,
+ localizationsDelegates: const [
+ AppLocalizations.delegate,
+ GlobalMaterialLocalizations.delegate,
+ GlobalWidgetsLocalizations.delegate,
+ GlobalCupertinoLocalizations.delegate,
+ ],
+ home: const LoginScreen(),
+ ),
+ ),
+ );
+ }
+
+ testWidgets('renders one button per configured SSO provider', (tester) async {
+ await pumpLogin(tester, const [
+ SsoProvider(
+ name: 'openid_connect',
+ strategy: 'openid_connect',
+ label: 'Authentik'),
+ SsoProvider(
+ name: 'google_oauth2',
+ strategy: 'google_oauth2',
+ label: 'Sign in with Google'),
+ ]);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Authentik'), findsOneWidget);
+ expect(find.text('Sign in with Google'), findsOneWidget);
+ });
+
+ testWidgets('hides SSO when no providers are configured', (tester) async {
+ await pumpLogin(tester, const []);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Sign in with Google'), findsNothing);
+ expect(find.text('or'), findsNothing);
+ });
+
+ testWidgets('falls back to Google when the provider list is unavailable',
+ (tester) async {
+ await pumpLogin(tester, null);
+ await tester.pumpAndSettle();
+
+ expect(find.text('Sign in with Google'), findsOneWidget);
+ });
+}
diff --git a/mobile/test/services/auth_service_test.dart b/mobile/test/services/auth_service_test.dart
index 6f3eec1aaa..0d179cbe12 100644
--- a/mobile/test/services/auth_service_test.dart
+++ b/mobile/test/services/auth_service_test.dart
@@ -59,6 +59,80 @@ void main() {
expect(await authService.getStoredTokens(), isNull);
expect(await authService.getStoredUser(), isNull);
});
+
+ test('fetchSsoProviders parses configured providers', () async {
+ final providers = await _withServer(
+ '/api/v1/auth/sso_providers',
+ 200,
+ {
+ 'providers': [
+ {
+ 'name': 'openid_connect',
+ 'strategy': 'openid_connect',
+ 'label': 'Authentik',
+ },
+ {
+ 'name': 'google_oauth2',
+ 'strategy': 'google_oauth2',
+ 'label': 'Google Oauth2',
+ },
+ ],
+ },
+ () => AuthService().fetchSsoProviders(),
+ );
+
+ expect(providers!.map((p) => p.name), ['openid_connect', 'google_oauth2']);
+ expect(providers.first.label, 'Authentik');
+ expect(providers.first.isGoogle, false);
+ expect(providers.last.isGoogle, true);
+ });
+
+ test('fetchSsoProviders returns null for a malformed response', () async {
+ final providers = await _withServer(
+ '/api/v1/auth/sso_providers',
+ 200,
+ {'unexpected': true},
+ () => AuthService().fetchSsoProviders(),
+ );
+
+ expect(providers, isNull);
+ });
+
+ test('fetchSsoProviders returns null when the endpoint is missing', () async {
+ final providers = await _withServer(
+ '/some/other/path',
+ 200,
+ {},
+ () => AuthService().fetchSsoProviders(),
+ );
+
+ expect(providers, isNull);
+ });
+}
+
+Future<T> _withServer<T>(
+ String path,
+ int statusCode,
+ Map<String, dynamic> responseBody,
+ Future<T> Function() body,
+) async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final subscription = server.listen((request) async {
+ final matched = request.uri.path == path;
+ request.response
+ ..statusCode = matched ? statusCode : 404
+ ..headers.contentType = ContentType.json
+ ..write(jsonEncode(matched ? responseBody : {'error': 'Not found'}));
+ await request.response.close();
+ });
+
+ try {
+ ApiConfig.setBaseUrl('http://${server.address.host}:${server.port}');
+ return await body();
+ } finally {
+ await subscription.cancel();
+ await server.close(force: true);
+ }
}
Future<Map<String, dynamic>> _loginWithResponse(
diff --git a/spec/requests/api/v1/auth_spec.rb b/spec/requests/api/v1/auth_spec.rb
index 0dd88ec2ca..f5dd5fe491 100644
--- a/spec/requests/api/v1/auth_spec.rb
+++ b/spec/requests/api/v1/auth_spec.rb
@@ -135,6 +135,34 @@ RSpec.describe 'API V1 Auth', type: :request do
end
end
+ path '/api/v1/auth/sso_providers' do
+ get 'List configured SSO providers' do
+ tags 'Auth'
+ produces 'application/json'
+ description 'Lists the SSO providers configured on this instance. Each name can be used with GET /auth/mobile/{name} to start mobile SSO.'
+
+ response '200', 'providers listed' do
+ schema type: :object,
+ properties: {
+ providers: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ name: { type: :string, description: 'Provider name used in /auth/mobile/{name}' },
+ strategy: { type: :string, description: 'OmniAuth strategy, e.g. openid_connect, google_oauth2, github, saml' },
+ label: { type: :string, description: 'Button label' }
+ },
+ required: %w[name strategy label]
+ }
+ }
+ },
+ required: %w[providers]
+ run_test!
+ end
+ end
+ end
+
path '/api/v1/auth/sso_exchange' do
post 'Exchange mobile SSO authorization code for tokens' do
tags 'Auth'
diff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rb
index 0b24efe4bd..c5200ee008 100644
--- a/test/controllers/api/v1/auth_controller_test.rb
+++ b/test/controllers/api/v1/auth_controller_test.rb
@@ -1310,4 +1310,33 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
assert_equal family.id, invitee.family_id
assert_equal 0, AccountShare.where(user: invitee).count
end
+
+ test "sso_providers lists configured providers without secrets" do
+ Rails.configuration.x.auth.stubs(:sso_providers).returns([
+ { id: "authentik", name: "authentik", strategy: "openid_connect", label: "Authentik", client_secret: "shh", issuer: "https://idp.example.com" },
+ { id: "oidc", name: "openid_connect", strategy: "openid_connect", label: "", client_secret: "shh" },
+ { id: "google", name: "google_oauth2", strategy: "google_oauth2", client_secret: "shh" },
+ { name: "my_keycloak", strategy: "openid_connect" }
+ ])
+
+ get "/api/v1/auth/sso_providers"
+
+ assert_response :success
+ assert_equal [
+ { "name" => "authentik", "strategy" => "openid_connect", "label" => "Authentik" },
+ { "name" => "openid_connect", "strategy" => "openid_connect", "label" => "Sign in with OpenID Connect" },
+ { "name" => "google_oauth2", "strategy" => "google_oauth2", "label" => "Sign in with Google" },
+ { "name" => "my_keycloak", "strategy" => "openid_connect", "label" => "My Keycloak" }
+ ], JSON.parse(response.body)["providers"]
+ assert_not_includes response.body, "shh"
+ end
+
+ test "sso_providers returns an empty list when no providers are configured" do
+ Rails.configuration.x.auth.stubs(:sso_providers).returns([])
+
+ get "/api/v1/auth/sso_providers"
+
+ assert_response :success
+ assert_equal [], JSON.parse(response.body)["providers"]
+ end
end