HaKim
HaKim

Reputation: 287

adding authenticated user to firestore 'users' collection flutter

I am stuck at the adding an authenticated user to a firestore 'users' collection.

Unhandled Exception: [cloud_firestore/not-found] Some requested document 
was not found.

User signs in via Google:

class GoogleSignInProvider extends ChangeNotifier {
final GoogleSignIn _googleSignIn = GoogleSignIn();

GoogleSignInAccount _user;

GoogleSignInAccount get user => _user;

AuthService auth = AuthService();

Future googleSignIn(BuildContext context) async {
try {
  final googleUser = await _googleSignIn.signIn();
  if (googleUser == null) return;

  _user = googleUser;

  final googleAuth = await googleUser.authentication;

  final AuthCredential credential = GoogleAuthProvider.credential(
      idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);

  await FirebaseAuth.instance.signInWithCredential(credential);
  } catch (e) {
  print(e.toString());
}

final User currentUser = FirebaseAuth.instance.currentUser;
if (currentUser != null)
usersRef.add(currentUser.uid);

Navigator.of(context).pushReplacement(
    CupertinoPageRoute(builder: (_) => TabScreen()));
notifyListeners();
}

However, no matter what and how I tried the authentication firebase id is not added to the usersRef (the firestore collection). How do I fix it?

My firestore rules are:

match /users/{userId}/{documents=**} {
  allow read: if request.auth.uid != null;
  allow write, update, create, delete: if isOwner(userId);
}
 function isOwner(userId) {
return request.auth.uid == userId;
}

Help appreciated very much!

Upvotes: 1

Views: 1115

Answers (2)

HaKim
HaKim

Reputation: 287

so this solved my issue:

final User currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser != null)
    await usersRef.doc(currentUser.uid).set({'email': 
user.email, 'username': user.displayName, 'photoUrl': 
user.photoURL});

I think, I was overthinking it..

Thanks, ppl for the directions and help!

Upvotes: 3

Peter Obiechina
Peter Obiechina

Reputation: 2835

Do this.

Map data = {};
FirebaseFirestore.instance
    .collection('usersCollection')
    .doc(currentUser.uid)
    .set(data);

in place of usersRef.add(currentUser.uid);

Use set when you have doc id and use add when you want an auto generated id.

Upvotes: 0

Related Questions