158 lines
5.0 KiB
Dart
158 lines
5.0 KiB
Dart
import 'package:cloud_firestore/cloud_firestore.dart';
|
|
import 'package:firebase_auth/firebase_auth.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:image_picker/image_picker.dart';
|
|
import '../models/user_model.dart';
|
|
import '../utils/firebase_storage_manager.dart';
|
|
|
|
class LocalUserProvider with ChangeNotifier {
|
|
UserModel? _currentUser;
|
|
final FirebaseAuth _auth = FirebaseAuth.instance;
|
|
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
|
final FirebaseStorageManager _storageManager = FirebaseStorageManager();
|
|
|
|
UserModel? get currentUser => _currentUser;
|
|
String? get uid => _currentUser?.uid;
|
|
String? get firstName => _currentUser?.firstName;
|
|
String? get lastName => _currentUser?.lastName;
|
|
String? get role => _currentUser?.role ?? 'USER';
|
|
String? get profilePhotoUrl => _currentUser?.profilePhotoUrl;
|
|
String? get email => _currentUser?.email;
|
|
String? get phoneNumber => _currentUser?.phoneNumber;
|
|
|
|
/// Charge les données de l'utilisateur actuel
|
|
Future<void> loadUserData() async {
|
|
if (_auth.currentUser == null) {
|
|
print('No current user in Auth');
|
|
return;
|
|
}
|
|
|
|
print('Loading user data for: ${_auth.currentUser!.uid}');
|
|
try {
|
|
DocumentSnapshot userDoc = await _firestore
|
|
.collection('users')
|
|
.doc(_auth.currentUser!.uid)
|
|
.get();
|
|
|
|
if (userDoc.exists) {
|
|
print('User document found in Firestore');
|
|
final userData = userDoc.data() as Map<String, dynamic>;
|
|
print('User data: $userData');
|
|
|
|
// Si le document n'a pas d'UID, l'ajouter
|
|
if (!userData.containsKey('uid')) {
|
|
await userDoc.reference.update({'uid': _auth.currentUser!.uid});
|
|
userData['uid'] = _auth.currentUser!.uid;
|
|
}
|
|
|
|
setUser(UserModel.fromMap(userData, userDoc.id));
|
|
print('User data loaded successfully');
|
|
} else {
|
|
print('No user document found in Firestore');
|
|
// Créer un document utilisateur par défaut
|
|
final defaultUser = UserModel(
|
|
uid: _auth.currentUser!.uid,
|
|
email: _auth.currentUser!.email ?? '',
|
|
firstName: '',
|
|
lastName: '',
|
|
role: 'USER',
|
|
phoneNumber: '',
|
|
profilePhotoUrl: '',
|
|
);
|
|
|
|
await _firestore.collection('users').doc(_auth.currentUser!.uid).set({
|
|
'uid': _auth.currentUser!.uid,
|
|
'email': _auth.currentUser!.email,
|
|
'firstName': '',
|
|
'lastName': '',
|
|
'role': 'USER',
|
|
'phoneNumber': '',
|
|
'profilePhotoUrl': '',
|
|
'createdAt': FieldValue.serverTimestamp(),
|
|
});
|
|
|
|
setUser(defaultUser);
|
|
print('Default user document created');
|
|
}
|
|
} catch (e) {
|
|
print('Error loading user data: $e');
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
/// Met à jour l'utilisateur
|
|
void setUser(UserModel user) {
|
|
_currentUser = user;
|
|
notifyListeners();
|
|
}
|
|
|
|
/// Efface les données utilisateur
|
|
void clearUser() {
|
|
_currentUser = null;
|
|
notifyListeners();
|
|
}
|
|
|
|
/// Mise à jour des informations utilisateur
|
|
Future<void> updateUserData(
|
|
{String? firstName, String? lastName, String? phoneNumber}) async {
|
|
if (_currentUser == null) return;
|
|
try {
|
|
await _firestore.collection('users').doc(_currentUser!.uid).set({
|
|
'firstName': firstName ?? _currentUser!.firstName,
|
|
'lastName': lastName ?? _currentUser!.lastName,
|
|
'phone': phoneNumber ?? _currentUser!.phoneNumber,
|
|
}, SetOptions(merge: true));
|
|
|
|
_currentUser = _currentUser!.copyWith(
|
|
firstName: firstName ?? _currentUser!.firstName,
|
|
lastName: lastName ?? _currentUser!.lastName,
|
|
phoneNumber: phoneNumber ?? _currentUser!.phoneNumber,
|
|
);
|
|
notifyListeners();
|
|
} catch (e) {
|
|
debugPrint('Erreur mise à jour utilisateur : $e');
|
|
}
|
|
}
|
|
|
|
/// Changement de photo de profil
|
|
Future<void> changeProfilePicture(XFile image) async {
|
|
if (_currentUser == null) return;
|
|
try {
|
|
String? newProfilePhotoUrl = await _storageManager.sendProfilePicture(
|
|
imageFile: image,
|
|
uid: _currentUser!.uid,
|
|
);
|
|
if (newProfilePhotoUrl != null) {
|
|
_firestore
|
|
.collection('users')
|
|
.doc(_currentUser!.uid)
|
|
.update({'profilePhotoUrl': newProfilePhotoUrl});
|
|
_currentUser =
|
|
_currentUser!.copyWith(profilePhotoUrl: newProfilePhotoUrl);
|
|
notifyListeners();
|
|
}
|
|
} catch (e) {
|
|
debugPrint('Erreur mise à jour photo de profil : $e');
|
|
}
|
|
}
|
|
|
|
/// Connexion
|
|
Future<UserCredential> signInWithEmailAndPassword(
|
|
String email, String password) async {
|
|
try {
|
|
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
|
|
email: email, password: password);
|
|
await loadUserData();
|
|
return userCredential;
|
|
} catch (e) {
|
|
throw FirebaseAuthException(code: 'login-failed', message: e.toString());
|
|
}
|
|
}
|
|
|
|
/// Déconnexion
|
|
Future<void> signOut() async {
|
|
await _auth.signOut();
|
|
clearUser();
|
|
}
|
|
}
|