1
0
forked from baron/baron-sso
Files
baron-sso/userfront/lib/features/dashboard/domain/providers/linked_rps_provider.dart

63 lines
1.9 KiB
Dart

import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:userfront/core/services/auth_proxy_service.dart';
import 'package:userfront/core/services/auth_token_store.dart';
import 'package:userfront/core/services/http_client.dart';
import 'package:userfront/core/services/runtime_env.dart';
import '../models.dart';
class LinkedRpsNotifier extends AsyncNotifier<List<LinkedRp>> {
@override
Future<List<LinkedRp>> build() async {
return _fetchLinkedRps();
}
Future<List<LinkedRp>> _fetchLinkedRps() async {
try {
final baseUrl = runtimeBackendUrl();
final url = Uri.parse('$baseUrl/api/v1/user/rp/linked');
final useCookie = AuthTokenStore.usesCookie();
final token = AuthTokenStore.getToken();
final client = createHttpClient(withCredentials: useCookie);
final headers = <String, String>{'Content-Type': 'application/json'};
if (!useCookie && token != null) {
headers['Authorization'] = 'Bearer $token';
}
final response = await client.get(url, headers: headers);
client.close();
if (response.statusCode != 200) {
throw Exception('Failed to load linked rps: ${response.statusCode}');
}
final body = jsonDecode(response.body) as Map<String, dynamic>;
final items = (body['items'] as List?) ?? [];
return items
.whereType<Map<String, dynamic>>()
.map(LinkedRp.fromJson)
.toList();
} catch (e) {
rethrow;
}
}
Future<void> refresh() async {
state = const AsyncLoading();
state = await AsyncValue.guard(() => _fetchLinkedRps());
}
Future<void> revokeRp(String clientId) async {
await AuthProxyService.revokeLinkedRp(clientId);
await refresh();
}
}
final linkedRpsProvider =
AsyncNotifierProvider<LinkedRpsNotifier, List<LinkedRp>>(() {
return LinkedRpsNotifier();
});