Created
July 10, 2020 14:52
-
-
Save Runman44/028dff4138a804fb73dbe7387d35ba7e to your computer and use it in GitHub Desktop.
Authentication Service for Firebase/Flutter in Dart
This file contains hidden or 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
class AuthService { | |
final FirebaseAuth _auth = FirebaseAuth.instance; | |
final GoogleSignIn _googleSignIn = GoogleSignIn(); | |
Stream<User> get user { | |
return _auth.onAuthStateChanged.map(_userFromFirebaseUser); | |
} | |
User _userFromFirebaseUser(FirebaseUser user) { | |
return user != null ? User(id: user.uid, name: user.displayName, email: user.email) : null; | |
} | |
Future<User> signInWithGoogle() async { | |
try { | |
final GoogleSignInAccount googleSignInAccount = | |
await _googleSignIn.signIn(); | |
final GoogleSignInAuthentication googleSignInAuthentication = | |
await googleSignInAccount.authentication; | |
final AuthCredential credential = GoogleAuthProvider.getCredential( | |
accessToken: googleSignInAuthentication.accessToken, | |
idToken: googleSignInAuthentication.idToken, | |
); | |
final AuthResult authResult = | |
await _auth.signInWithCredential(credential); | |
final FirebaseUser user = authResult.user; | |
assert(!user.isAnonymous); | |
assert(await user.getIdToken() != null); | |
final FirebaseUser currentUser = await _auth.currentUser(); | |
assert(user.uid == currentUser.uid); | |
print(user); | |
return _userFromFirebaseUser(user); | |
} catch (e) { | |
return null; | |
} | |
} | |
Future signOutGoogle() async { | |
try { | |
return await _auth.signOut(); | |
} catch (e) { | |
print(e.toString()); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment