firebase assign a key to a specific browser instance when created? - javascript

I'm experimenting with Firebase/javascript and am wondering how do I assign a key to a specific browser instance when created?
Upon entry, user is greeted with a user input field for their name and submit button
When the submit button is clicked the user information is sent to firebase and saved under a newly created key
I know how to do this and how to retrieve the data from firebase but,
how do i ensure the key that is created gets assigned to the specific user so that only the information in that key is sent back to the user or updated?
I am trying to do this without having a user signup or login. Is there a way to do this?

When the user clicks the submit button, you will send the name and the key to the database:
var ref = firebase.database().ref();
var reference = ref.child('users');
var post = reference.push();
post.set({
username:name
});
Then after that you will have this in the database:
users
pushkey
username: userx
another user adds his name and clicks submit:
user
pushkey <--- this key will be only to this user
username: userx
pushkey1 <--- will be only to usery
username:usery

Related

email and password remember me for login after user logged in for the first time

when the user login to his account and click remember me how to make the login form auto-fill the user email and password when the user come to login again so he doesn't have to fill his email and password again in react and next
First of all, store user's credentials on front side (localStorage, lessionStorage and etc.) is not a good practice.
Usually "Remember me" checkboxes are used to create an auth-cookie with longer time life.
For example:
When user checked "Remember me", you will send post request with query params remember=1, server handle this, and send response with header:
Set-Cookie: {auth-cookie}={value}; Max-Age={one week, for example}
It will create a cookie in browser, which time life is one week.
In another case, if user didn't check "remember me", server responds with header like this:
Set-Cookie: {auth-cookie}={value}; Max-Age={one day, for example}
It means that user will be authorized during just one day, after it cookie will be expired, and user will logged out.
User can allow the browser to autocomplete input fields if click "Save password" after submitting the form in browser's popup.
It's browser behavior.
Best regards!
Answer
You can use localStorage, a built-in object in JavaScript for browsers.
localStorage is of type Storage, which means that you can use it via the methods setItem, getItem, and removeItem.
How to use
localStorage.getItem("item1"); // null
localStorage.setItem("item2", "EntityPlantt");
localStorage.getItem("item1"); // still null
localStorage.getItem("item2"); // "EntityPlant"
localStorage.item1; // "EntityPlantt"
location.reload(true); // Reloads page
localStorage is persistent, so you can call it on load to fill in the form.
Examples
onload = () => {
if (localStorage.getItem("data")) {
var data = JSON.parse(localStorage.data);
// fill out the form
}
}
And, when someone fills the form, you can save the form data in localStorage.
btn.onclick = () => {
localStorage.setItem("data", JSON.stringify({
// Form data
}));
submitForm(); // The submitting of the form; your code here
}
Note that localStorage can only store strings. So you can convert them to your type.
var number = parseFloat(localStorage.getItem("number"));
var string = localStorage.getItem("string");
var object = JSON.parse(localStorage.getItem("object"));
var array = localStorage.getItem("array").split(",");
var symbol = Symbol(localStorage.getItem("symbol"));
Reference
If you want to learn more about localStorage (and sessionStorage), go to the MDN docs.
You can use the localstorage of the browser (better encrypted). Then, if the user doesen't refresh the localstorage you will be able to use this information to fill the form.

How to retrieve a specific data in Firebase Database?

After a user signed in his/her account, he/she will be ask what is his/her user role.
IMG 1: ask user role
After selecting a role, it will then be save in the database,
IMG 2: saved user role
So, how do we retrieve the specific data from Firebase database and then print it in the HTML?
IMG 3: show the user role
These are the codes I used in my .js
function app(user){
function updateMyStatus(e){
var myUpdate={};
myUpdate.email = user.email;
myUpdate.displayName = user.displayName;
myUpdate.status = document.getElementById("clientStatus").value;
fb.child(user.uid).set(myUpdate);
}
function receiveUpdate(received){
var data = received.val();
console.log( data );
document.getElementById('role').innerHTML= "";
}
document.getElementById('userName').innerHTML = user.displayName;
var fb = firebase.database().ref('Accounts');
document.getElementById("clientStatus")
.addEventListener("input",updateMyStatus);
}
and if the user has already a user role(status) as shown in the image 2, how do you hide the Dropbox that is shown in the image 1?
The below will get back your data from Firebase for that account. Then it is a matter of setting the values to their respective HTML elements.
fb.child(AccountId).on(‘value’, callbackFunction)
For reference: https://firebase.google.com/docs/database/web/read-and-write
function receiveUpdate(received){
var data = received.val();
console.log( data );
document.getElementById('role').innerHTML= "";
//hide the dropdown box
document.getElementById("clientStatus").style.display = "none";
}
document.getElementById("clientStatus").addEventListener("input",updateMyStatus);
//put this under your other event listener
fb.child('Accounts').on(‘value’, receiveUpdate);
This code will not work as written. I hope this helps give you a good idea.
Based on your current code, and based on my own understanding of the Firebase Realtime Database, these are the steps you need to take:
Register a listener to listen for changes to the database
To be more specific, you need to add a listener to the particular field that you are interested in in the database.
This listener should preferably not be inside any function.
This listener would check whether a role exists for your user in the database.
If yes, hide the input field and display user's details.
Else, display both the input field and the user's details.
As I have no experience using the Realtime Database (I have only used Cloud Firestore before), I am not very familiar with its syntax. But the link suggested by #Andre Kool and #thezachcannon in the previous post has examples of adding a listener to a particular database reference.
Hope that helped.

Firebase Realtime Database Connection Data - Web

I have to show data belonging to a user that logged in.
My database structure is as follows:
Users/Drivers/Uid/name,phone...
How can I show the data of a user that logged in by using JavaScript as a Text?
<a> Username </a>
If you have this HTML:
<a id="username"> Username </a>
And this database structure:
Users
Drivers
Uid: { name: "Name", phone: "Phone number" }
Then you can display the name of the current user with:
var currentUser = firebase.auth().currentUser;
var userRef = firebase.database().ref("Users/Drivers").child(currentUser.uid);
userRef.on("value", function(snapshot) {
document.getElementById("username").innerText = snapshot.val().name;
})
So this code does (line by line):
Determine the current user
Create a reference to that user's data in the database
Starts listening for that data, meaning it loads the current data, and then monitors for any changes
Puts the name of the user into the element.
Line 4 will be called immediately, with the current value of the user, and then every time that user data change.
Also see the Firebase documentation on listening for values.
If the page can also be loaded when the user is not signed in (yet), you'll want to make sure to only run this code when the user did sign in. You can do this by using a so-called auth state change listener, which is called whenever the user's auth state changes:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var userRef = firebase.database().ref("Users/Drivers").child(user.uid);
userRef.on("value", function(snapshot) {
document.getElementById("username").innerText = snapshot.val().name;
})
}
});
See the Firebase documentation on getting the current signed in user..

refreshing the browser overwrites the child's content in Firebase

I am a complete beginner in the database world. I'm trying to use Firebase database and here is the problem I encounter: I want to create a simple signup where the user should write the info and this info should be stored in Realtime Database. That is to say, when the user enters his info and clicks on "sign up" user 1 should be created, then user 2 enters his info and user 2 should be created, but all of them must be same level "childs". Everything seemed to be working fine, I created an object (in Javascript) then I added to the database as a "child" named "user 1", but when I refreshed the page and entered other info for user 2, this info overwrote user 1's info, but when I just delete user 1's info from the input fields in the browser (without doing a refresh) and enter user 2's info it creates the second "child" named user 2 as it was supposed to be and it's what I want to be. The question is why refreshing the browser overwrites the previous info. Here is my js code:
function submitClick(x){
var firebaseRef = firebase.database().ref();
user_number ++;
firebaseRef.child("user" + " " + user_number).set(x);
}
function signup(){
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var username = document.getElementById("user_name").value;
var password = document.getElementById("password").value;
var obj = {
First_Name: first_name,
Last_Name: last_name,
Username: username,
Password: password
}
return obj;
}
var hold;
var user_number = 0;
submit_btn.onclick = function() {hold = signup(); submitClick(hold)};
and the html is just input fields and a button named "sign up"
When you reload your page, the JavaScript is reloaded and executed again from scratch. It has no memory of what happened before you reloaded it.
That means that this line executes again:
var user_number = 0;
And thus user_number starts counting from 0 again.
The simplest way to fix this problem is to use Firebase's push() method:
function submitClick(x){
var firebaseRef = firebase.database().ref();
firebaseRef.push().set(x);
}
This generates a new unique ID under the root, where it sets the user. While these so-called push IDs are not as easily readable as your numbers, they are guaranteed to be unique across reloads, multiple users, and even offline/online conditions.

Check for new user

I want to know when a user logs in via a provider(twitter,facebook,etc...) If he is a new user. If so then add his data to my firebase.. Currently i have read this:
https://www.firebase.com/docs/web/guide/user-auth.html
And it tells me to do:
var isNewUser = true;
Then check by saying
if(authData && isNewUser){
//This is a new user
}
But it dosent work... I logged in with the same account but it tells me its a new user...
Generally with Firebase, you would have a /users node where you would store other data about your users
users
user_id_0
name: "Buck Murdock"
email: "buck#moonbasealphabeta"
user_id_1
name: "Ted Striker"
email: "ted#airplane.com"
The user_id is the Firebase assigned user id.
When a user starts to access your App, you would query your /users node to see if, for example, their email already exists. If not, then you create the user and add them to the /users node.
Oh - and refer to the section Storing User Data in the Firebase guide as you may have overlooked the comment
// here we will just simulate this with an isNewUser boolean

Categories