How to use Firestore's document as unique username? - ios

In order to use Firestore's document as userID(username), I found this way.
-> users
-> UID
-> name
-> phone
-> email
-> usersByName
-> UserName: UID
However, one Google Firestore worker replied me like this on twitter.
His reply
I know that each document is unique.
But it will be overwritten by everyone.
If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data
https://firebase.google.com/docs/firestore/manage-data/add-data?hl=ja
I want to know what the best way to use document as userID(username) is.
Thanks!

Building on the answer below:
I added a second check to make sure the uid being stored matches the uid of the user requesting it.
match /usernames/{username} {
allow create: if !exists(/databases/$(database)/documents/usernames/$(username)) && request.auth.uid == request.resource.data.uid;
}
*one more check would be necessary to prevent a single user to register multiple usernames.
Source:
Enforcing unique userIds in Firebase Firestore

Related

Firebase: Maintain a Username Directory

I am creating a Social app and want to track if a username already exists or not. The username list is supposed to grow in future and the way I was doing it now was a key value pair of <string,bolean> like this:
name1: true,
name2: true
all the above data was to be stored in a single document and whenever I want to see if a user exists I would call this document and check accordingly. But here's the problem, firebase max document size is 1MBs and as the users grow this can be problematic, so wanted to know from firebase experts that what's the best way to solve this use case in firestore or realtime database but since I need to query exists maybe realtime db won't suit that well.
Note that I don't want any of firestore querying capabilities but only to check if an entry exists in the record or not and if not just add it.
The Realtime Database doesn't have a 1MB limit (since it has no concept of a document, and everything is just a tree of JSON), so I'd typically use that for the index of user names.
Checking whether a name exists is pretty simple there too, and in JavaScript would look something like:
const usernames = firebase.database().ref('usernames');
usernames.child('name1').once((snapshot) => {
if (snapshot.exists()) {
...
}
});

Swift and Firestore security rules, firebase security

I'm new developer working on my first Firestore app. I've changed the rules on Firestore to make the data more secure for user, but it's not allowing read/write.
This is the key line and I don't know how to configure it specific to my app -
match /some_collection/{userId}/{documents=**} {
I don't know if I change the "some_collection" to my collection name or if some_collection in that sense is an actual wildcard type of parameter itself.
Also, do I need to pass in the userID somehow from my swift application to Firestore? where is userID coming from in this line? I'd prefer to make the rule such that only the user who created the data can read/write. I believe this block is to allow any authenticated user, so I'm just trying to explore each step.
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /some_collection/{userId}/{documents=**} {
allow read, write: if request.auth != null && request.auth.uid == userId
}
}
}
Addressing your questions:
This is the key line and I don't know how to configure it specific to my app.
match /some_collection/{userId}/{documents=**}
I don't know if I change the "some_collection" to my collection name or if some_collection in that sense is an actual wildcard type of parameter itself.
In the line above "some_collection" is not a firestore wildcard and you need to replace some_collection with the actual value of your collection.
Also, do I need to pass in the userID somehow from my swift application to Firestore?
Yes and it is expected that before reading or writing to/from firestore:
You had already created and configured the firebase object.
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
You had already authenticated your users with firebase auth.
firebase.auth().signInWithCustomToken(token)
.then((user) => {
// Signed in
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
Passing the userId is done by the firebase object when you call db. collection(“col123”).add or any other method. If you look at how firestore is initialized:
var db = firebase.firestore();
You will see its dependency with the firebase object.
where is userID coming from in this line?
The userID is coming from the firebase object.
I believe this block is to allow any authenticated user, so I'm just trying to explore each step.
Yes, the last rules allow any authenticated user to read and write from/to the subcollections/documents wildcard {userId}.
Lastly it is also expected that there is some naming consistency in the ids of your firestore documents or subcollections.
This means when you create firestore documents, use the firebase.auth.uid as the document id.
Otherwise, the rule from above will fail because the value behind {userId} is not equal to firebase.auth.uid of the logged user.
To achieve the latter, you can refer to this answer.
I highly recommend you have a look at this video(from the firebase channel) since it elaborates more on the core concepts of firestore security rules.
I hope you find this useful.

Is my User ID supposed to be different than my Document ID for each User in my Users Collection (Firestore)?

I know that this is probably a dumb question, but I'm only starting to learn Firebase/Firestore and I'm having trouble finding the answer that I'm looking for.
I know that I can get the User ID from the currentUser method, but how am I supposed to reference the uid in my file path if the uid and the document id for each user is a different value?
For example, in the reference variable bellow, "HEo4YjfjJ0p2B6hVJRXs" is the document id. If I replace this value with the current user's uid, would it still work the same despite the fact that the uid value is different?
var colRef = Firestore.firestore().collection("/users/HEo4YjfjJ0p2B6hVJRXs/Days")
For example, in the reference variable bellow, "HEo4YjfjJ0p2B6hVJRXs" is the document id.
If that's the id of the document, than that id should be used in your reference, as you already do.
If I replace this value with the current user's uid, would it still work the same despite the fact that the uid value is different?
If the current user's uid is different than the id of the document, then you won't be able to read that document. If you need a document that has as id, the user's uid then you should create that document. If you are also thinking about wildcards, please also note that in Firestore there are no wildcards paths to documents. You have to identify collections and documents by their ids.

Allow Firebase Storage Bucket to be accessed only by some users

I have a main "folder" in my storage directory called users-projects and then I create folders for every users' projects. I want to allow the users to access only their projects and the projects they are invited in, like a Dropbox or Google Drive folder with collaborators.
In the Documentation they says:
Include group information (such as a group ID or list of authorized
uids) in the file metadata
So here is my questions:
Can I do this directly with the folder?
How can I store the list of authorized uids?
I am programming an iOS app in Swift.
Here is my actual code for the Rules:
service firebase.storage {
match /b/on-team.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
match /users-projects {
match /{projectId} {
allow read, write: if ?????
}
}
}
}
Here is the official documentation: https://firebase.google.com/docs/storage/security/user-security .
I think the correct static rule would be :
allow read, write: if request.auth.uid == 'a-user-id' || request.auth.uid == 'another-user-id' || ...
But I guess you are looking for dynamic rules :)
For the owners it's quite simple to setup a dynamic rule with the folder name :
match /users-projects/{projectId}/{userId} {
allow read, write: if request.auth.uid == userId
For more complex cases like invited users, you can try using the custom metadata to store invited uids in the file, and match them against user id accessing that ressource, example rule:
allow read: if resource.metadata.invited.matches(request.auth.uid);
The custom metadata values can only be strings, so I suggest you store them as coma-separated value so you can edit them easily, and at the same time use a simple match in the access rule.
Note: this is only scalable while invitedUids.join(',') length is shorter than maximum length of custom metadata values. (I don't know that value). If your app is not built to accept hundreds of invited users, it should be ok, otherwise you might need to setup a server-side access mecanism which build a unique download link for each invited user, instead of relying on simple rules.
Also, I don't think you can use token groupId value to enforce access security in your case (as depicted in the docs), because you have a many-to-many relationship between users and folders/files. (users will not belong to only one group)
So, to answer your questions:
The resource object in the rules only apply to files, if using metadata to enforce access, they need to be updated on each file in the folder if they share the same access rules
The metadata is just a string->string key-value store, you just need to store user ids as a string in a arbitrary non-reserved key, as explained above.
Store individual project in a directory using their userid
/users-projects/user_id/project1
/users-projects/user_id/project2
service firebase.storage {
match /b/on-team.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
match /users-projects/{user_id} {
allow read, write: if request.auth.uid == user_id
}
}
}

Google Contacts: Unique Contacts?

I am building an application that I will need to distinguish the Google Contacts from each other. I am just wondering, as long as google sends contacts as First Name/Last Name/mail.. etc (Example) without a unique ID, what will be the first approach to distinguish each contacts?
1) Should I create an ID based on the user's fields? -> by a minimal change, it can break down.
2) Should I create an ID based on First Name + Last Name? -> but most people can have duplicate contacts on their page, would that be a problem? Or married contacts, which can create a little mess.
The reason I am asking this I am trying to create relations and I need to store the data somewhere like that [person=Darth Vader, subject=Luke Skywalker, type=father(or son)], so I need a fast algorithm that can make a mapping for each contact and retrieve the related contacts fast.
I believe they do send back an ID. From the return schema:
<link rel='self' type='application/atom+xml' href='https://www.google.com/m8/feeds/contacts/userEmail/full/contactId'/>
You could use the full HREF value as the ID, or parse out the contactID from the end of the URL, whichever you like better.

Resources