This commit is contained in:
2026-09-29 14:26:17 +02:00
parent 88a7c2eba0
commit 06fe43bba3
24 changed files with 985 additions and 174 deletions

View File

@@ -0,0 +1,22 @@
import 'package:flutter_dotenv/flutter_dotenv.dart';
/// Endpoints et variables OAuth 42 (fichier `.env` à la racine du package Flutter).
abstract final class IntraConfig {
static const String authorizeUrl = 'https://api.intra.42.fr/oauth/authorize';
static const String tokenUrl = 'https://api.intra.42.fr/oauth/token';
static const String apiBaseUrl = 'https://api.intra.42.fr/v2';
static String get clientId => dotenv.env['CLIENT_ID']?.trim() ?? '';
static String get clientSecret => dotenv.env['CLIENT_SECRET']?.trim() ?? '';
static String get redirectUri => dotenv.env['REDIRECT_URI']?.trim() ?? '';
static bool get isConfigured =>
clientId.isNotEmpty && clientSecret.isNotEmpty && redirectUri.isNotEmpty;
/// Aide debug (écran auth) — ne pas afficher le secret complet.
static String get clientIdSuffix {
final id = clientId;
if (id.length < 6) return '?';
return id.substring(id.length - 6);
}
}

View File

@@ -1,121 +1,28 @@
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
void main() {
runApp(const MyApp());
import 'screens/search_screen.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await dotenv.load(fileName: '.env');
runApp(const SwiftyCompanionApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
class SwiftyCompanionApp extends StatelessWidget {
const SwiftyCompanionApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: 'Swifty Companion',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF00BABC)),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: .center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
home: const SearchScreen(),
onUnknownRoute: (_) => MaterialPageRoute<void>(
builder: (_) => const SearchScreen(),
),
);
}

View File

@@ -0,0 +1,139 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_appauth/flutter_appauth.dart';
import '../config/intra_config.dart';
import '../services/intra_auth_service.dart';
/// Écran temporaire étape 2 : valider OAuth + token unique (/v2/me).
class AuthScreen extends StatefulWidget {
const AuthScreen({super.key});
@override
State<AuthScreen> createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final _auth = IntraAuthService.instance;
bool _loading = false;
String? _error;
String? _login;
Future<void> _connect() async {
setState(() {
_loading = true;
_error = null;
_login = null;
});
try {
await _auth.signIn();
final me = await _auth.fetchMe();
if (!mounted) return;
setState(() {
_login = me['login'] as String?;
_error = null;
});
} on FlutterAppAuthUserCancelledException {
if (!mounted) return;
setState(() => _error = 'Connexion annulée');
} on FlutterAppAuthPlatformException catch (e) {
final d = e.platformErrorDetails;
if (!mounted) return;
setState(() {
_error = d.errorDescription ??
d.error ??
d.errorDebugDescription ??
e.message ??
'Échec OAuth (UID, SECRET, redirect Intra)';
});
} on PlatformException catch (e) {
if (!mounted) return;
setState(() => _error = e.message ?? 'Erreur OAuth');
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
} finally {
if (mounted) {
setState(() => _loading = false);
}
}
}
void _disconnect() {
_auth.signOut();
setState(() => _login = null);
}
@override
Widget build(BuildContext context) {
if (!IntraConfig.isConfigured) {
return Scaffold(
appBar: AppBar(title: const Text('Swifty Companion')),
body: const Padding(
padding: EdgeInsets.all(24),
child: Text(
'Fichier .env manquant ou incomplet.\n'
'Copie swiftyCompanion/.env vers swifty_companion/.env '
'(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI).',
),
),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Swifty Companion'),
backgroundColor: const Color(0xFF00BABC),
foregroundColor: Colors.black,
),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Étape 2 — Connexion API 42',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
_auth.isAuthenticated
? 'Token actif (réutilisé pour /v2/me)'
: 'Connecte-toi une fois ; le token servira pour toutes les requêtes.',
),
const SizedBox(height: 24),
if (_login != null) ...[
Text('Connecté : $_login', style: const TextStyle(fontSize: 16)),
const SizedBox(height: 16),
OutlinedButton(onPressed: _disconnect, child: const Text('Déconnexion')),
] else
FilledButton(
onPressed: _loading ? null : _connect,
child: _loading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Se connecter avec 42'),
),
if (_error != null) ...[
const SizedBox(height: 16),
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
],
const Spacer(),
Text(
'Config (.env dans swifty_companion/)\n'
'Redirect : ${IntraConfig.redirectUri}\n'
'CLIENT_ID …${IntraConfig.clientIdSuffix}\n'
'Après modification du .env : arrêter l’app puis flutter run (pas hot reload).',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
);
}
}

View File

@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
/// Vue 2 — squelette étape 3 ; détails complets à l’étape 4.
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key, required this.user});
final Map<String, dynamic> user;
String? _imageUrl() {
final image = user['image'];
if (image is Map<String, dynamic>) {
final link = image['link'];
if (link is String && link.isNotEmpty) return link;
}
final url = user['image_url'];
if (url is String && url.isNotEmpty) return url;
return null;
}
@override
Widget build(BuildContext context) {
final login = user['login']?.toString() ?? '?';
final imageUrl = _imageUrl();
return Scaffold(
appBar: AppBar(
title: Text(login),
backgroundColor: const Color(0xFF00BABC),
foregroundColor: Colors.black,
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: CircleAvatar(
radius: 56,
backgroundImage:
imageUrl != null ? NetworkImage(imageUrl) : null,
child: imageUrl == null
? Text(
login.isNotEmpty ? login[0].toUpperCase() : '?',
style: const TextStyle(fontSize: 32),
)
: null,
),
),
const SizedBox(height: 16),
Text(
login,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 24),
Text(
'Étape 4 à venir : email, level, skills, projets (dont failed), etc.',
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 8),
Text(
'ID Intra : ${user['id'] ?? '—'}',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
);
}
}

View File

@@ -0,0 +1,208 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_appauth/flutter_appauth.dart';
import '../config/intra_config.dart';
import '../services/intra_api_exception.dart';
import '../services/intra_auth_service.dart';
import '../services/intra_user_service.dart';
import 'profile_screen.dart';
/// Vue 1 — recherche par login 42.
class SearchScreen extends StatefulWidget {
const SearchScreen({super.key});
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
final _auth = IntraAuthService.instance;
final _users = IntraUserService.instance;
final _loginController = TextEditingController();
bool _connecting = false;
bool _searching = false;
String? _error;
String? _sessionLogin;
@override
void dispose() {
_loginController.dispose();
super.dispose();
}
Future<void> _connect() async {
setState(() {
_connecting = true;
_error = null;
});
try {
await _auth.signIn();
final me = await _auth.fetchMe();
if (!mounted) return;
setState(() {
_sessionLogin = me['login'] as String?;
});
} on FlutterAppAuthUserCancelledException {
if (!mounted) return;
setState(() => _error = 'Connexion annulée');
} on FlutterAppAuthPlatformException catch (e) {
final d = e.platformErrorDetails;
if (!mounted) return;
setState(() {
_error = d.errorDescription ??
d.error ??
d.errorDebugDescription ??
e.message ??
'Échec OAuth';
});
} on PlatformException catch (e) {
if (!mounted) return;
setState(() => _error = e.message ?? 'Erreur OAuth');
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
} finally {
if (mounted) setState(() => _connecting = false);
}
}
void _disconnect() {
_auth.signOut();
setState(() {
_sessionLogin = null;
_error = null;
});
}
Future<void> _search() async {
setState(() {
_searching = true;
_error = null;
});
try {
final user = await _users.fetchUserByLogin(_loginController.text);
if (!mounted) return;
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => ProfileScreen(user: user),
),
);
} on IntraApiException catch (e) {
if (!mounted) return;
setState(() => _error = e.message);
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
} finally {
if (mounted) setState(() => _searching = false);
}
}
@override
Widget build(BuildContext context) {
if (!IntraConfig.isConfigured) {
return Scaffold(
appBar: AppBar(title: const Text('Swifty Companion')),
body: const Padding(
padding: EdgeInsets.all(24),
child: Text(
'Fichier .env manquant dans swifty_companion/.env',
),
),
);
}
final isAuthenticated = _auth.isAuthenticated;
return Scaffold(
appBar: AppBar(
title: const Text('Swifty Companion'),
backgroundColor: const Color(0xFF00BABC),
foregroundColor: Colors.black,
actions: [
if (isAuthenticated)
IconButton(
onPressed: _connecting || _searching ? null : _disconnect,
icon: const Icon(Icons.logout),
tooltip: 'Déconnexion API',
),
],
),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!isAuthenticated) ...[
const Text(
'Connexion API 42',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
'Connecte-toi une fois ; le token servira pour toutes les recherches.',
),
const SizedBox(height: 16),
FilledButton(
onPressed: _connecting ? null : _connect,
child: _connecting
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Se connecter avec 42'),
),
] else ...[
Text(
'Session : ${_sessionLogin ?? 'connecté'}',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 24),
const Text(
'Rechercher un étudiant',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
TextField(
controller: _loginController,
decoration: const InputDecoration(
labelText: 'Login 42',
hintText: 'ex. fgras-ca',
border: OutlineInputBorder(),
),
textInputAction: TextInputAction.search,
onSubmitted: (_) {
if (!_searching) _search();
},
enabled: !_searching,
),
const SizedBox(height: 16),
FilledButton(
onPressed: _searching ? null : _search,
child: _searching
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Rechercher'),
),
],
if (_error != null) ...[
const SizedBox(height: 16),
Text(
_error!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
],
],
),
),
);
}
}

View File

@@ -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);
}

View File

@@ -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>;
}
}

View File

@@ -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;
}
}