I am trying to check if a username is already taken in my flutter and firebase app, but I am facing some problems.
I am able to query the user's collection and compare a name string saved in the input of the text form with names already in the database, which works perfectly well. But my problem is when a user takes a name and that same user tries to save his profile without changing his name, he gets the message username is already taken, meaning he can't save his profile cause he has already taken his own name.
I want a solution where a user can save his profile if he or she hasn't modified his or her username without going through the username is already taken process. I don't know if it's possible to add an if statement to check if the current user name is equal to the username in the text field? or help with any solution that works.
please these are my codes below
//checks fields of user collection and compares the
//string _username with the userName of each user.
final QuerySnapshot result = await Firestore.instance
.collection('users')
.where('userName', isEqualTo: _userName)
.getDocuments();
//converts results to a list of documents
final List<DocumentSnapshot> documents =
result.documents;
//checks the length of the document to see if its
//greater than 0 which means the username has already been taken
the name
if (documents.length > 0) {
print(_userName + ' is already taken choose
another name');
}else{
print(_userName + ' are you sure you want to use
this name');
}
I think a solution would to only check to see if this username is taken if the user changes his username! Therefore you would not have to worry if the user with the taken username is just saving his profile without changing his username.
yes if you are in firestore as backend...you can not show query stream in registration page for username suggestions for availability bcoz u hav to set firestore rules insecure and allow unauthorised users to read write your database...so better to push a new page after that registration page where you can place field for username in this case you are already registered and logged in so firestore security rule will not invade....
Happy coding :)
Related
so im building an app which has 2 users(staff and student) and the staff must accept/verify users manually. thereby when the student registers/signs up this would show up as a request on the staff side then after the staff accepts or rejects the request which allows the studentto enter the app. i've already coded the sign-in sign up pages which looks very similar to this using firestore authentication.
the only solution i could think of is adding the user sign up info as a request and saving it under a firestore collection("registration requests") i though about how the password field might be an issue but i found that people used the flutter_string_encryption package to save the password as a .doc field. then when the staff accepts the request the method/ function .createUserWithEmailAndPassword(email: email, password: password) would be called but i don't know if this is the "correct" way of achieving this.honestly i have no idea how to tackle this problem. is there is any resource that tackle the same issue or any other way this could be archived?
You could implement a system whereby any student can create an account using .createUserWithEmailAndPassword() but the account has an associated flag/boolean which prevents them from viewing content until it is true.
E.g
Student creates account using .createUserWithEmailAndPassword().
Upon creating new user, create a FireStore document containing a boolean set to false if the account is unverified.
Allow teachers to alter the FireStore record for students and change the boolean value to true upon verification.
Dynamically display content to users based on wether the boolean in their FireStore record is set to true or false.
If this sounds feasible, I can provide more detail on the specific code if you're not familiar with the packages.
My database is quite simple. A collection and inside, there are documents with user information, including their username.
(I am doing this in flutter and firestore).
What I want is to prevent two users from having the same username.
I am doing this to insert the data.
FirebaseFirestore.instance.collection('users').add({
'username': 'username',
'desc': 'some bio',
'fieldone': 'aaa',
'fieldtwo': 'bbb',
// other user info
});
And to consult the data of a user (by their username).
FirebaseFirestore.instance.collection('users').where('username', isEqualTo: 'username').get();
At the moment I insert the data, what can I do to verify that said username is already in the database?
So if the username already exists, return an error and don't let insert it. And if it doesn't exist yet, it can be inserted.
What query can help me for this?
I am new to firebase. :(. Thanks.
What query can help me for this?
This can't be accomplished by a single query. You will have to take the steps you outlined already in your question. You will have to first query for documents with that username, then only insert a new one if there were none found.
However, you should be aware that there is a race condition here. If two people are trying at the same time to add the same username, it's possible that they both end up adding a document.
The only way to ensure uniqueness in Firestore is using the document ID. You might want to consider using the ID of the document to store the username (or some version of it, like a hash) so that a race condition can never occur, and that you only have one document with that username.
See also:
Firestore unique index or unique constraint?
Cloud Firestore: Enforcing Unique User Names
Unique field in Firestore database + Flutter
firebase rule for unique property in firestore
As you can see, your issue has already been thoroughly discussed on Stack Overflow.
I'm trying to build a search functionality where a text entered in my search field is search through two fields in my Firestore(profileName and username). For example, if a user has the profileName 'Sylvester Appiah' and username 'keeett'. Then when either the username or profileName is searched it should return the same user. I'm not sure if I can do profileName or username inside the .where() method. Any help is appreciated!
controlSearch(String searchWord){
Future<QuerySnapshot>pUsers=usersReference
.where("profileName",isGreaterThanOrEqualTo:searchWord)
.getDocuments();
setState(() {
futureSearchResult = pUsers;
});
}
You can't pass multiple conditions to where(). Instead you can call where() multiple times, chaining them together into the query you need:
usersReference
.where("profileName",isGreaterThanOrEqualTo: searchWord)
.where("username",isEqualTo: "QeustionableCoder")
.getDocuments();
Note that you may need to define an index for such multi-field queries. If you're missing an index, the SDK will log an error message about that. Look for the URL in that error message, as it is the fastest way to define an index on the correct fields.
With iOS/MacOS is there a way to retrieve the uid immediately after createUser?
Our app allows an Admin user to create other user accounts (email/password authentication) and also stores some other info about the created user in our Firebase with the uid as the key.
One solution is when the admin creates the user (createUser), it's followed by authenticating the user, grabbing the uid from FAuthData that's returned and then create the key/value pair in our Firebase with the user data. Then that account is unauth'd.
In doing a Google search, there were a couple of references to something like this
-(void)createUser:(NSString *)email password:(NSString *)password withCompletionBlock(NSError *error, User *user) {block}
where it appears a user (or FAuthData?) was returned.
If no, what is the best practice to get the just-created uid? Is this a feature that is upcoming?
2/22/2016 update
For completeness, soon after I asked this question, Firebase was updated with a method that created the user and returns the uid at the time of creation:
createUser:password:withValueCompletionBlock:
- (void)createUser:(NSString *)email password:(NSString *)password
withValueCompletionBlock:(void ( ^ ) ( NSError *error, NSDictionary *result ))
The result dictionary contains newly-created user attributes, including uid.
I have a forgot password page in which i need to ask from the user his user id to provide him his password from the database and it is working but what to do if anyone enters any wrong user id.
Be aware that there's a certain measure of risk in this. If you always respond with a message saying that the User ID is incorrect, then that can be used to guess User IDs in your system. An attacker can brute-force this form with variations of common names and end up with a sizable list of your users. For any given account, that gives them half of the information needed to login as that user.
I would recommend that you display a message saying that an email has been sent to the email address for that account with instructions to reset the password (which includes a time-sensitive key required for the reset), regardless if the User ID was found in the system or not. If they don't get the email, they can always try again (assuming the first attempt included a typo in the User ID). If they don't actually know their User ID, there can be another form to recover that by entering their email address (behaves in a similar manner to this form, always showing success on the form and just sending the email where applicable).
You have to perform following 3 steps to ensure tight security.
1) Based on the userid fetch the user information from database. If the information is null then send an error to the user, saying invalid UserId.
2) a) If you have registration of EmailId at the time of user creation, then send the password to the registered mail.
b) If you don't have registration of EmailId then ask and match the security question selected at the time of user registration.
3) If possible try to combine the a) & b) points of point 2) for more enhanced security.
You must do SELECT to check if that records exists and proceed if so.
Simply return a message stating they have entered an incorrect user id.
If you're asking what do you do if they give you the valid ID of another user entirely, then I'm assuming you're doing something quite unsafe with the password you're recovering (you aren't just showing them the password are you?) - most systems like this will email you the password, at least affording the security that only the associated email account will ever be given the password.
SELECT * FROM users WHERE username = inputhere
if (mysql_num_rows($result) > 0)
{
// found it
}
else
{
// doesn't exist
}
Is that what you were looking for?