etape3
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
/// Erreurs métier pour les appels API 42.
|
||||
sealed class IntraApiException implements Exception {
|
||||
const IntraApiException(this.message);
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class IntraNotAuthenticatedException extends IntraApiException {
|
||||
const IntraNotAuthenticatedException()
|
||||
: super('Connecte-toi d’abord à l’API 42');
|
||||
}
|
||||
|
||||
class IntraUserNotFoundException extends IntraApiException {
|
||||
const IntraUserNotFoundException()
|
||||
: super('Aucun utilisateur pour ce login');
|
||||
}
|
||||
|
||||
class IntraNetworkException extends IntraApiException {
|
||||
const IntraNetworkException()
|
||||
: super('Connexion impossible. Vérifie le réseau.');
|
||||
}
|
||||
|
||||
class IntraUnauthorizedException extends IntraApiException {
|
||||
const IntraUnauthorizedException()
|
||||
: super('Session expirée. Reconnecte-toi à l’API 42');
|
||||
}
|
||||
|
||||
class IntraApiErrorException extends IntraApiException {
|
||||
const IntraApiErrorException(super.message);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_appauth/flutter_appauth.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../config/intra_config.dart';
|
||||
|
||||
/// OAuth2 Intra : un token réutilisé pour toutes les requêtes API.
|
||||
class IntraAuthService {
|
||||
IntraAuthService._();
|
||||
static final IntraAuthService instance = IntraAuthService._();
|
||||
|
||||
final FlutterAppAuth _appAuth = const FlutterAppAuth();
|
||||
|
||||
String? _accessToken;
|
||||
|
||||
String? get accessToken => _accessToken;
|
||||
bool get isAuthenticated => _accessToken != null && _accessToken!.isNotEmpty;
|
||||
|
||||
static final AuthorizationServiceConfiguration _serviceConfiguration =
|
||||
AuthorizationServiceConfiguration(
|
||||
authorizationEndpoint: IntraConfig.authorizeUrl,
|
||||
tokenEndpoint: IntraConfig.tokenUrl,
|
||||
);
|
||||
|
||||
Future<void> signIn() async {
|
||||
if (!IntraConfig.isConfigured) {
|
||||
throw StateError(
|
||||
'CLIENT_ID, CLIENT_SECRET ou REDIRECT_URI manquant dans .env',
|
||||
);
|
||||
}
|
||||
|
||||
final result = await _appAuth.authorizeAndExchangeCode(
|
||||
AuthorizationTokenRequest(
|
||||
IntraConfig.clientId,
|
||||
IntraConfig.redirectUri,
|
||||
clientSecret: IntraConfig.clientSecret,
|
||||
serviceConfiguration: _serviceConfiguration,
|
||||
scopes: ['public'],
|
||||
),
|
||||
);
|
||||
|
||||
_accessToken = result.accessToken;
|
||||
|
||||
if (!isAuthenticated) {
|
||||
throw StateError('Connexion 42 annulée ou token absent');
|
||||
}
|
||||
}
|
||||
|
||||
void signOut() {
|
||||
_accessToken = null;
|
||||
}
|
||||
|
||||
/// Header Authorization pour les appels `api.intra.42.fr`.
|
||||
Map<String, String> authHeaders() {
|
||||
if (!isAuthenticated) {
|
||||
throw StateError('Non connecté à l’Intra');
|
||||
}
|
||||
return {
|
||||
'Authorization': 'Bearer $_accessToken',
|
||||
'Accept': 'application/json',
|
||||
};
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> fetchMe() async {
|
||||
final response = await http.get(
|
||||
Uri.parse('${IntraConfig.apiBaseUrl}/me'),
|
||||
headers: authHeaders(),
|
||||
);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('GET /v2/me a échoué (${response.statusCode})');
|
||||
}
|
||||
|
||||
return jsonDecode(response.body) as Map<String, dynamic>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user