Files
swift_companion/swiftyCompanion/swifty_companion/lib/services/intra_user_service.dart
2026-09-29 14:26:17 +02:00

70 lines
1.9 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import '../config/intra_config.dart';
import 'intra_api_exception.dart';
import 'intra_auth_service.dart';
class IntraUserService {
IntraUserService._();
static final IntraUserService instance = IntraUserService._();
final IntraAuthService _auth = IntraAuthService.instance;
/// Recherche par login — réutilise le token OAuth (pas de nouvel OAuth).
Future<Map<String, dynamic>> fetchUserByLogin(String login) async {
final trimmed = login.trim();
if (trimmed.isEmpty) {
throw const IntraApiErrorException('Saisis un login');
}
if (!_auth.isAuthenticated) {
throw const IntraNotAuthenticatedException();
}
final uri = Uri.parse('${IntraConfig.apiBaseUrl}/users').replace(
queryParameters: {'filter[login]': trimmed},
);
try {
final response = await http.get(uri, headers: _auth.authHeaders());
return _parseUserListResponse(response, trimmed);
} on IntraApiException {
rethrow;
} on SocketException {
throw const IntraNetworkException();
} on http.ClientException {
throw const IntraNetworkException();
}
}
Map<String, dynamic> _parseUserListResponse(
http.Response response,
String login,
) {
if (response.statusCode == 401) {
throw const IntraUnauthorizedException();
}
if (response.statusCode != 200) {
throw IntraApiErrorException(
'Erreur API (${response.statusCode})',
);
}
final decoded = jsonDecode(response.body);
if (decoded is! List) {
throw IntraApiErrorException('Réponse API inattendue');
}
if (decoded.isEmpty) {
throw const IntraUserNotFoundException();
}
final user = decoded.first;
if (user is! Map<String, dynamic>) {
throw IntraApiErrorException('Réponse API inattendue');
}
return user;
}
}