Login Using Firebase And React Js
Solution 1:
you can check for all id's in the database if any fetch request from http://<Server>/givenID/username is the same as the given username. Same for the password.
Solution 2:
You don't have to fetch the whole "users" node to check that. I'm not sure how your database structure looks like but usually you would have child nodes with users' UIDs as the keys and another another node which holds all the usernames taken. Then you just check if a node where username is equal to that username exists.
firebase.database().ref("usernames/"+"the-username").once("value").then((snapshot) => {
if (snapshot.exists()){
const userInfo = snapshot.val();
console.log("Username taken")
// Process and redirect
} else {
// username available
}
});
Make sure you add the username in that node when a new user signs up:
asyncfunctionsignUp() {
const {user} = await firebase.auth().createUserWithEmailAndPassword(email, password)
awaitPromise.all([
firebase.auth().updateProfile(user.uid, {displayName: "NewUserName"}),
firebase.database().ref(`usernames/${newUsername.toLowerCase()}`).set(true)
])
}
However anyone can bypass this and try to override existing usernames so you must add security rules to prevent that. The following rules should do it:
"users": {
"$uid": {
".write": "auth !== null && auth.uid === $uid",
".read": "auth !== null && auth.uid === $uid",
"username": {
".validate": "!root.child('usernames').child(newData.val()).exists()"
}
}
}
You cannot have multiple .equalTo() in realtime database. For the passwords part, I'd recommend using Firebase Authentication as that'll be safer as well. But if your requirement needs you to look up for data with given username and password (i.e. multiple equalTo), you might have to switch to Firestore.
Alternatively, you can create users using a cloud function if you don't want to maintain a separate node for usernames and use security rules.
exports.addUser = functions.https.onCall(async (data, context) => {
const {username, email, password} = data;
// Check if username is taken from users nodeconst userRef = admin.database().ref("users").orderBy("username").equalTo(username);
if ((await userRef.once("value")).val()) return {error: "Username taken"}
const newUser = await admin.auth().createUser({
email,
password,
displayName: username
})
return {data: newUser.uid}
});
I'd recommend Firebase Auth or the Cloud functions method. If you use Firestore there's a higher chance of someone randomly spamming with login requests and it won't have any rate limiting errors such as TOO_MANY_ATTEMPTS_TRY_LATER that Firebase Auth has.
Post a Comment for "Login Using Firebase And React Js"