64 lines
1.7 KiB
Dart
64 lines
1.7 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';
|
|
import 'intra_http.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 intraApiGet(uri, auth: _auth);
|
|
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,
|
|
) {
|
|
ensureIntraOk(response);
|
|
|
|
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;
|
|
}
|
|
}
|