feat: Implement Google Sign-In functionality and update user profile management

This commit is contained in:
Dayron
2025-10-07 08:25:21 +02:00
parent ec0bc59a70
commit 563ba05f74
7 changed files with 163 additions and 8 deletions

View File

@@ -49,5 +49,7 @@
<string>We need your location to show it on the map.</string> <string>We need your location to show it on the map.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We need your location to show it on the map even in background.</string> <string>We need your location to show it on the map even in background.</string>
<key>GIDClientID</key>
<string>521527250907-3i1qe2656eojs8k9hjdi573j09i9p41m.apps.googleusercontent.com</string>
</dict> </dict>
</plist> </plist>

View File

@@ -47,8 +47,9 @@ class ProfileContent extends StatelessWidget {
radius: 40, radius: 40,
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.primary,
child: Text( child: Text(
user.prenom[0].toUpperCase() + user.prenom.isNotEmpty
user.nom[0].toUpperCase(), ? user.prenom[0].toUpperCase()
: 'U',
style: TextStyle( style: TextStyle(
fontSize: 24, fontSize: 24,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,

View File

@@ -67,6 +67,57 @@ class _LoginPageState extends State<LoginPage> {
} }
} }
Future<void> _signInWithGoogle() async {
setState(() {
_isLoading = true;
});
try {
final userCredential = await _authService.signInWithGoogle();
if (mounted && userCredential.user != null) {
final user = userCredential.user!;
final userProvider = Provider.of<UserProvider>(context, listen: false);
// Récupérer les données utilisateur depuis Firestore
final userData = await userProvider.getUserData(user.uid);
if (userData != null) {
// L'utilisateur existe déjà
userProvider.setCurrentUser(userData);
Navigator.pushReplacementNamed(context, '/home');
} else {
// L'utilisateur n'existe pas, créer son profil
final newUserData = {
'uid': user.uid,
'email': user.email ?? '',
'name': user.displayName ?? 'Utilisateur',
};
// Créer le profil utilisateur dans Firestore
final createdUser = await userProvider.createUser(newUserData);
if (createdUser != null) {
userProvider.setCurrentUser(createdUser);
Navigator.pushReplacementNamed(context, '/home');
} else {
_showErrorMessage('Erreur lors de la création du profil utilisateur');
}
}
}
} catch (e) {
if (mounted) {
_showErrorMessage('Erreur lors de la connexion avec Google: ${e.toString()}');
}
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@@ -215,12 +266,7 @@ class _LoginPageState extends State<LoginPage> {
children: [ children: [
// GOOGLE // GOOGLE
GestureDetector( GestureDetector(
onTap: () { onTap: _isLoading ? null : _signInWithGoogle,
// TODO: Implémenter la connexion Google
_showErrorMessage(
'Connexion Google non implémentée',
);
},
child: Container( child: Container(
width: 50, width: 50,
height: 50, height: 50,

View File

@@ -66,6 +66,27 @@ class UserProvider extends ChangeNotifier {
} }
} }
// Méthode pour créer un nouvel utilisateur dans Firestore
Future<User?> createUser(Map<String, dynamic> userData) async {
try {
// Structurer les données pour que tous les utilisateurs aient le même format
final userDoc = {
'id': userData['uid'],
'email': userData['email'] ?? '',
'nom': '', // Nom vide pour tous les utilisateurs
'prenom': userData['name'] ?? userData['nom'] ?? 'Utilisateur', // Nom complet dans prenom
};
await _firestore.collection('users').doc(userData['uid']).set(userDoc);
// Retourner l'objet User créé
return User.fromMap({...userDoc, 'id': userData['uid']});
} catch (e) {
print('Erreur lors de la création de l\'utilisateur: $e');
return null;
}
}
// Initialiser l'utilisateur connecté // Initialiser l'utilisateur connecté
Future<void> initializeUser() async { Future<void> initializeUser() async {
firebase_auth.User? firebaseUser = _authService.currentUser; firebase_auth.User? firebaseUser = _authService.currentUser;

View File

@@ -1,4 +1,6 @@
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
class AuthService { class AuthService {
final FirebaseAuth firebaseAuth = FirebaseAuth.instance; final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
@@ -64,5 +66,39 @@ class AuthService {
// Update the password // Update the password
await currentUser!.updatePassword(newPassword); await currentUser!.updatePassword(newPassword);
} }
Future<void> ensureInitialized(){
return GoogleSignInPlatform.instance.init(const InitParameters());
}
Future<UserCredential> signInWithGoogle() async {
try {
await ensureInitialized();
final AuthenticationResults result = await GoogleSignInPlatform.instance.authenticate(const AuthenticateParameters());
final String? idToken = result.authenticationTokens.idToken;
if (idToken == null) {
throw FirebaseAuthException(
code: 'ERROR_MISSING_GOOGLE_ID_TOKEN',
message: 'Missing Google ID Token',
);
} else {
final OAuthCredential credential = GoogleAuthProvider.credential(idToken: idToken);
UserCredential userCredential = await firebaseAuth.signInWithCredential(credential);
// Retourner le UserCredential au lieu de void
return userCredential;
}
} on GoogleSignInException catch (e) {
print('Erreur lors de l\'initialisation de Google Sign-In: $e');
rethrow;
} on FirebaseAuthException catch (e) {
print('Erreur Firebase lors de l\'initialisation de Google Sign-In: $e');
rethrow;
} catch (e) {
print('Erreur inconnue lors de l\'initialisation de Google Sign-In: $e');
rethrow;
}
}
} }

View File

@@ -200,6 +200,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
google_identity_services_web:
dependency: transitive
description:
name: google_identity_services_web
sha256: "5d187c46dc59e02646e10fe82665fc3884a9b71bc1c90c2b8b749316d33ee454"
url: "https://pub.dev"
source: hosted
version: "0.3.3+1"
google_maps: google_maps:
dependency: transitive dependency: transitive
description: description:
@@ -248,6 +256,46 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.5.14+2" version: "0.5.14+2"
google_sign_in:
dependency: "direct main"
description:
name: google_sign_in
sha256: "521031b65853b4409b8213c0387d57edaad7e2a949ce6dea0d8b2afc9cb29763"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
google_sign_in_android:
dependency: transitive
description:
name: google_sign_in_android
sha256: "7abdfa0088dc8f7d08eb3dbb1665a72bcb5b37afa256c9ec5d21e1e2d7503e5c"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
google_sign_in_ios:
dependency: transitive
description:
name: google_sign_in_ios
sha256: d9d80f953a244a099a40df1ff6aadc10ee375e6a098bbd5d55be332ce26db18c
url: "https://pub.dev"
source: hosted
version: "6.2.1"
google_sign_in_platform_interface:
dependency: transitive
description:
name: google_sign_in_platform_interface
sha256: "7f59208c42b415a3cca203571128d6f84f885fead2d5b53eb65a9e27f2965bb5"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
google_sign_in_web:
dependency: transitive
description:
name: google_sign_in_web
sha256: "2fc1f941e6443b2d6984f4056a727a3eaeab15d8ee99ba7125d79029be75a1da"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
html: html:
dependency: transitive dependency: transitive
description: description:

View File

@@ -43,6 +43,7 @@ dependencies:
firebase_core: ^4.1.1 firebase_core: ^4.1.1
firebase_auth: ^6.1.0 firebase_auth: ^6.1.0
cloud_firestore: ^6.0.2 cloud_firestore: ^6.0.2
google_sign_in: ^7.2.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: