I saw this code on Firebase tutorial and I dont know what they mean by writing "userID".(if there is a data that I need to take, where should I can find this?
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl
});
}
I don't know if I correctly understand your question, but each user in firebase is assigned a unique identification string called the uid which is the userId in this case. This uniquely tags the user in the database and any data stored and is uniquely attached to that user can be stored under the uid node for easy reference. What I am seeing here with the function writeUserData() is implemented to be called after registering a user. So you can get the uid by simply calling firebase.auth().currentUser.uid. This will return the string that you can provide as the userID.
A cleaner way could be to first make sure the current user is not null forexample:
var user = firebase.auth().currentUser
var userID = ''
if(user !== null) {
userID = user.uid
} else{
console.warn("User does not exist")
}
Related
I'm playing around with a firebase web app and having some difficulty diagnosing where something is coming from.
I am trying to simply push some data to my project under the heading of the uid created when authentication takes place. The authentication works fine and it is returning the uid correctly however, when values are passed it seems to be adding a second layer before the actual values.
function registerAccount() {
var firebase = app_firebase;
var firebaseRef = app_firebase.database(); //database reference
var user = firebase.auth().currentUser;
uid = user.uid;
var ref = firebaseRef.ref('User').child(uid); //referencing node
var userName = document.getElementById("txtUsernameInput").value;
if (user) {
// User is signed in.
var data = { //data being added
Username: userName,
}
window.location = 'myHome.aspx';
} else {
// No user is signed in.
console.log("Cannot get UID");
}
ref.push(data);
}
I am expecting the data entry to show with the child of user to be the uid taken from the authentication (this is working) then have the passed values immediately in the uid without the seemingly auto generated child between the uid and the values.
Image shows the unwanted field being generated
[See here][1]
André Kool's suggestion in a comment:
Change ref.push(data); to ref.set(data);
worked.
I have data stored in a firebase realtime database, in the following format.
users:
-L5ZAb7r10_nqss7Ag:
role: "user"
email: "person#example.com"
username: "King Arthur"
-KL3Abnar7_nals8:
role: "admin"
email: "other#example.com"
username: "Queen Ferdinand"
And in the database.rules.json I have:
"users":{
".indexOn":["email"],
".write": false,
".read": "auth != null"
},
On the front end I have a user giving their email, having been authenticated with Google OAuth, and I want to see if their email is a valid user, and if so return their role and username, otherwise throw an error. Right now I loop through the 'n' accounts and check each account's email. O(n) is obviously a really sucky runtime.
Not knowing what the user's key in the database is (the "-L5ZAb7r10_nqss7Ag" part), I want to be able to check for the given email in O(1) by searching the email in the indexed database. What I have in mind is something like the below. If this is posisble can someone point me to the riht documentation for the correct syntax?
firebase.database().ref(`/users/`).getIndexedValue($key/person#example.com).once('value').then(function(snap){
if(snap == null) console.log("error);
else{
user = snap.val();
console.log(user[role]);
console.log(user[username]);
}
}
I know the above won't work, .getIndexedValue() isn't real. What would be the correct syntax for this functionality? Is there someway to look for a specific indexed value (the email) that sits below an arbitrary partent (the -KL3Abnar7_nals8)?
You're looking for orderByChild() and equalTo(). Something like this:
firebase.database()
.ref('users')
.orderByChild('email')
.equalTo('person#example.com')
.once('value').then(function(snapshot){
if (snapshot.exists()) {
snapshot.forEach(function(snap) {
user = snap.val();
console.log(user[role]);
console.log(user[username]);
})
}
}
To learn more about Firebase Database queries, see the documentation on sorting and filtering data. I'd also recommend checking some previous questions on the topic.
I'm trying to update/add data on firebase. I used the Facebook login and I want to use the UserID as a key for the new data aded.
(check pict below)
The userID that I want to use it:
I want to replace that key with the userID:
fblogin(){
this.facebook.login(['email'])
.then(res=> {
const fc = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
firebase.auth().signInWithCredential(fc)
.then(fs => {
this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height(720).as(picture_large)', []).then(profile => {
this.newuser = {name: profile['first_name'] ,email: profile['email'],picture: profile['picture_large']['data']['url'],phone:''}
this.navCtrl.push(HomePage);
console.log(fs.uid);
this.db.list('/users/'+ fs.uid).update(this.newuser);
});
I got this error in compilation:
supplied parameters do not matchany signature of call target
In this line: this.db.list('/users/'+ fs.uid).update(this.newuser);
Any help?
The FB error looks correct. You cant update on the uid as the user has been saved with a unique FB id
You do not show the code that created the users record in the database, but what i think you want to do is set and object when you first save the users record. However this could be an issue because the user could be saved before the return of the uid. I cant tell with your code snippet. Regardless, I will write the code that i think will work if the users/ record is created at the time that of registration.
The service
async signupUser(email: string, password: string) {
try {
const result = await this.afA.auth.createUserWithEmailAndPassword(email, password);
return result;
} catch (err) {
console.log('error', err);
}
}
So this initially creates a user without facebook, The key here is that the users FB uid was created and is held in the returned result
The component
this.authData.signupUser(email,password).then(userData => {
console.log(userData) // <- this is result
}
Then we create a record in FB with the uid returned
this.db.object(`users/${userData.uid}/`).set(data);
.set(data) is whatever data you want to save in the users/uid namespace.
So basically you need to create that user table with its uid namespace when the user first registers. Then you can update the user with the uid returned from the facebook fs.uid
With your current code you could find the user based on the email ( because the email should be unique to all users) and then update ...
with lodash is it just
let foundUser = find(this.db.list('users'),{ 'email' : fs.email }
// and then update based on the object key
this.db.list('/users/'+ Object.keys(foundUser)).update(this.newuser);
i fixed the problem by using:
this.db.object('/users/'+ fs.uid).update(this.newuser);
instead of :
this.db.list('/users/'+ fs.uid).update(this.newuser);
And it works correctly !
Thanks all for help.
As part of my studies I need to develop web-app (javasript language) Where we work with firebase realtime database.
currently inside the database,I have a tree of users objects that representing all the users who registered to the system. And what I'm trying to do is a simple user login function.
After the user entered his username and his password, I created an array to enter the entire user tree from a database. The problem is that when im calling the function from the Firebase it's not enough to ended.. and what happens is that the array remains empty and you can not verify that the user is registered on the system.
now I have used a temporary solution that Im using setTimeout function,I understand that this is wrong programming, and also i do not want the user to wait 2 seconds every time he wants to login to the system.
Can someone please help me? how to do it right without the setTimeout function?
I want that the function of the Firebase ends so only then start with the Authentication process.
Here is the code I wrote so far,
var correntUser;
var userlist = [];
var usersRef = database.ref('users');
// Query that inserts all users keys and names to an array.
usersRef.orderByChild("username").on("child_added", function(snapshot)
{
userlist.push({userKey:snapshot.key,username:snapshot.val().username,password:snapshot.val().password});
});
setTimeout(function()
{
//check if user exist in userlist.
for(var i=0; i<userlist.length;i++)
if (userlist[i].username == usernameArg && userlist[i].password == passwordArg)
correntUser = userlist[i].userKey;
if(correntUser == undefined)
{
//check if undefined
alert("wrong username or password");
document.getElementById("username").value = "";
document.getElementById("password").value = "";
return;
}
mainPage.addHeader();
},2000);
thank you all.
There is no need to manually check all users and see if there is a match with the attempted login credentials when Firebase provides built-in authentication. Password-based accounts require email addresses, although you can combine the username with any domain name to satisfy that requirement as suggested here.
You did not explain what your database structure looks like under the users path, but one way to handle that is to incorporate the user's unique id that gets returned as part of the createUserWithEmailAndPassword password:
function createAccount(email, password) {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(userData) {
// account created successfully
usersRef.child(userData.uid).set({
email: email,
creation_date: new Date(),
...
})
}
.catch(function(error) {
...
})
}
Then for login attempts:
function login(email, password) {
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(userData) {
// login successful
mainPage.addHeader();
})
.catch(function(error) {
alert("wrong username or password");
document.getElementById("username").value = "";
document.getElementById("password").value = "";
})
}
I am new to website creation and I am using login/membership features. How would I dynamically create a new, permanent web page (profile page) for a member once they sign up?
//where I would use the code
//Javascript
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
//Navigate to the User's page, which does not yet exist
var url = "http://example.com/" + user.uid;
window.location = url;
} else {
// No user is signed in.
}
});
The answer is in the docs.
https://firebase.google.com/docs/auth/web/manage-users#get_a_users_profile
I suggest having a read of some FireBase documentation, you'll likely need to find out about how FireBase routing works (assuming you're using it as a server)
However, for your requirements (i.e. a user profile page), you can just grab the data and display it at a general profile URL.
var user = firebase.auth().currentUser;
var name, email, photoUrl, uid;
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
uid = user.uid; // The user's ID, unique to the Firebase project. Do NOT use
// this value to authenticate with your backend server, if
// you have one. Use User.getToken() instead.
}