Firebase reading a particular key values - javascript

Basically I have my username as a key for user data. Now I am trying to match the username with my current username stored in session storage and read the userdata for that username.
Here is my .js code
var database = firebase.database();
var currentusername = sessionStorage.getItem("username");
var userref = database.ref("users");
userref.orderByChild("username").equalTo(currentusername).once("value").then(function(snapshot) {
console.log(snapshot.val());
});
Firebase Data Structure
Appname
Users
username: "a1"
email: " ",
firstname: "abc",
lastname: "xyz"
When I try to run the above code I am getting snapshot.val() as null although there exists a record with a matching username key.

var userref = database.ref("users/"+currentusername);
userref.once("value").then(function(snapshot)
This worked!!!

This should work
var currentusername;
try {
currentusername = sessionStorage.getItem("username");
}
catch(error) {
console.log("shucks " + error);
}
if(currentusername){
firebase.database().ref("users").child(currentusername).once('value').then(function(snap) {
if(snap.val()){
console.log(snap.val().firstname);
}
}, function(error) {
// The Promise was rejected.
console.log('Error: ',error);
});
}

Related

How to fix nodemailer "object object" error in node.js website?

I am creating a node.js website for a business and would like to be able to notify through email, everytime someone applies. I am using nodemailer and mailgun to send an email every time the job application form is submitted. The emails are being sent, however, it does not contain the key value pairs of the applicant object I've created. Any help would be greatly appreciated!
Here is an image of the email I receive when submitting and application
Here is the nodemailer code I'm running
const nodemailer = require('nodemailer');
const mailgun = require('nodemailer-mailgun-transport');
const debug = require('debug')('app:mail');
const auth = {
auth: {
api_key: '**************',
domain: '***************'
}
};
const transporter = nodemailer.createTransport(mailgun(auth));
function sendOrderEmail(applicant) {
let html = '<ul>';
Object.entries(applicant).forEach(([key, value]) => {
html += `<li>${key}: ${value}</li>`;
});
html += '</ul>';
const mailOptions = {
from: '*************',
to: '*********, *************',
subject: '*****************',
html
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
debug(`Error: ${err}`);
} else {
debug(`Info: ${info}`);
}
});
}
module.exports = sendOrderEmail;
Here is my post route where I create the applicant object
app.post('/employment', function(req, res){
var firstName = req.body.firstName;
var middleInitial = req.body.middleInitial;
var lastName = req.body.lastName;
var address = req.body.address;
var city = req.body.city;
var state = req.body.state;
var zipCode = req.body.zipCode;
var phoneNumber = req.body.phoneNumber;
var doYouRecieveText = req.body.doYouRecieveText;
var newApplicant = {
firstName: firstName,
middleInitial: middleInitial,
lastName: lastName,
address: address,
city: city,
state: state,
zipCode: zipCode,
phoneNumber: phoneNumber,
doYouRecieveText: doYouRecieveText
};
Applicant.create(newApplicant, function(err, newlyCreated){
if(err) {
console.log(err);
} else {
console.log(newlyCreated);
sendOrderEmail(newlyCreated);
res.redirect('/');
}
});
});
It looks like the value you are attempting to insert in your html is an Object but the html is expecting a value of type String.
Try stringifying your value before inserting it in your html.
html += `<li>${key}: ${ typeof value === 'string' ? value : JSON.stringify(value)}</li>`;
I was passing through the newlyCreated parameter to the sendOrderEmail function when I should have been passing through the newApplicant variable
Applicant.create(newApplicant, function(err, newlyCreated){
if(err) {
console.log(err);
} else {
console.log(newlyCreated);
sendOrderEmail(newApplicant);
res.redirect('/');
}
});

ReactNative and firebase, Real time database when signUp

I build a react native signUp form with this fields (email, password, name, and phone) and I need to add it to the firebase database when user create his account.
I create the signUp function like this:
onSignUpPress() {
const navigation = this.props.navigation;
this.setState({ error: '', loading: true });
const { email, password } = this.state;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(() => {
this.setState({ error: '', loading: false });
navigation.navigate("Profile");
})
.catch(() => {
this.setState({ error: 'Authentication failed.', loading: false });
console.log("Error creating user:");
});
}
and it's work
I need to know how can I add the field to a database
I try this :
writeUserData(uid, name, email, phone) {
let userId = firebaseApp.auth().currentUser.uid;
var newUser = {
name: name,
email: email,
phone: phone
}
var newUserKey = firebase.database().ref().child('users').push().key;
var updates = {};
updates['/users/' + newUserKey] = newUser;
updates['/user-users/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
onSignUpPress() {
....
....
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(() => {
....
this.writeUserData(uid, name, email, phone);
navigation.navigate("Profile");
})
....
.....
}
but it's not working correctly any help, please?
Firebase has many functionalities. Out of them two are authentication and real time database.
When you call createUserWithEmailPassword successfully, it automatically creates a UID of the user and stores the meta in Firebase Authentication.
You can now at point of time get this UID of this user when he is authenticated using firebase.auth(). currentUser.uid and then create a firebase reference where you want to save data database.ref().child(path)
Use the .set(object) or .push(object) to save data.
Tip : Create your database architecture properly (see documentation) to be able to fetch the saved data properly.
try this,
writeUserData(uid, name, email, phone) {
const userId = firebase.auth().currentUser.uid;
//You don't have to create key because userId is uniq value.
return firebase.database().ref(`users/${userId}`).update({name, email, phone});
}
onSignUpPress() {
....
....
// createUserWithEmailAndPassword promise resolve return userData!
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(userData => {
....
this.writeUserData(userData.uid, name, email, phone);
navigation.navigate("Profile");
})
....
.....
}
and I don't get it why you try to update,
updates['/user-users/' + uid + '/' + newPostKey] = postData;
even if you don't have postData at this moment!
You just set when user create post data like this
writePostData(uid, postData) {
const postRef = firebase.database().ref(`user-users/${uid}`);
//this way is useful when key handling before push
var push = postRef.push();
var key = push.key;
return postRef.child(key).set(postData);
//or just push
return postRef.push(postData);
}

Firestore UPDATE a single field but creates another node

I am updating a single field name, which is "name", I am successful on editing it, but it creates another node. like this
This is my Code:
const user = firebase.auth().currentUser;
let uid;
if (user != null) {
uid = user.uid;
const db = firebase.firestore();
const docRef = db.collection('users').doc(uid);
docRef.update({
name,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}).then(() => {
console.log('Profile Successfully Edited!');
}).catch((error) => {
console.log('Error updating the document:', error);
})
}
I already found the solution,
if (user != null) {
uid = user.uid;
const db = firebase.firestore();
db.collection('users').doc(uid).update({
name })....
I just directly put the .update unto the db reference.
Try
docRef.update({
name:"Christian",
timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
You can pass a string var after name:

How do I access the user UID in my firebase database

I am working on a fantasy soccer web app based on a local league. So far, when a user is created using firebase auth, there is a respective node created in my firebase using the user uid as follows:
$scope.signUp = function (){
var username = $scope.user.email;
var password = $scope.user.password;
var teamname = $scope.user.teamname;
var fullname = $scope.user.fullname;
var ref = firebase.database().ref().child('users');
if(username && password){
var auth = $firebaseAuth();
auth.$createUserWithEmailAndPassword(username,
password).then(function(user){
console.log("User Successfully Created");
let usersRef = firebase.database().ref("users");
//child is created under users node with a user's user id as
child name
usersRef.child(user.uid).set({
email: user.email,
userName: username,
teamname: teamname,
fullname: fullname,
total: 0,
week:0
});
$location.path('/home');
}).catch(function(error){
$scope.errMsg = true;
$scope.errorMessage = error.message;
});
}
};
That part works fine. In the database, the JSON tree looks something like this:
users:{
user UID: {
email:
teamname:
fullname:
week:
}
}
I have a service I use for all my views :
.service('CommonProp',['$location','$firebaseAuth', function($location,$firebaseAuth){
var user = "";
var auth = $firebaseAuth();
return {
getUser:function(){
if(user == ""){
user = localStorage.getItem("userEmail");
}
return user;
},
setUser: function(value){
localStorage.setItem("userEmail", value);
user = value;
},
logoutUser: function(){
auth.$signOut();
console.log("Logged Out Successfully");
user = "";
localStorage.removeItem("userEmail");
$location.path('/home');
}
};
}]);
PROBLEM
My problem is that when I go to my 'select player' view, I do not know how to access the user UID so that I can set each user's selection for each week.This is what I tried to do :`
$scope.saveTeam = function(user){
$scope.history = [];
var uid = user.uid;
var ref2 = firebase.database().ref("users/" + auth.uid + "/week");
ref2.set($scope.history);
};
Is there a way that I can access each user's respective "week" child node under their respective user uid?

Firebase security per user

I'm working on a site, using firebase
The security was:
{
"rules": {
"users": {
".read": true,
".write": true
}
}
}
So everyone can add their info, but none can access the main part.
But when someone now types this in the console:
ref = new Firebase("https://xxx.firebaseio.com/users");
ref.createUser({
email: email,
password: password
}, function(error, userData) {});
ref.authWithPassword({
email: email,
password: password
}, function(error, authData) {));
ref.remove();
all userdata will be removed.
All users have their own uid (e.g. simplelogin:58) and storageID (e.g. -Js18LFoT0SmFi2Iq4GP)
could I maybe do something with those? I really don't want anyone to be able to remove all of my user data, but I need to let the users edit their own info, and to remove their account when they'd like to.
Here's some of my code:
function register() {
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
ref.createUser({
email: email,
password: password
}, function(error, userData) {
if (error) {
alert("Error creating user: " + error)
} else {
console.log("Successfully created user account with uid:", userData.uid);
var uid = userData.uid
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + uid)
var newUser = usersRef.set({
faveShow1: "",
faveShow2: "",
faveShow3: "",
faveShow4: "",
faveShow5: "",
faveShow6: "",
faveShow7: "",
faveShow8: "",
faveShow9: "",
faveShow10: "",
uid: uid
});
//var key = newUser.key();
//console.log(key)
login();
}
});
}
function login() {
clear();
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
ref.authWithPassword({
email: email,
password: password
}, function(error, authData) {
if (error) {
alert("Login Failed!" + error);
} else {
console.log("Authenticated successfully with payload:", authData);
thisAuthData = authData.uid;
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + thisAuthData);
usersRef.on("value", function(snapshot) {
for (var i = 0; i < 1; i++) {
console.log(snapshot.val())
if (true) {
globalAuthData = snapshot.val();
//globalKey = amount;
var SS = snapshot.val()
show1 = SS.faveShow1;
show2 = SS.faveShow2;
show3 = SS.faveShow3;
show4 = SS.faveShow4;
show5 = SS.faveShow5;
show6 = SS.faveShow6;
show7 = SS.faveShow7;
show8 = SS.faveShow8;
show9 = SS.faveShow9;
show10 = SS.faveShow10;
//...//
}
}
}, function(errorObject) {
alert("The read failed: " + errorObject.code);
});
}
});
}
function removeUser() {
clear();
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
var refSer = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + thisAuthData)
ref.removeUser({
email: email,
password: password
}, function(error) {
if (error === null) {
alert("User removed successfully");
refSer.remove();
logoff();
} else {
console.log("Error removing user:", error);
}
});
}
function edit() {
clear();
var fredNameRef = new Firebase('https://fiery-heat-xxx.firebaseio.com/users/' + thisAuthData);
var onComplete = function(error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
console.log(thisAuthData);
console.log(globalAuthData);
login();
}
};
if (document.getElementById("form1").value != "") {
var show1 = document.getElementById("form1").value;
}
var show2 = document.getElementById("form2").value;
var show3 = document.getElementById("form3").value;
var show4 = document.getElementById("form4").value;
var show5 = document.getElementById("form5").value;
var show6 = document.getElementById("form6").value;
var show7 = document.getElementById("form7").value;
var show8 = document.getElementById("form8").value;
var show9 = document.getElementById("form9").value;
var show10 = document.getElementById("form10").value;
fredNameRef.update({
faveShow1: show1,
faveShow2: show2,
faveShow3: show3,
faveShow4: show4,
faveShow5: show5,
faveShow6: show6,
faveShow7: show7,
faveShow8: show8,
faveShow9: show9,
faveShow10: show10,
}, onComplete);
}
function logoff() {
clear()
var ref = new Firebase('https://fiery-heat-xxx.firebaseio.com/')
ref.unauth();
//...//
}
}
and my securety rules:
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
},
".read": true
}
}
}
But I can't register or update right now...
To make sure a user's information can only be edited by that user, you want to use auth.uid.
https://www.firebase.com/docs/web/guide/understanding-security.html
The most important built-in variable is auth. This variable is
populated after your user authenticates. It contains data about them
and auth.uid, a unique, alphanumeric identifier that works across
providers. The auth variable is the foundation of many rules.
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
}
}
}
}
To make it a little more clear, auth.uid refers to the currently logged in user, and $user_id refers to the location in database. The $ points to the $location rule variable:
https://www.firebase.com/docs/security/api/rule/path.html
{ "rules": {
"users": {
"$user": {
".read": "auth.uid === $user",
".write": "auth.uid === $user"
}
}
}
}
When a user authenticates to a Firebase app, three things happen:
Information about the user is returned in callbacks on the client
device. This allows you to customize your app's user experience for
that specific user.
The user information returned contains a uid (a
unique ID), which is guaranteed to be distinct across all providers,
and to never change for a specific authenticated user. The uid is a
String that contains the name of the provider you're authenticating
with, followed by a colon and a unique id returned from the provider.
The value of the auth variable in your app's Security and Firebase
Rules becomes defined. This variable is null for unauthenticated
users, but for authenticated users it is an object containing the
user's unique (auth.uid) and potentially other data about the user.
This allows you to securely control data access on a per-user basis.

Categories

Resources