How do I sign out form Google Auth from Flutter? - firebase

I am able to successfully - sign in a user using firebase using both Google and Facebook:
firebase_auth.dart, flutter_facebook_login.dart, google_sign_in.dart
I am able to sign out the firebase user using this function from a different widget:
Future<void>_signOut() async {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
return _firebaseAuth.signOut();
}
Now this is a catch-all for both types of logins, Google and Facebook, how can I determine if the user is a Google auth user in which case I can execute
final GoogleSignIn _googleSignIn = new GoogleSignIn();
...
_googleSignIn.signOut();
Additionally, if my sign out function is in a different widget and file how can I pass the GoogleSignIn object to be referenced to sign out?

There is bool Future type of method for GoogleSignIn and FacebookSignIn.
final facebookLogin = FacebookLogin();
final GoogleSignIn googleSignIn = new GoogleSignIn();
googleSignIn.isSignedIn().then((s) {});
facebookLogin.isLoggedIn.then((b) {});
you will get true or false using this you can use sign out method.
and for your 2nd problem of the solution is to create a global object for GoogleSignIn and facebook as well.
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
final facebookLogin = FacebookLogin();
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = new GoogleSignIn();
Future<FirebaseUser> signInWithGoogle() async {
// Attempt to get the currently authenticated user
GoogleSignInAccount currentUser = _googleSignIn.currentUser;
if (currentUser == null) {
// Attempt to sign in without user interaction
currentUser = await _googleSignIn.signInSilently();
}
if (currentUser == null) {
// Force the user to interactively sign in
currentUser = await _googleSignIn.signIn();
}
final GoogleSignInAuthentication googleAuth =
await currentUser.authentication;
// Authenticate with firebase
final FirebaseUser user = await firebaseAuth.signInWithGoogle(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
);
assert(user != null);
assert(!user.isAnonymous);
return user;
}
Future<Null> signOutWithGoogle() async {
// Sign out with firebase
await firebaseAuth.signOut();
// Sign out with google
await googleSignIn.signOut();
}

Related

FirebaseUser not an existing class | authentication errors [duplicate]

I'm new to Flutter. I have an Issue with Firebase Auth/ Google Auth
The FirebaseUser is not defined
Code:
FirebaseAuth _auth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn();
Future<FirebaseUser> currentUser() async { // The Issue is here in the Future<>
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.getCredential(
idToken: authentication.idToken, accessToken: authentication.accessToken);
final AuthResult authResult = await _auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user; // and here as I can't define this FirebaseUser object to return
return user;
}
Pubspec.yml
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
firebase_auth: ^0.18.0
location: ^3.0.2
page_transition: ^1.1.6
google_sign_in: ^4.5.1
flutter_facebook_login: ^3.0.0
firebase_database: ^4.0.0
I also face the same issue with AuthResult
final AuthResult authResult = await _auth.signInWithCredential(credential);
Starting from Version firebase_auth 0.18.0:
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredential. Therefore change your code to the following:
Future<User> currentUser() async {
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.credential(
idToken: authentication.idToken,
accessToken: authentication.accessToken);
final UserCredential authResult =
await _auth.signInWithCredential(credential);
final User user = authResult.user;
return user;
}
FirebaseUser changed to User
AuthResult changed to UserCredential
GoogleAuthProvider.getCredential() changed to GoogleAuthProvider.credential()
onAuthStateChanged which notifies about changes to the user's sign-in state was replaced with authStateChanges()
currentUser() which is a method to retrieve the currently logged in user, was replaced with the property currentUser and it no longer returns a Future<FirebaseUser>.
Example of the above two methods:
FirebaseAuth.instance.authStateChanges().listen((event) {
print(event.email);
});
And:
var user = FirebaseAuth.instance.currentUser;
print(user.uid);
Deprecation of UserUpdateInfo class for firebaseUser.updateProfile method.
Example:
Future updateName(String name, FirebaseUser user) async {
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = name;
await user.updateProfile(userUpdateInfo);
await user.reload();
}
now
import 'package:firebase_auth/firebase_auth.dart' as firebaseAuth;
Future updateName(String name, auth.User firebaseUser) async {
firebaseUser.updateProfile(displayName: name);
await firebaseUser.reload();
}
Since firebase_auth 0.18.0, the class FirebaseUser was changed to User
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredentail. Therefore change FirebaseUser to User
The class FirebaseUser was changed to User
try this way
_registerUser() async {
try {
final User? user =
(await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailCtrl.text,
password: passCtrl.text,
))
.user;
FirebaseFirestore.instance.collection('users').doc().set({
'name': nameCtrl.text,
'uid': user!.uid,
'email': user.email,
'isEmailVerified': user.emailVerified, // will also be false
'photoUrl': user.photoURL, // will always be null
});
print("Created");
} catch (e) {
print(e.toString());
}
}
Run
flutter pub get
Then rebuild your app.
This can be your signin function with email and password as of Sept 2020.Initialze app is a new introduced method we must at least call once before we use any other firebase methods.
Future<void> signin() async {
final formState = _formkey.currentState;
await Firebase.initializeApp();
if (formState.validate()) {
setState(() {
loading = true;
});
formState.save();
try {
print(email);
final User user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password))
.user;
} catch (e) {
print(e.message);
setState(() {
loading = false;
});
}
}
}

Undefined class 'FirebaseUser'

I'm new to Flutter. I have an Issue with Firebase Auth/ Google Auth
The FirebaseUser is not defined
Code:
FirebaseAuth _auth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn();
Future<FirebaseUser> currentUser() async { // The Issue is here in the Future<>
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.getCredential(
idToken: authentication.idToken, accessToken: authentication.accessToken);
final AuthResult authResult = await _auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user; // and here as I can't define this FirebaseUser object to return
return user;
}
Pubspec.yml
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
firebase_auth: ^0.18.0
location: ^3.0.2
page_transition: ^1.1.6
google_sign_in: ^4.5.1
flutter_facebook_login: ^3.0.0
firebase_database: ^4.0.0
I also face the same issue with AuthResult
final AuthResult authResult = await _auth.signInWithCredential(credential);
Starting from Version firebase_auth 0.18.0:
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredential. Therefore change your code to the following:
Future<User> currentUser() async {
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.credential(
idToken: authentication.idToken,
accessToken: authentication.accessToken);
final UserCredential authResult =
await _auth.signInWithCredential(credential);
final User user = authResult.user;
return user;
}
FirebaseUser changed to User
AuthResult changed to UserCredential
GoogleAuthProvider.getCredential() changed to GoogleAuthProvider.credential()
onAuthStateChanged which notifies about changes to the user's sign-in state was replaced with authStateChanges()
currentUser() which is a method to retrieve the currently logged in user, was replaced with the property currentUser and it no longer returns a Future<FirebaseUser>.
Example of the above two methods:
FirebaseAuth.instance.authStateChanges().listen((event) {
print(event.email);
});
And:
var user = FirebaseAuth.instance.currentUser;
print(user.uid);
Deprecation of UserUpdateInfo class for firebaseUser.updateProfile method.
Example:
Future updateName(String name, FirebaseUser user) async {
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = name;
await user.updateProfile(userUpdateInfo);
await user.reload();
}
now
import 'package:firebase_auth/firebase_auth.dart' as firebaseAuth;
Future updateName(String name, auth.User firebaseUser) async {
firebaseUser.updateProfile(displayName: name);
await firebaseUser.reload();
}
Since firebase_auth 0.18.0, the class FirebaseUser was changed to User
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredentail. Therefore change FirebaseUser to User
The class FirebaseUser was changed to User
try this way
_registerUser() async {
try {
final User? user =
(await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailCtrl.text,
password: passCtrl.text,
))
.user;
FirebaseFirestore.instance.collection('users').doc().set({
'name': nameCtrl.text,
'uid': user!.uid,
'email': user.email,
'isEmailVerified': user.emailVerified, // will also be false
'photoUrl': user.photoURL, // will always be null
});
print("Created");
} catch (e) {
print(e.toString());
}
}
Run
flutter pub get
Then rebuild your app.
This can be your signin function with email and password as of Sept 2020.Initialze app is a new introduced method we must at least call once before we use any other firebase methods.
Future<void> signin() async {
final formState = _formkey.currentState;
await Firebase.initializeApp();
if (formState.validate()) {
setState(() {
loading = true;
});
formState.save();
try {
print(email);
final User user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password))
.user;
} catch (e) {
print(e.message);
setState(() {
loading = false;
});
}
}
}

When I log out of application and again login it takes me to homepage automatically without asking for choosing an account

I have created login application, using flutter and firebase.
i am doing google login. I have 2 pages login.dart and homepage.dart where everything happens. When i click on login button it asks for choose an account and take me to homepage, but when i logout, and again try to login it takes me automatically to homepage, but i want it to ask again for choosing an account.
I have created signout() function in loginpage itself, where I have written the code for the rest of the authentication, but when I call this function in homepage.dart in logout button, it wont come.
Code for Login Authentication in loginpage.dart
class _LoginPageState extends State<LoginPage> {
String _email;
String _password;
//google sign in
final GoogleSignIn googleSignIn= GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<FirebaseUser> _signIn() async{
//GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
GoogleSignInAccount googleUser = await googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
);
final FirebaseUser user = await _auth.signInWithCredential(credential);
print("User Name: ${user.displayName}");
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await _auth.currentUser();
assert(user.uid == currentUser.uid);
Navigator.of(context).pushReplacementNamed('/homepage');
}
Future<void> signOut() async {
return googleSignIn.signOut();
}
code for log out button in homepage.dart
MaterialButton(
onPressed: () {
signOut
FirebaseAuth.instance.signOut().then((value) {
Navigator.of(context).pushReplacementNamed('/landingpage');
})
.catchError((e){
print(e);
});
},
child: Text('Log Out'),
)
Please Help me out

is there any function in firebase Google Auth package for flutter to find the date of the creation of user?

i want to get the user creation timestamp, is there any way to do this?
im using google sign in auth.
Any help is appreciated!
Edit: i cant find the user creation timestamp when printing the whole user
Edit 2: Code I am using for authentication:
GoogleSignInAccount currentUser;
final GoogleSignIn googleSignIn = GoogleSignIn();
final FirebaseAuth auth = FirebaseAuth.instance;
Future<FirebaseUser> signIn() async {
GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
GoogleSignInAuthentication gSA = await googleSignInAccount.authentication;
FirebaseUser user = await auth.signInWithGoogle(
idToken: gSA.idToken, accessToken: gSA.accessToken);
print('Signed In as ${user.displayName}');
return user;
}
You can get the creation timestamp in epoch format with:
user.metadata.creationTime
See:
metadata

How to get current user email address FirebaseAuth/Flutter

I want to get the email of the currently signed in user, but I can't seem to find a way to do it.
I presume it should be something similar to:
FirebaseAuth.instance.currentUser().getEmail(); //The .getEmail() part is made up
Assuming you are using the Firebase Auth package:
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<FirebaseUser> _handleSignIn() async {
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
FirebaseUser user = await _auth.signInWithGoogle(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken, );
// get email here
print("signed in " + user.email);
return user; }
And handling the login:
_handleSignIn() .then((FirebaseUser user) => print(user)) .catchError((e) => print(e));
It is very easy to do... you just have to get the current user with FirebaseAuth.instance.currentUser and get the email by adding .email
You will get the email of the current user
In order to get the signed-in user information, you should first call the currentUser() method, and then call for the email and save it into a string variable, like this:
final _auth = FirebaseAuth.instance;
String userEmail;
void getCurrentUserEmail() async {
final user =
await _auth.currentUser().then((value) => userEmail = value.email);
}
Another way of doing this is by saving currentUser() into a variable then fetching for related information such as email or phoneNumber by typing . and choosing any value you want ,
like this:
final _auth = FirebaseAuth.instance;
dynamic user;
String userEmail;
String userPhoneNumber;
void getCurrentUserInfo() async {
user = await _auth.currentUser();
userEmail = user.email;
userPhoneNumber = user.phoneNumber;
}

Resources