Created
May 5, 2020 13:20
-
-
Save oluwaseye/a39b06296d019674599ff8ef54a8bac0 to your computer and use it in GitHub Desktop.
Updates for Firebase Google signin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:firebase_auth/firebase_auth.dart'; | |
import 'package:google_sign_in/google_sign_in.dart'; | |
import 'package:cloud_firestore/cloud_firestore.dart'; | |
import 'package:rxdart/rxdart.dart'; | |
class AuthService { | |
final GoogleSignIn _googleSignIn = GoogleSignIn(); | |
final FirebaseAuth _auth = FirebaseAuth.instance; | |
final Firestore _db = Firestore.instance; | |
Stream<FirebaseUser> user; // firebase user | |
Stream<Map<String, dynamic>> profile; // custom user data in Firestore | |
PublishSubject loading = PublishSubject(); | |
// constructor | |
AuthService() { | |
user = _auth.onAuthStateChanged; | |
profile = user.switchMap((FirebaseUser u) { | |
if (u != null) { | |
return _db | |
.collection('users') | |
.document(u.uid) | |
.snapshots() | |
.map((snap) => snap.data); | |
} else { | |
return Stream.value({}); | |
} | |
}); | |
} | |
Future<FirebaseUser> googleSignIn() async { | |
try { | |
loading.add(true); | |
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn(); | |
GoogleSignInAuthentication googleAuth = | |
await googleSignInAccount.authentication; | |
final AuthCredential credential = GoogleAuthProvider.getCredential( | |
accessToken: googleAuth.accessToken, | |
idToken: googleAuth.idToken, | |
); | |
final AuthResult authResult = | |
await _auth.signInWithCredential(credential); | |
FirebaseUser user = authResult.user; | |
updateUserData(user); | |
print("user name: ${user.displayName}"); | |
loading.add(false); | |
return user; | |
} catch (error) { | |
return error; | |
} | |
} | |
void updateUserData(FirebaseUser user) async { | |
DocumentReference ref = _db.collection('users').document(user.uid); | |
return ref.setData({ | |
'uid': user.uid, | |
'email': user.email, | |
'photoURL': user.photoUrl, | |
'displayName': user.displayName, | |
'lastSeen': DateTime.now() | |
}, merge: true); | |
} | |
Future<String> signOut() async { | |
try { | |
await _auth.signOut(); | |
return 'SignOut'; | |
} catch (e) { | |
return e.toString(); | |
} | |
} | |
} | |
// TODO refactor global to InheritedWidget | |
final AuthService authService = AuthService(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment