- Framework: Flutter web - Pages: Login, inscription, dashboards - Services: API client, authentification, gestion d'état - Intégration avec backend NestJS - Dockerfile pour déploiement web
151 lines
4.5 KiB
Dart
151 lines
4.5 KiB
Dart
import 'dart:convert';
|
|
import 'package:p_tits_pas/services/api/api_config.dart';
|
|
import 'package:p_tits_pas/services/api/tokenService.dart';
|
|
import '../models/user.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
|
|
class AuthService {
|
|
final String baseUrl = ApiConfig.baseUrl;
|
|
|
|
//login
|
|
Future<Map<String, dynamic>> login(String email, String password) async {
|
|
try {
|
|
final response = await http.post(
|
|
Uri.parse('$baseUrl${ApiConfig.login}'),
|
|
headers: ApiConfig.headers,
|
|
body: jsonEncode({
|
|
'email': email,
|
|
'password': password
|
|
}),
|
|
);
|
|
if (response.statusCode == 201) {
|
|
final data = jsonDecode(response.body);
|
|
|
|
await TokenService.saveToken(data['access_token']);
|
|
await TokenService.saveRefreshToken(data['refresh_token']);
|
|
final role = _extractRoleFromToken(data['access_token']);
|
|
await TokenService.saveRole(role);
|
|
|
|
return data;
|
|
} else {
|
|
throw Exception('Failed to login: ${response.body}');
|
|
}
|
|
} catch (e) {
|
|
throw Exception('Failed to login: $e');
|
|
}
|
|
}
|
|
|
|
String _extractRoleFromToken(String token) {
|
|
try {
|
|
final parts = token.split('.');
|
|
if (parts.length != 3) return '';
|
|
|
|
final payload = parts[1];
|
|
final normalizedPayload = base64Url.normalize(payload);
|
|
final decoded = utf8.decode(base64Url.decode(normalizedPayload));
|
|
final Map<String, dynamic> payloadMap = jsonDecode(decoded);
|
|
|
|
return payloadMap['role'] ?? '';
|
|
} catch (e) {
|
|
print('Error extracting role from token: $e');
|
|
return '';
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
await TokenService.clearAll();
|
|
}
|
|
|
|
Future<bool> isAuthenticated() async {
|
|
final token = await TokenService.getToken();
|
|
if (token == null) return false;
|
|
|
|
return !_isTokenExpired(token);
|
|
}
|
|
|
|
bool _isTokenExpired(String token) {
|
|
try {
|
|
final parts = token.split('.');
|
|
if (parts.length != 3) return true;
|
|
|
|
final payload = parts[1];
|
|
final normalizedPayload = base64Url.normalize(payload);
|
|
final decoded = utf8.decode(base64Url.decode(normalizedPayload));
|
|
final Map<String, dynamic> payloadMap = jsonDecode(decoded);
|
|
|
|
final exp = payloadMap['exp'];
|
|
if (exp == null) return true;
|
|
|
|
final expirationDate = DateTime.fromMillisecondsSinceEpoch(exp * 1000);
|
|
return DateTime.now().isAfter(expirationDate);
|
|
} catch (e) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
//register
|
|
Future<AppUser> register({
|
|
required String email,
|
|
required String password,
|
|
required String firstName,
|
|
required String lastName,
|
|
required String role,
|
|
}) async {
|
|
final response = await http.post(
|
|
Uri.parse('$baseUrl${ApiConfig.register}'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({
|
|
'email': email,
|
|
'password': password,
|
|
'firstName': firstName,
|
|
'lastName': lastName,
|
|
'role': role,
|
|
}),
|
|
);
|
|
|
|
if (response.statusCode == 201) {
|
|
final data = jsonDecode(response.body);
|
|
return AppUser.fromJson(data['user']);
|
|
} else {
|
|
throw Exception('Failed to register');
|
|
}
|
|
}
|
|
|
|
/*static const String _usersKey = 'users';
|
|
static const String _parentsKey = 'parents';
|
|
static const String _childrenKey = 'children';
|
|
|
|
// Méthode pour se connecter (mode démonstration)
|
|
static Future<AppUser> login(String email, String password) async {
|
|
await Future.delayed(const Duration(seconds: 1)); // Simule un délai de traitement
|
|
throw Exception('Mode démonstration - Connexion désactivée');
|
|
}
|
|
|
|
// Méthode pour s'inscrire (mode démonstration)
|
|
static Future<AppUser> register({
|
|
required String email,
|
|
required String password,
|
|
required String firstName,
|
|
required String lastName,
|
|
required String role,
|
|
}) async {
|
|
await Future.delayed(const Duration(seconds: 1)); // Simule un délai de traitement
|
|
throw Exception('Mode démonstration - Inscription désactivée');
|
|
}
|
|
|
|
// Méthode pour se déconnecter (mode démonstration)
|
|
static Future<void> logout() async {
|
|
// Ne fait rien en mode démonstration
|
|
}
|
|
|
|
// Méthode pour vérifier si l'utilisateur est connecté (mode démonstration)
|
|
static Future<bool> isLoggedIn() async {
|
|
return false; // Toujours non connecté en mode démonstration
|
|
}
|
|
|
|
// Méthode pour récupérer l'utilisateur connecté (mode démonstration)
|
|
static Future<AppUser?> getCurrentUser() async {
|
|
return null; // Aucun utilisateur en mode démonstration
|
|
}*/
|
|
} |