162 lines
4.5 KiB
Dart
162 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');
|
|
}
|
|
}
|
|
|
|
Future<String> getUserId() async {
|
|
final token = await TokenService.getToken();
|
|
if (token == null) return '';
|
|
|
|
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['sub'] ?? '';
|
|
} catch (e) {
|
|
print('Error extracting user id from token: $e');
|
|
return '';
|
|
}
|
|
}
|
|
|
|
Future<String?> getUserNameById() async {
|
|
final userid = await getUserId();
|
|
final token = await TokenService.getToken();
|
|
|
|
if (token == null || userid.isEmpty) return null;
|
|
try {
|
|
final response = await http.get(
|
|
Uri.parse('$baseUrl${ApiConfig.users}/$userid'),
|
|
headers: {
|
|
'Authorization': 'Bearer $token',
|
|
'accept': '*/*',
|
|
},
|
|
);
|
|
if (response.statusCode == 200) {
|
|
final data = jsonDecode(response.body);
|
|
final firstName = data['prenom'];
|
|
// final lastName = data['nom'];
|
|
return '$firstName';
|
|
} else {
|
|
print('Erreur Api: ${response.statusCode} - ${response.body}');
|
|
return null;
|
|
}
|
|
} catch (e) {
|
|
print('Error fetching user name: $e');
|
|
return null;
|
|
}
|
|
}
|
|
} |