91 lines
2.5 KiB
Dart
91 lines
2.5 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:afterwork/core/constants/urls.dart';
|
|
import 'package:afterwork/data/models/user_model.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../../core/errors/exceptions.dart';
|
|
|
|
class UserRemoteDataSource {
|
|
final http.Client client;
|
|
|
|
UserRemoteDataSource(this.client);
|
|
|
|
// Authentifier l'utilisateur
|
|
Future<UserModel> authenticateUser(String email, String password, String userId) async {
|
|
if (email.isEmpty || password.isEmpty) {
|
|
throw Exception('Email ou mot de passe vide');
|
|
}
|
|
|
|
final response = await client.post(
|
|
Uri.parse('${Urls.baseUrl}/users/authenticate'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({
|
|
'email': email,
|
|
'motDePasse': password,
|
|
}),
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
final jsonResponse = json.decode(response.body);
|
|
return UserModel.fromJson(jsonResponse);
|
|
} else if (response.statusCode == 401) {
|
|
throw AuthenticationException('Email ou mot de passe incorrect');
|
|
} else {
|
|
throw ServerException();
|
|
}
|
|
}
|
|
|
|
// Récupérer un utilisateur par ID
|
|
Future<UserModel> getUser(String id) async {
|
|
final response = await client.get(Uri.parse('${Urls.baseUrl}/users/$id'));
|
|
|
|
if (response.statusCode == 200) {
|
|
return UserModel.fromJson(json.decode(response.body));
|
|
} else {
|
|
throw ServerException();
|
|
}
|
|
}
|
|
|
|
// Créer un nouvel utilisateur
|
|
Future<UserModel> createUser(UserModel user) async {
|
|
final response = await client.post(
|
|
Uri.parse('${Urls.baseUrl}/users'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode(user.toJson()),
|
|
);
|
|
|
|
if (response.statusCode == 201) {
|
|
return UserModel.fromJson(json.decode(response.body));
|
|
} else {
|
|
throw ServerException();
|
|
}
|
|
}
|
|
|
|
// Mettre à jour un utilisateur
|
|
Future<UserModel> updateUser(UserModel user) async {
|
|
final response = await client.put(
|
|
Uri.parse('${Urls.baseUrl}/users/${user.userId}'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode(user.toJson()),
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
return UserModel.fromJson(json.decode(response.body));
|
|
} else {
|
|
throw ServerException();
|
|
}
|
|
}
|
|
|
|
// Supprimer un utilisateur par ID
|
|
Future<void> deleteUser(String id) async {
|
|
final response = await client.delete(
|
|
Uri.parse('${Urls.baseUrl}/users/$id'),
|
|
);
|
|
|
|
if (response.statusCode != 204) {
|
|
throw ServerException();
|
|
}
|
|
}
|
|
}
|