Firestore onAuthStateChanged and users in a subcollection - firebase

I'm building an app where users can authenticate, in Firestore I save extra data from that user (username, age).
Now in my app, users are coupled to events, I chose to have an events collection, which has a users subcollection.
I'm using the firebase onAuthStateChanged listener to see when my user has logged in. However the issue I'm not facing is, to get the firestore data for my user, I need to know which event this user belongs to, which is of course, data I do not have access to at the time the user signs in, for example:
const onAuthStateChangedPromise = new Promise((resolve, reject) => {
auth.onAuthStateChanged(async firebaseUser => {
if (firebaseUser !== null) {
const user = await getDoc(doc(db, 'events/${eventId}/users', id))
useAuth().user = user
return resolve(user)
}
return resolve(null)
}, err => {
reject(err)
})
})
In the example above, to get my user's data, I need to know the eventId, which I can not possible determine from the authenticated user.
I'm wondering how to achieve this?
I could save the eventId in localStorage as soon as the user registers, but that can cause issue's, since the complete app then relies on something being set on localStorage

The typical way to solve this would be to add the UID of the user in a field inside the events/${eventId}/users documents and then use a collection group query across all users collections. This will give you a list of all event/users docs for that user.
To find the event for such an event/user doc, you first take the DocumentReference for the DocumentSnapshot and then go up the parent chain twice to get to the parent event document.

Related

Unique field in Firestore database + Flutter

I'm trying to implement a normal authentication system in my app, but I'd like to create a new field for each user that is the "uniqueName" so users can search and add each other in their friends list. I was thinking of adding a textField in the signup form for the uniqueName and updating my User class adding a new String in this way:
class User {
String email;
String name;
String uniqueName;
String userID;
String profilePictureURL;
String appIdentifier;
...
}
Now, since I have this method for the email&password signup:
static firebaseSignUpWithEmailAndPassword(String emailAddress,String password,File? image,String name,) async {
try {
auth.UserCredential result = await auth.FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: emailAddress, password: password);
String profilePicUrl = '';
if (image != null) {
await updateProgress('Uploading image, Please wait...');
profilePicUrl =
await uploadUserImageToFireStorage(image, result.user?.uid ?? '');
}
User user = User(
email: emailAddress,
name: name,
userID: result.user?.uid ?? '',
profilePictureURL: profilePicUrl);
String? errorMessage = await firebaseCreateNewUser(user);
if (errorMessage == null) {
return user;
} else {
return 'Couldn\'t sign up for firebase, Please try again.';
}
}
how do I have to modify it in order to add this new field in the registration? Since I have to check that the uniqueName insert by the user is effectively unique before creating a new user in the database, what can I do?
Furthermore, I think that it would be cool if this check is made concurrently to the filling of the form, how can I do it? (this is not necessary)
Thanks everyone for the answers
You have to save your users in a collection, then check if uniqueName already exists in the collection. If it exists, return error.
Then when a new user account is created, save the uniqueName.
// this function checks if uniqueName already exists
Future<bool> isDuplicateUniqueName(String uniqueName) async {
QuerySnapshot query = await FirebaseFirestore.instance
.collection('PATH_TO_USERS_COLLECTION')
.where('uniqueName', isEqualTo: uniqueName)
.get();
return query.docs.isNotEmpty;
}
// call the above function inside here.
static firebaseSignUpWithEmailAndPassword(String emailAddress, String password, File? image, String name,) async {
if (await isDuplicateUniqueName(name)) {
// UniqueName is duplicate
// return 'Unique name already exists';
}
// ... the rest of your code. Go ahead and create an account.
// remember to save the uniqueName to users collection.
I suggest doing the following steps:
Create your own users collection (for example users) in Firestore, which you might have done already. (I don't think that User is a good class name, since Firebase Authentication is using the same name. Try MyUser or something.)
Add authentication triggers that will ensure that whenever a Firebase user is added or deleted, it will also be added to or deleted from users collection, use Firebase uid as identifier.
Create a solution to check whether a uniqueName already exists in users collection. You can use a Firestore query, but in this case you have to allow unauthenticated access to read users, at least uniqueName field. (Since the user is not authenticated yet at this point.) A Firebase Cloud Function is another option.
When users enter their desired uniqueName, run the check before creating Firebase user. You can do it when user enters this or when you start the signup process.
If uniqueName is unique, you can try to create Firebase user. Be aware, this step can also fail (for example e-mail name taken etc.). Your users document will be created by the authentication trigger you set up in step 2.
Finally, you have to store this uniqueName in users collection. At this point you will have uid of the newly created Firebase user, so you can use Firestore set command with merge option set to true, so you don't overwrite other data.
It is important to note that you can't guarantee that the Firebase trigger already created the new document in users by the time you arrive to point 6, it is very likely that the trigger is still working or not even started yet. That's why you have to use set both in the authentication trigger and in your own code that sets uniqueName: which "arrives" first, will create the document, and the second will update it.
Also, for the same reason, you have to allow inserts and updates into users collection with Firestore rules. This might sound a little scary, but keep in mind that this is only your own user list to keep track of uniqueName, and authentication is based not on this, but on Firebase Authentication's user management which is well protected.
Last comment: this is not a 100% solution. It is quite unlikely, but theoretically can happen, that some else reserves a uniqueName between you check whether it's unique and the user is actually created. To mitigate this, it is a good idead to make the check just before Firebase user is created. Even in this case a slight chance remains for duplicates.

how to get data from cloud firestore where user.uid equal to document id in flutter?

I am Having this profile screen which shows users info.
after user authenticated I am storing data in cloud firestore with document id is equal to user-id.
Now, I want to retrieve data from cloud firestore with having current userId is equal to document id.
For now i have this :
class UserManagement {
getData() async{
String userId = (await FirebaseAuth.instance.currentUser()).uid;
print(userId);
return Firestore.instance.collection('users').document(userId);
}
but this is not working properlywhen i log out and after re-login with different user it showing me same data.
UserManagement().getData().then((results) {
setState(() {
userFlag = true;
users = results;
});
});
Now, how get other fields like name,email,course,phonenumber..etc
and all values all storing into user.right?
If the document id in your firestore is equal to the userid in the Firebase authentication console, then you need to retrieve the uid first and pass it as an argument to the method document():
getData() async{
String userId = (await FirebaseAuth.instance.currentUser()).uid;
return Firestore.instance.collection('users').document(userId);
}
Your query is fetching all of the documents in the "userData" collection, then picking out the first document from that entire set. This will be the same set of documents for all users that have read access to that collection. I don't see why you would expect a different result for different users. Perhaps you meant to access a single document for a user given their user ID, instead of all of the documents. If that's the case, you should request that document by its ID with Firestore.instance.collection('userData').document(uid)' whereuid` is the ID of the currently signed in user.
Also, your code is querying a collection called "userData", but your screenshot shows a collection called "users", so that is confusing.

How to add a document to a collection in cloud firestore

I have a collection called 'users'. I'm trying to add a user to the collection after Google authentication but I keep getting the following error:
FirebaseError: [code=invalid-argument]: Invalid document reference. Document references must have an even number of segments, but users has 1.
Here is the code
this.googlePlus.login({
'scopes': '',
'webClientId': environment.googleWebClientId,
'offline': true,
})
.then(user => {
// save user data on the native storage
const userRef: AngularFirestoreCollection<User> = this.afs.collection<User>(`users/`);
const data: User = {
email: user.email,
displayName: user.displayName,
uid: user.uid
};
userRef.set(data)
.then(() => {
this.router.navigate(['/home']);
Google+ is being discontinued so you should look at Firebase Authentication, or GCP's new Cloud Identity Platform.
In the case of Firebase Authentication, you must listen to the .onAuthStateChanged observer. Once it fires off your user object, you then take that and write a new user document to a users collection in Firestore. Best practise is to use the uid of the firebase.auth().currentUser.uid as the user document ID in your users collection.
Your userRef refers to a collection, and the type of object is called a CollectionReference. You're attempting to call set() on it with some object that should become a new document in that collection. But that's not the way it works. Instead, it looks like you want to call add() to add a new document with a new random ID.
If you somehow already know the ID of the new user document, you should build a DocumentReference with that id, then use set() on that DocumentReference to create the document.

How to create unique and safe UID on Admin- Custom Token- Firebase

I use custom auth function on my app, in order to login anonymous users (by saving a unique permanent custom token on their device).
The functions work fine both on app side and admin side but I need to provide a unique UID on the admin side- in order to save the user on Firebase.
Here's my code on Admin (index.js):
exports.createToken = functions.https.onCall((data, context) => {
const uid = "?????"; // how to create some unique uid here?
return admin.auth()
.createCustomToken(uid)
.then(customToken => {
console.log(`The customToken is: ${customToken}`);
return {status: 'success', customToken: customToken};
})
});
I need to create unique uid (that isn't on my Authentication users
table already).
It should be "safe" (that two users won't get it at the same time).

Flutter - How to add Firebase-Auth user credentials to new records (FireStore documents)?

I'm trying to create a simple Crud app with Flutter and Firebase which the records (documents created in FireStore) are related to the user who has been Authenticated. Therefore the Crud functions will only be performed by the user who created the record. IE a user will only be able able to edit/update/delete the records they added in the first place.
I have the firebase_auth and crud functions working nicely with firestore. the issues i'm have is with relating the two. I have chosen to use the users email and the unique identifier (i'm not sure if it's better to use the auto generated user id or not). I have created a separate function for simply returning the current user's email as it's being added to the firestore document. The problem is the first time i add a record the user email returns null, If i submit the form again it starts working fine.
String _userEmail;
_getUserAuthEmail() {
FirebaseAuth.instance.currentUser().then((user){
setState((){this._userEmail = user.email;});
});
return this._userEmail;
}
Which is being called from the onPressed event
onPressed: () {
crudObj.addData({
'itemName': this.itemName,
'userEmail': _getUserAuthEmail(),
}).then((result) {
dialogTrigger(context);
}).catchError((e) {
print(e);
});
},
As i'm just starting out please let me know if there is a better approach. Cheers.
You are getting null because you are not waiting for the currentUser method to settle. Change the _getUserEmail method like this:
String _userEmail;
_getUserAuthEmail() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
setState(() {
_userEmail = user.email;
});
return this._userEmail;
}
Also, about this
"I have chosen to use the users email and the unique identifier (i'm not sure if it's better to use the auto generated user id or not)."
I suggest you using the user's uid for saving user related stuff.

Resources