Charles Jr
Charles Jr

Reputation: 9119

How to successfully log in and out of Firebase using Flutter?

I've had a problem for a while that I think I've narrowed down to not completely logging in and out of Firebase; this has led to users not always being able to access database nodes. I have a main screen that reads whether my app has a null Firebase.instance.currentuser or not by reading the app's setState((){}); like so...

 Future <Null> logout() async {

    await FirebaseAuth.instance.signOut();

    setState((){
      FirebaseAuth.instance.currentUser;
    });
  }

If currentUser == null the same page, which is my main.dart page, lodes with different build settings. On my login page I'm logging in users like so...

Future<Null> _google() async {
try {
  await _googleSignIn.disconnect();
  GoogleSignInAccount googleUser = await _googleSignIn.signIn();
  GoogleSignInAuthentication googleAuth = await googleUser.authentication;
  await FirebaseAuth.instance.signInWithGoogle(
      idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);

  Navigator.pushNamed(context, '/menu');
} catch (error) {
  print(error);
}

}

       Future<Null> _loginButton() async {

await FirebaseAuth.instance.signOut();
await _googleSignIn.disconnect();

_email = _emailController.text.toString().replaceAll(" ", "");
  _password = _passController.text.toString().replaceAll(" ", "");
  //_username = _nameController.text.toString().replaceAll(" ", "");
  if (_email != null && _password != null) {
    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: _email, password: _password);
      final userid = FirebaseAuth.instance.currentUser.uid;

    } catch (error) {
      print(error.toString());
    }
  } else {

  }

}

All the flows work as expected and running FirebaseAuth.instance.currentuser.uid returns the expected User ID, but its as if the database is only reading the original user only.

Security Rules...

{
  "rules": {
    "$user_id": {
      ".write": true,
      ".read": true
    }
  },
}

Upvotes: 0

Views: 850

Answers (1)

Fabio Veronese
Fabio Veronese

Reputation: 8360

It looks you have a flaw in your security rules. At the moment you enable any user to edit and read the table {$user_id}.

If you mean to restrict access to logged in users, whose id match a particular table I suggest what follows:

"users": {
  "$uid": {
    ".read": "auth != null && auth.uid == $uid",
    ".write": "auth != null && auth.uid == $uid",
      }
   }

or similar, where you force user auth (auth!=null) and the fact that each user can access and edit the entry of users named with its own uid (auth.uid == $uid)

Upvotes: 1

Related Questions