From cf0accfc47ec23c90d636861bad747badb612f0b Mon Sep 17 00:00:00 2001 From: emkartal1 Date: Wed, 16 Aug 2023 13:08:27 +0200 Subject: [PATCH] Connection with google done :white_check_mark: --- .../lib/exceptions/user_exception.dart | 6 ++ .../justMUSIC/lib/screens/login_screen.dart | 18 +++- .../justMUSIC/lib/screens/profile_screen.dart | 4 +- .../lib/screens/registration_screen.dart | 14 ++- .../justMUSIC/lib/services/AuthService.dart | 91 ++++++++++++------- .../lib/view_model/UserViewModel.dart | 16 +++- 6 files changed, 101 insertions(+), 48 deletions(-) create mode 100644 Sources/justMUSIC/lib/exceptions/user_exception.dart diff --git a/Sources/justMUSIC/lib/exceptions/user_exception.dart b/Sources/justMUSIC/lib/exceptions/user_exception.dart new file mode 100644 index 0000000..22a137a --- /dev/null +++ b/Sources/justMUSIC/lib/exceptions/user_exception.dart @@ -0,0 +1,6 @@ +class UserException implements Exception { + String code; + String description; + + UserException(this.code,this.description); +} \ No newline at end of file diff --git a/Sources/justMUSIC/lib/screens/login_screen.dart b/Sources/justMUSIC/lib/screens/login_screen.dart index 0cbddf1..a1afcf3 100644 --- a/Sources/justMUSIC/lib/screens/login_screen.dart +++ b/Sources/justMUSIC/lib/screens/login_screen.dart @@ -1,4 +1,3 @@ -import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -10,6 +9,7 @@ import 'package:justmusic/main.dart'; import 'package:justmusic/values/constants.dart'; import '../components/login_button.dart'; +import '../exceptions/user_exception.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @@ -33,7 +33,7 @@ class _LoginScreenState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - e.toString() ?? "", + e.toString(), style: GoogleFonts.plusJakartaSans(color: Colors.white, fontWeight: FontWeight.w400, fontSize: 20.h), ), backgroundColor: Colors.red, @@ -43,6 +43,18 @@ class _LoginScreenState extends State { } } + signInWithGoogle() async { + try { + await MyApp.userViewModel.signInWithGoogle(); + } on UserException catch (e) { + if (e.code == 'user-created') { + Navigator.pushNamed(context, '/explanation'); + } else if (e.code == 'user-already-exist') { + Navigator.pushNamed(context, '/feed'); + } + } + } + @override Widget build(BuildContext context) { return GestureDetector( @@ -269,7 +281,7 @@ class _LoginScreenState extends State { SignInButton( Buttons.Google, text: "Login with Google", - onPressed: () {}, + onPressed: signInWithGoogle, ), ], ), diff --git a/Sources/justMUSIC/lib/screens/profile_screen.dart b/Sources/justMUSIC/lib/screens/profile_screen.dart index a40fd0a..f87ff7a 100644 --- a/Sources/justMUSIC/lib/screens/profile_screen.dart +++ b/Sources/justMUSIC/lib/screens/profile_screen.dart @@ -1,4 +1,3 @@ -import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -21,8 +20,7 @@ class _ProfileScreenState extends State { @override Widget build(BuildContext context) { Future logout() async { - print("cc"); - await FirebaseAuth.instance.signOut(); + await MyApp.userViewModel.logout(); Navigator.pushNamed(context, '/welcome'); } diff --git a/Sources/justMUSIC/lib/screens/registration_screen.dart b/Sources/justMUSIC/lib/screens/registration_screen.dart index afb2319..60be518 100644 --- a/Sources/justMUSIC/lib/screens/registration_screen.dart +++ b/Sources/justMUSIC/lib/screens/registration_screen.dart @@ -7,6 +7,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_signin_button/button_list.dart'; import 'package:flutter_signin_button/button_view.dart'; import 'package:google_fonts/google_fonts.dart'; +import 'package:justmusic/exceptions/user_exception.dart'; import 'package:justmusic/values/constants.dart'; import '../components/login_button.dart'; @@ -37,7 +38,7 @@ class _RegistrationScreenState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - e.toString() ?? "", + e.toString(), style: GoogleFonts.plusJakartaSans( color: Colors.white, fontWeight: FontWeight.w400, @@ -51,8 +52,15 @@ class _RegistrationScreenState extends State { } signInWithGoogle() async { - await MyApp.userViewModel.signInWithGoogle(); - //Navigator.pushNamed(context, '/explanation'); + try { + await MyApp.userViewModel.signInWithGoogle(); + } on UserException catch (e) { + if (e.code == 'user-created') { + Navigator.pushNamed(context, '/explanation'); + } else if (e.code == 'user-already-exist') { + Navigator.pushNamed(context, '/feed'); + } + } } @override diff --git a/Sources/justMUSIC/lib/services/AuthService.dart b/Sources/justMUSIC/lib/services/AuthService.dart index 642c682..59411f0 100644 --- a/Sources/justMUSIC/lib/services/AuthService.dart +++ b/Sources/justMUSIC/lib/services/AuthService.dart @@ -3,44 +3,52 @@ import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:google_sign_in/google_sign_in.dart'; +import 'package:justmusic/exceptions/user_exception.dart'; import '../main.dart'; class AuthService { - register(String pseudo, String email, String password) async { + Future addUserToFirestore( + UserCredential userCredential, String pseudo, String email) async { + var token; + if (!kIsWeb) { + token = await FirebaseMessaging.instance.getToken(); + } else { + token = "empty"; + } + + String uniqueId = await generateUniqueId(pseudo); + + final user = { + "mail": email, + "pseudo": pseudo, + "unique_id": uniqueId, + "followed": [], + "nbCapsules": 0, + "followers": [], + "token_notify": token, + "musics_likes": [], + "picture": + "https://firebasestorage.googleapis.com/v0/b/justmusic-435d5.appspot.com/o/justMusicDefaultImage.png?alt=media&token=020d0fcb-b7df-4d4d-b380-e99597293fcc" + }; + + try { + await MyApp.db + .collection("users") + .doc(userCredential.user?.uid) + .set(user); + print("User Added"); + } catch (error) { + print("Failed to add user: $error"); + } + } + + Future register(String pseudo, String email, String password) async { try { - var token; final data = await FirebaseAuth.instance.createUserWithEmailAndPassword( email: email, password: password, ); - - if (kIsWeb) { - token = "empty"; - } else { - token = await FirebaseMessaging.instance.getToken(); - } - - String uniqueId = await generateUniqueId(pseudo); - - final user = { - "mail": email, - "pseudo": pseudo, - "unique_id": uniqueId, - "followed": [], - "nbCapsules": 0, - "followers": [], - "token_notify": token, - "musics_likes": [], - "picture": - "https://firebasestorage.googleapis.com/v0/b/justmusic-435d5.appspot.com/o/justMusicDefaultImage.png?alt=media&token=020d0fcb-b7df-4d4d-b380-e99597293fcc" - }; - - MyApp.db - .collection("users") - .doc(data.user?.uid) - .set(user) - .then((value) => print("User Added")) - .catchError((error) => print("Failed to add user: $error")); + await addUserToFirestore(data, pseudo, email); } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { throw ('Mot de passe trop court'); @@ -55,15 +63,26 @@ class AuthService { signInWithGoogle() async { final GoogleSignInAccount? gUser = await GoogleSignIn().signIn(); - final GoogleSignInAuthentication gAuth = await gUser!.authentication; - final credential = GoogleAuthProvider.credential( accessToken: gAuth.accessToken, idToken: gAuth.idToken, ); - return await FirebaseAuth.instance.signInWithCredential(credential); + final userCredential = + await FirebaseAuth.instance.signInWithCredential(credential); + final user = + await MyApp.db.collection("users").doc(userCredential.user?.uid).get(); + + if (!user.exists) { + await addUserToFirestore( + userCredential, + userCredential.user?.displayName ?? "user", + userCredential.user?.email ?? ""); + throw UserException("user-created", "L'utilisateur vien d'être créé"); + } + + throw UserException("user-already-exist", "L'utilisateur existe déjà"); } Future generateUniqueId(String pseudo) async { @@ -100,8 +119,12 @@ class AuthService { } } - void signOut() async { + signOut() async { + final GoogleSignIn googleSignIn = GoogleSignIn(); await FirebaseAuth.instance.signOut(); + if (await googleSignIn.isSignedIn()) { + await googleSignIn.signOut(); + } } Future delete() async { diff --git a/Sources/justMUSIC/lib/view_model/UserViewModel.dart b/Sources/justMUSIC/lib/view_model/UserViewModel.dart index adac733..61173f0 100644 --- a/Sources/justMUSIC/lib/view_model/UserViewModel.dart +++ b/Sources/justMUSIC/lib/view_model/UserViewModel.dart @@ -80,7 +80,13 @@ class UserViewModel { } signInWithGoogle() async { - await _authService.signInWithGoogle(); + try { + await _authService.signInWithGoogle(); + await updateUserCurrent(); + } catch (e) { + print(e); + rethrow; + } } Future> getUsersByUniqueId(String uniqueId) async { @@ -105,12 +111,12 @@ class UserViewModel { } } - logout() { - _authService.signOut(); + logout() async { + await _authService.signOut(); } - delete() { - _authService.delete(); + delete() async { + await _authService.delete(); } bool isFriend(String id) {