How get specific Field data by document id from firestore website - javascript

auth.onAuthStateChanged(function(user){
if(user.uid){
var db = firebase.firestore();
document.getElementById("empUpd_email").value = user.email;
db.collection("employee").doc(user.uid).get().then(result => {
console.log(`${result.id} => ${result.data()}`);
document.getElementById('empUpd_fullname').value=result.fullName;
});
}else{
//no user is signed in
}
});**strong text**
i wanna gender value how i get it
And Database looks like
address
"abdul"
(string)
bio
"abdul"
dob
"2020-08-22"
fullName
"abdul"
gender
"Female"
serName
"abdul"

You can just retrieve the value of gender, using the same way how you did it for fullName.
Try something like this,
auth.onAuthStateChanged(function(user) {
if (user.uid) {
var db = firebase.firestore();
document.getElementById("empUpd_email").value = user.email;
db.collection("employee").doc(user.uid).get().then((result) => {
const results = result.data();
document.getElementById('empUpd_fullname').value = results.fullName;
document.getElementById('empUpd_gender').value = results.gender; // Tag ID is a guess!
});
} else {
//no user is signed in
}
});
Hope that works!

DocumentReference documentReference = fStore.collection("User").document(Objects.requireNonNull(fAuth.getCurrentUser()).getUid());
documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
profileName.setText(documentSnapshot.getString("Name"));
profileEmail.setText(documentSnapshot.getString("Email"));
}
}
});

Related

ASP.NET query to get data from database

In my ASP.NET MVC application, in the signup form, I want to check the user-entered values with my current database table and get the Id if a record is matched.
Here from the user's end, I'm getting their email address, surname, date of birth .
Then in the controller, I'm trying to match any record from the above details to get the existing record Id.
The issue is that it happens takes more time to run this query and returns as timeout.
Is there any way of searching the record more efficiently way?
This is my Controller code
public JsonResult SignUpCustomer(string emailAddress, string password, string surName, string name, DateTime dateOfBirth, string timeZone)
{
int customerId = 0;
try
{
customerId = db.Customer.AsEnumerable().Where(x => x.Sur_Name.ToLower().Contains(surName.ToLower()) && x.Date_of_birth.Date == dateOfBirth.Date && x.Email_Primary.ToLower() == emailAddress.ToLower()).Select(x => x.Id).FirstOrDefault();
if (customerId == 0) {
customerId = db.Customer.AsEnumerable().Where(x => x.Email_Primary.ToLower() == emailAddress.ToLower() && x.Date_of_birth.Date == dateOfBirth.Date).Select(x => x.Id).FirstOrDefault();
if (customerId == 0) {
customerId = db.Customer.AsEnumerable().Where(x => x.Sur_Name.ToLower().Contains(surName.ToLower()) && x.Date_of_birth.Date == dateOfBirth.Date).Select(x => x.Id).FirstOrDefault();
}
}
if (customerId != 0) {
UserAccounts accounts = new UserAccounts();
accounts.Email_Address = emailAddress;
accounts.Surname = surName;
accounts.Name = name;
accounts.Password = Crypto.Hash(password);
accounts.Status = true;
accounts.Created_Date = DateTime.UtcNow.AddMinutes(int.Parse(timeZone));
accounts.Customer_Id = customerId;
dbs.UserAccounts.Add(accounts);
dbs.SaveChanges();
} else {
UserAccounts accounts = new UserAccounts();
accounts.Email_Address = emailAddress;
accounts.Surname = surName;
accounts.Name = name;
accounts.Password = Crypto.Hash(password);;
accounts.Status = true;
accounts.Created_Date = DateTime.UtcNow.AddMinutes(int.Parse(timeZone));
accounts.Customer_Id = customerId;
dbs.UserAccounts.Add(accounts);
dbs.SaveChanges();
}
return Json(new {
Success = true,
}, JsonRequestBehavior.AllowGet);
} catch (Exception ex) {
throw;
}
}
You can clear your Linq query to something like this:
var loweredName=surName.ToLower();
var loweredEmailAddress=surName.ToLower();
var dateOfBirthDateDatePart=dateOfBirth.Date;
customerID = db.Customer.FirstOrDefault(
x => x.Sur_Name.ToLower().Contains(loweredName)
&& x.Date_of_birth.Year== dateOfBirthDateDatePart.Year
&& x.Date_of_birth.Month == dateOfBirthDateDatePart.Month
&& x.Date_of_birth.Day == dateOfBirthDateDatePart.Day
&& x.Email_Primary.ToLower() == loweredEmailAddress)?.Id;
Change other selects too.
Date comparison options are totally diffrenet depending on the version of Ef of efCore you are using. For choosing the best way check here

Display user's data in an html tag after reading them from firebase for webapps

This is the structure of my database, every user is in a child with value as that of their user-id
This is the code i am using
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).child("userName").once('value').then(function(snapshot) {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
$("#name-tag").append(username);
});
I want the userName value and have to display it
First change the way you authenticate the user then create a proper reference to the database.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var userDBRef = firebase.database().ref().child("User Database").child(user.uid);
userDBRef.on("value", function(userDB){
$("#para-id").append(userDB.child("userName").val());
});
} else {
// No user is signed in.
console.log("no user!!!");
}
});
Try this code :
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' +
userId).child("userName").once('value').then(function(snapshot) {
var username = snapshot.val() ? snapshot.val().username) : 'Anonymous';
$("#name-tag").append(username);
});
If snapshot.val() return null then usename will be 'Anonymus'

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

When creating a user with email, how to add elements in DB in Firebase in Javascript

So i'm new to using Firebase and I have been looking at the Firebase documentation but I haven't found how to do the following:
The user puts the following inputs: username, email, password, confirm password.
When I call the "createUserWithEmailAndPassword", if it works, I want at the same time to create entries in the DB in Firebase. I tried writing the following line:
firebase.auth().createUserWithEmailAndPassword(userEmailCreate, userPasswordCreate).then(function(){
//do what I want
}).catch(function (error) {})
But it doesn't work. What am I doing wrong?
Or do you have any suggestions as to how to add additional elements in the entry User using the uid that is created by the authentication method?
function createUser() {
//instance of database Firebase
var database = firebase.database();
//Get inputs from user
var userUsername = document.getElementById("usernameCreation_Field").value;
var userEmailCreate = document.getElementById("emailCreation_field").value;
var userPasswordCreate = document.getElementById("passwordCreation_field").value;
var userPassword2Create = document.getElementById("passwordCreation2_field").value;
if (userPasswordCreate == userPassword2Create && userUsername.length > 0) {
//If passwords match try to create user
firebase.auth().createUserWithEmailAndPassword(userEmailCreate, userPasswordCreate).catch(function (error) {
// Handle Errors here when creating account
var errorCode = error.code;
var errorMessage = error.message;
document.getElementById('createSuccess').style.display = 'block';
document.getElementById('createSuccess').innerHTML = errorMessage;
});
//Passwords don't match
} else if(userUsername.length == 0){
document.getElementById('createSuccess').innerHTML = 'Username must be filled!';
document.getElementById('createSuccess').style.display = 'block';
} else {
document.getElementById('createSuccess').style.display = 'block';
document.getElementById('createSuccess').innerHTML = 'Passwords don\'t match!';
}
}
//Add new user to database
function setUserData(userId, username, email){
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl,
topScore : topScore
});
}
Thank you in advance for your time!
Your code is not calling setUserData anywhere, so that would definitely explain why nothing is written to the database.
You're probably looking to call if from the then of createUser...:
firebase.auth().createUserWithEmailAndPassword(userEmailCreate, userPasswordCreate).then(function(userCredential) {
setUserdata(userCredential.user.uid, userUsername, userEmailCreate);
}).catch(function (error) {
// Handle Errors here when creating account
var errorCode = error.code;
var errorMessage = error.message;
document.getElementById('createSuccess').style.display = 'block';
document.getElementById('createSuccess').innerHTML = errorMessage;
});

How to get just the first name when a user logs in using social media with firebase?

Here is the code that I am using to get the details of the user when they log in using google, facebook or twitter.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var uid = user.uid;
var phoneNumber = user.phoneNumber;
var providerData = user.providerData;
user.getToken().then(function(accessToken) {
console.debug('user', user);
document.getElementById('name').textContent = displayName;
document.getElementById("avatar").src = photoURL;
});
} else {
console.log('not logged in');
}
});
Then in the html by writing <p id="name"></p> the entire name of the user is displayed.
How do I display just the first name of the user?
You can do it like this;
document.getElementById('name').textContent = (displayName.split(' '))[0];
First and last name are available from most social providers just after you log in, but you will need to save them to your database as Firebase does not. What each provider calls first and last name varies, though.
Documentation at https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signinwithpopup
firebase.auth
.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then((user) => {
const firstName = user.additionalUserInfo.profile.given_name;
const lastName = user.additionalUserInfo.profile.family_name;
});
firebase.auth
.signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com'))
.then((user) => {
const firstName = user.additionalUserInfo.profile.givenName;
const lastName = user.additionalUserInfo.profile.surname;
});

Categories

Resources