refactoring

This commit is contained in:
DahoudG
2024-09-01 04:08:50 +00:00
parent 7e1cb85160
commit a1fce6bf27
31 changed files with 1651 additions and 441 deletions

View File

@@ -0,0 +1,145 @@
import 'dart:convert';
import 'package:afterwork/core/constants/urls.dart';
import 'package:afterwork/data/models/event_model.dart';
import 'package:http/http.dart' as http;
import '../../core/errors/exceptions.dart';
class EventRemoteDataSource {
final http.Client client;
EventRemoteDataSource(this.client);
/// Récupérer tous les événements depuis l'API.
Future<List<EventModel>> getAllEvents() async {
print('Récupération de tous les événements depuis ${Urls.baseUrl}/events');
final response = await client.get(Uri.parse('${Urls.baseUrl}/events'));
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode == 200) {
final List<dynamic> jsonResponse = json.decode(response.body);
print('Réponse JSON reçue: $jsonResponse');
return jsonResponse.map((event) => EventModel.fromJson(event)).toList();
} else {
print('Erreur lors de la récupération des événements: ${response.body}');
throw ServerException();
}
}
/// Créer un nouvel événement via l'API.
Future<EventModel> createEvent(EventModel event) async {
print('Création d\'un nouvel événement avec les données: ${event.toJson()}');
final response = await client.post(
Uri.parse(Urls.eventsUrl),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(event.toJson()),
);
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode == 201) {
print('Événement créé avec succès');
return EventModel.fromJson(json.decode(response.body));
} else {
print('Erreur lors de la création de l\'événement: ${response.body}');
throw ServerException();
}
}
/// Récupérer un événement spécifique par son ID.
Future<EventModel> getEventById(String id) async {
print('Récupération de l\'événement avec l\'ID: $id');
final response = await client.get(Uri.parse('${Urls.eventsUrl}/$id'));
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode == 200) {
print('Événement récupéré avec succès');
return EventModel.fromJson(json.decode(response.body));
} else {
print('Erreur lors de la récupération de l\'événement: ${response.body}');
throw ServerException();
}
}
/// Mettre à jour un événement existant.
Future<EventModel> updateEvent(String id, EventModel event) async {
print('Mise à jour de l\'événement avec l\'ID: $id, données: ${event.toJson()}');
final response = await client.put(
Uri.parse('${Urls.eventsUrl}/$id'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(event.toJson()),
);
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode == 200) {
print('Événement mis à jour avec succès');
return EventModel.fromJson(json.decode(response.body));
} else {
print('Erreur lors de la mise à jour de l\'événement: ${response.body}');
throw ServerException();
}
}
/// Supprimer un événement par son ID.
Future<void> deleteEvent(String id) async {
print('Suppression de l\'événement avec l\'ID: $id');
final response = await client.delete(Uri.parse('${Urls.eventsUrl}/$id'));
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode != 204) {
print('Erreur lors de la suppression de l\'événement: ${response.body}');
throw ServerException();
} else {
print('Événement supprimé avec succès');
}
}
/// Participer à un événement.
Future<EventModel> participateInEvent(String eventId, String userId) async {
print('Participation à l\'événement avec l\'ID: $eventId, utilisateur: $userId');
final response = await client.post(
Uri.parse('${Urls.eventsUrl}/$eventId/participate'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'userId': userId}),
);
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode == 200) {
print('Participation réussie');
return EventModel.fromJson(json.decode(response.body));
} else {
print('Erreur lors de la participation à l\'événement: ${response.body}');
throw ServerException();
}
}
/// Réagir à un événement.
Future<void> reactToEvent(String eventId, String userId) async {
print('Réaction à l\'événement avec l\'ID: $eventId, utilisateur: $userId');
final response = await client.post(
Uri.parse('${Urls.eventsUrl}/$eventId/react'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'userId': userId}),
);
print('Statut de la réponse: ${response.statusCode}');
if (response.statusCode != 200) {
print('Erreur lors de la réaction à l\'événement: ${response.body}');
throw ServerException();
} else {
print('Réaction réussie');
}
}
}

View File

@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:afterwork/data/models/user_model.dart';
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';
@@ -10,7 +11,8 @@ class UserRemoteDataSource {
UserRemoteDataSource(this.client);
Future<UserModel> authenticateUser(String email, String password) async {
// 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');
}
@@ -34,8 +36,9 @@ class UserRemoteDataSource {
}
}
// Récupérer un utilisateur par ID
Future<UserModel> getUser(String id) async {
final response = await client.get(Uri.parse('${Urls.baseUrl}/user/$id'));
final response = await client.get(Uri.parse('${Urls.baseUrl}/users/$id'));
if (response.statusCode == 200) {
return UserModel.fromJson(json.decode(response.body));
@@ -43,4 +46,45 @@ class UserRemoteDataSource {
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();
}
}
}

View File

@@ -0,0 +1,34 @@
import 'package:afterwork/data/models/user_model.dart';
/// Modèle représentant le créateur d'un événement.
class CreatorModel extends UserModel {
CreatorModel({
required String id,
required String nom,
required String prenoms,
}) : super(
userId: id,
nom: nom,
prenoms: prenoms,
email: '', // Valeur par défaut vide
motDePasse: '', // Valeur par défaut vide
);
factory CreatorModel.fromJson(Map<String, dynamic> json) {
return CreatorModel(
id: json['id'],
nom: json['nom'],
prenoms: json['prenoms'],
);
}
@override
Map<String, dynamic> toJson() {
return {
'id': userId,
'nom': nom,
'prenoms': prenoms,
};
}
}

View File

@@ -0,0 +1,65 @@
import 'package:afterwork/data/models/user_model.dart';
/// Modèle de données représentant un événement.
class EventModel {
final String id;
final String title;
final String description;
final String date;
final String location;
final String category;
final String link;
final String? imageUrl;
final UserModel creator;
final List<UserModel> participants;
/// Constructeur pour initialiser toutes les propriétés de l'événement.
EventModel({
required this.id,
required this.title,
required this.description,
required this.date,
required this.location,
required this.category,
required this.link,
required this.imageUrl,
required this.creator,
required this.participants,
});
/// Convertit un objet JSON en `EventModel`.
factory EventModel.fromJson(Map<String, dynamic> json) {
return EventModel(
id: json['id'],
title: json['title'],
description: json['description'],
date: json['date'],
location: json['location'],
category: json['category'],
link: json['link'],
imageUrl: json['imageUrl'],
creator: UserModel.fromJson(json['creator']),
participants: json['participants'] != null
? (json['participants'] as List)
.map((user) => UserModel.fromJson(user))
.toList()
: [],
);
}
/// Convertit un `EventModel` en objet JSON.
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'description': description,
'date': date,
'location': location,
'category': category,
'link': link,
'imageUrl': imageUrl,
'creator': creator.toJson(),
'participants': participants.map((user) => user.toJson()).toList(),
};
}
}

View File

@@ -0,0 +1,34 @@
import 'package:afterwork/data/models/user_model.dart';
/// Modèle représentant un participant à un événement.
class ParticipantModel extends UserModel {
ParticipantModel({
required String id,
required String nom,
required String prenoms,
}) : super(
userId: id,
nom: nom,
prenoms: prenoms,
email: '', // Valeur par défaut vide
motDePasse: '', // Valeur par défaut vide
);
factory ParticipantModel.fromJson(Map<String, dynamic> json) {
return ParticipantModel(
id: json['id'],
nom: json['nom'],
prenoms: json['prenoms'],
);
}
@override
Map<String, dynamic> toJson() {
return {
'id': userId,
'nom': nom,
'prenoms': prenoms,
};
}
}

View File

@@ -1,14 +1,14 @@
import 'package:afterwork/domain/entities/user.dart';
class UserModel extends User {
class UserModel extends User {
const UserModel({
required String id,
required String userId, // Utilisez `id` pour correspondre à l'entité User
required String nom,
required String prenoms,
required String email,
required String motDePasse,
}) : super(
id: id,
userId: userId,
nom: nom,
prenoms: prenoms,
email: email,
@@ -17,7 +17,7 @@ class UserModel extends User {
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json['id'] ?? '',
userId: json['id'] ?? '',
nom: json['nom'] ?? '',
prenoms: json['prenoms'] ?? '',
email: json['email'] ?? '',
@@ -27,7 +27,7 @@ class UserModel extends User {
Map<String, dynamic> toJson() {
return {
'id': id,
'id': userId, // Utilisez `id` pour correspondre à l'entité User
'nom': nom,
'prenoms': prenoms,
'email': email,

View File

@@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class UserProvider with ChangeNotifier {
String _userId = '';
String _userName = '';
String _userLastName = '';
String get userId => _userId;
String get userName => _userName;
String get userLastName => _userLastName;
void setUser(String id, String name, String lastName) {
_userId = id;
_userName = name;
_userLastName = lastName;
notifyListeners();
}
}

View File

@@ -14,8 +14,8 @@ class UserRepositoryImpl implements UserRepository {
return userModel; // Retourne un UserModel qui est un sous-type de User
}
Future<User> authenticateUser(String email, String password) async {
UserModel userModel = await remoteDataSource.authenticateUser(email, password);
Future<User> authenticateUser(String email, String password, String userId) async {
UserModel userModel = await remoteDataSource.authenticateUser(email, password, userId);
return userModel; // Retourne un UserModel qui est un sous-type de User
}
}

View File

@@ -0,0 +1,8 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
String hashPassword(String password) {
var bytes = utf8.encode(password); // Convertir en bytes
var digest = sha256.convert(bytes); // Hachage SHA-256
return digest.toString(); // Retourner le hash sous forme de chaîne
}

View File

@@ -0,0 +1,50 @@
import 'package:shared_preferences/shared_preferences.dart';
class PreferencesHelper {
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<void> setString(String key, String value) async {
final prefs = await _prefs;
await prefs.setString(key, value);
}
Future<String?> getString(String key) async {
final prefs = await _prefs;
return prefs.getString(key);
}
Future<void> remove(String key) async {
final prefs = await _prefs;
await prefs.remove(key);
}
Future<void> saveUserId(String userId) async {
await setString('user_id', userId);
}
Future<String?> getUserId() async {
return await getString('user_id');
}
Future<void> saveUserName(String userName) async {
await setString('user_name', userName);
}
Future<String?> getUserName() async {
return await getString('user_name');
}
Future<void> saveUserLastName(String userLastName) async {
await setString('user_last_name', userLastName);
}
Future<String?> getUserLastName() async {
return await getString('user_last_name');
}
Future<void> clearUserInfo() async {
await remove('user_id');
await remove('user_name');
await remove('user_last_name');
}
}

View File

@@ -0,0 +1,47 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorage {
final FlutterSecureStorage _storage = const FlutterSecureStorage();
Future<void> write(String key, String value) async {
await _storage.write(key: key, value: value);
}
Future<String?> read(String key) async {
return await _storage.read(key: key);
}
Future<void> delete(String key) async {
await _storage.delete(key: key);
}
Future<void> saveUserId(String userId) async {
await write('user_id', userId);
}
Future<String?> getUserId() async {
return await read('user_id');
}
Future<void> saveUserName(String userName) async {
await write('user_name', userName);
}
Future<String?> getUserName() async {
return await read('user_name');
}
Future<void> saveUserLastName(String userLastName) async {
await write('user_last_name', userLastName);
}
Future<String?> getUserLastName() async {
return await read('user_last_name');
}
Future<void> deleteUserInfo() async {
await delete('user_id');
await delete('user_name');
await delete('user_last_name');
}
}