How to make sure user is logged in using Firebase and Flutter - firebase

I want to check if the user is logged in then go to home page, if it is not logged in then go to login page.
The problem I am facing is, after I signed up, if I refresh it directly goes to home page even without logging in. I guess this is because after signing up (createUserWithEmailAndPassword) there is a current user. And I am checking that as the if condition.
Below shown is my code. Can anyone please help me? I want my user to go to home page only after logging in, not after signing up.
doo(context) async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
if (user == null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(),
),
);
}
}

One way you can try to do this is by signing-out the user immediately after the sign-up, something like this..
FirebaseUser user;
user = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
);
await FirebaseAuth.instance.signOut();
//then proceed with the logic for navigating to either LoginPage() or HomePage()
//..

You can check SharedPreferences. You can set value string in SharedPreferences and when user is login and in conditions check
if (user == null && sharedPrefs.getString('isLogin') != '')

Related

Flutter/Firebase problem with logout after email user verification

i'am building an app with flutter and firebase..(I'am new in flutter development). What I did is a system where the user can signup and signin. Once the user signup an email verification is sent to the user email account. I'll try to put all the step below
signup
redirect to email verification widget..(this check if user has verified the email with a Timer) if yes, navigator push new Page (HomePage).
the main logic is this one.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "My App Name",
debugShowCheckedModeBanner: false,
home: AuthService().handleAuth(),
theme: ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity
),
);
}}
this is what the AuthService().handleAuth() does:
handleAuth() {
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
print(snapshot.hasData);
if (snapshot.hasData && emailVerificationNeeded() == false) {
return HomePage();
}
return LoginPage();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
},
);
}
The verifyPage check with a timer if user has verified the email
Future<void> checkEmailVerified() async {
user = auth.currentUser!;
await user.reload();
if (user.emailVerified) {
timer.cancel();
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) => HomePage()));
}
}
Until here everything work fine! Now for a test purpose in the HomePage there is a button that fire the following action
FirebaseAuth.instance.signOut();
if I click in the button and I logout the user still remain in the home page instead of going back to the LoginPage. This problem happen only the first time when the user is redirected in the Verification page. On all the other case if I'm verified and I'm logged in, once I click on the Logout button the user is redirect back to the Login page.
Any ideas?
Thank you all
The StreamBuilder isn't reacting to changes because you've navigated to another route.
You can use FirebaseAuth.instance.userChanges instead of FirebaseAuth.instance.authChanges as authChanges only "notifies about changes to the user's sign-in state (such as sign-in or sign-out)." while userChanges listens to different states such as sign-in, sign-out, different user & token refresh.
And then you can call FirebaseAuth.instance.currentUser!.reload(); when you verify the user which removes the need to navigate to the HomePage manually.
So when you call FirebaseAuth.instance.signOut, it automatically signs you out.
Code Changes:
Update handleAuth to this:
handleAuth() {
return StreamBuilder(
stream: FirebaseAuth.instance.userChanges(),
...
);
}
Update checkEmailVerified to this:
Future<void> checkEmailVerified() async {
user = auth.currentUser!;
await user.reload();
if (user.emailVerified) {
timer.cancel();
}
}

Firebase sign out is not working in flutter application

I am implementing the the firebase sign out in flutter application based on the provider id which is not working at all right now.
I am executing the below code.
FirebaseAuth _auth = FirebaseAuth.instance;
if(_auth.currentUser != null) {
User user = _auth.currentUser;
var userset = user.providerData[0].providerId;
if(userset == 'google.com'){
print('google provider');
await GoogleSignIn().signOut();
//Firebase sign out navigation to the login page
} else {
_auth.signOut();
//Firebase sign out navigation to the login page
print('sign out done successfully');
}
}
The code is executed, but the auth state maintains the user logged in status, whether sign in or sign out and upon reloading the app it does not go to the login page and it goes to the home page.
How should I check whether the sign out was successful or not?
Auth State handling in app when the app reloads
Widget _handleAuth() {
return StreamBuilder<User>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (BuildContext context, snapshot) {
return (!snapshot.hasData)
? LoginPage()
: HomePage();
},
);
}
You need to also sign out from firebase even if you are using google provider:
if(userset == 'google.com'){
print('google provider');
await GoogleSignIn().signOut();
_auth.signOut();
}

Flutter Firebase check if user is signed in anonymously

I am giving Users the option to sign in via Email and Password or anonymously.
Creating and signing in the User with Email and Password works fine, but I am having problems with displaying different contents for anonymously signed in users.
This is how I create them:
final _auth = FirebaseAuth.instance;
// Create Anonymous User
Future signInAnonymously() {
// return _auth.signInAnonymously();
_auth.signInAnonymously();
}
If a user chooses to get into the app anonymously in the Auth Form, I trigger following function:
Future submitAnon() async {
await signInAnonymously();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(),
),
);
}
I am using a Future Builder / Stream to listen to Auth Changes in my main.dart:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
return FutureBuilder(
// Initialize FlutterFire:
future: _initialization,
builder: (context, appSnapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'myapp',
home: appSnapshot.connectionState != ConnectionState.done
? SplashScreen()
: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (ctx, userSnapshot) {
if (userSnapshot.connectionState ==
ConnectionState.waiting) {
return SplashScreen();
}
if (userSnapshot.hasData) {
return HomeScreen();
}
return AuthScreen();
}),
);
});
}
}
What I tried was passing a "isAnon=true" boolean to HomeScreen in submitAnon() but once the user re-opens the app, he is getting into the app from main.dart, where all the users that signed-up via email also get in. Is there a good way to check inside the App if the User is authenticated anonymously to build my widgets depending on that? e.g. showing Authentication Options instead of actual content that is only directed to e-mail&passsword users?
I think it's too late but here's the simplest way:
FirebaseAuth.instance.currentUser!.isAnonymous // returns a bool
To check if a user signed in to firebase anonymously. Firebase User class returned has an isAnonymous() method that returns true if the user signs in anonymously.
In your code, you can get a firebase user from the streambuilder snapshot. and check if isAnonymous is true. Like below:
StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (ctx, userSnapshot)
{
User user = userSnapshot.data;
print('Is user anonymous: ${user.isAnonymous}');
},
);
should print
'Is user anonymous: true'
if the user signs in anonymously and userSnapshot is not null.
I would propose you use the SharedPreferences library in order to keep track of of whether the user is anonymous or not. You should simply be able to store the isAnon in Shared Preferences to track whether the user is anonymous or not and from there you could use the Provider library to retrieve the isAnon value throughout the app. With a combinations of these two things you should be able to create the behavior you are looking for.
Please let me know if I misunderstood your question or need a further explanation!

How to Login and Register CORRECTLY in Firebase with Flutter?

I have this app that do login and register with firebase + email verification but not very effecient as when the user register if he entered the username, email , password, ..... It register even if the email is wrong so I searched and found a solutoin which is email varification in firebase but the problem is that if the user didn't verify, Firebase register it and he can login (even if the email is not valid), so any ideas ? also new to flutter.
My SignUp code Which I excute in the signup page:
static Future signup(String email, String password, BuildContext ctx) async {
String emessage;
if (email == '' || password == '') {
emessage = 'Please Provide Valid Email And Password';
} else {
emessage = 'An Error Occurred. Please Try Again Later.';
}
try {
final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
))
.user;
user.sendEmailVerification();
return user.uid;
} catch (e) {
showDialog(
context: ctx,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: Text(emessage),
actions: [
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text('Ok'),
),
],
);
});
}
}
The firebase docs of createUserWithEmailAndPassword do not list any parameters to force upfront email verification.
You could
Use signInWithEmailLink and add a password after the first login.
Disallow users without a verified email address to access content in your app -- just like you do it with unauthenticated users.

How to implement a proper log out method in my flutter app?

FirebaseAuth firebaseAuth;
_signOut() async {
await firebaseAuth.signOut();}
onTap: () {
Navigator.of(context).pop();
_signOut();
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => new LoginPage()));
},
This is the way I implemented it in my code, but I have a problem when I want to register a new user after logging out from the current user. After I complete the registration form that I created, in my firebase it doesn't create a new user, but it just updates the former user info, like Name, Surname etc. To create a new user I need to restart the app.I think the problem is with the sign out procedure, I am not sure.
You should have a root page that would take the following.
#override
Widget build(BuildContext context) {
switch (_authStatus){
case AuthStatus.notSignedIn:
return new LoginPage(auth: widget.auth, onSignedIn:_signedIn ,);
case AuthStatus.signedIn:
return new NifesHome(
auth: widget.auth,
onSignedOut: _signedOut,
);
}
}
what this does is if the user is signed out automatically he is taken to the root page which confirms the status of the user and redirects him to the login page.

Resources