How to loop through cookies and show my email in expressjs - javascript

I am trying to get the name, value field as cookies using loop. in my app.get method and then posting the field values in app.post method, I am using expressjs.
Can please anybody check the 'for loop' below and see my commented lines and brighten my knowledge on how to achieve the email field.
Please also check my uploaded image for UI.
var cookies = [];
if (req.cookies) {
for (var cookieName in req.cookies) {
var cookieValue = req.cookies[cookieName];
// var cookieEmail = req.cookies[cookieValue]; //I dont see my email being posted to server
cookies.push({ name: cookieName, value: cookieValue });
// cookies.push({ name: cookieName, value: cookieValue, email: cookieEmail });
}
}

The req.cookies is a JSON object. When looping over A javascript object you have to be careful you do not grab prototype data.
Take a look at this post here.
https://stackoverflow.com/a/684692/10067782

Related

How can I access a specific attribute of a specific document in a mongoDB collection?

To summarize, I am working with 2 collections - 'usercollection' and 'groupcollection' and I would like to associate users with groups. I don't want to have 2 copies of all the user documents so I have a unique ID attribute for each user that I want to use to associate specific users with specific groups. This is all running on a localhost webserver so I'm getting the input from an html page with a form in it where you enter 'username' and 'groupname'. I tried using the .distinct() function with query as 'username' and the target field/attribute as 'uid'.
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
// Set query and options for searching usercollection
var query = {"username" : userName};
const fieldName = "uid";
// Set our collections
var users = db.get('usercollection');
// Get UID corresponding to username
var uidToAdd = users.distinct(fieldName, query);
This is what I attempted (with some other lines that aren't relevant taken out) but it just returned a null object so I'm at a bit of a loss. Also, I'm still a beginner with nodejs/javascript/mongoDB so the more informative the answer the better! When I do the same code in the mongo shell I can get the actual value of the 'uid' attribute so I really don't know what's going wrong
I am not sure I am following you. But if I understood correctly, if you want to make a relationship between 'usercollection' and 'groupcolletion', you can simply create those 2 collections and each user in 'usercollection' should have a field with 'groupid' as a reference. In this way, you can access 'groupcollection' easily.
Here is an example with using mongoose.
In User model
...
groupId: {
type: mongoose.Schema.Types.ObjectID
ref: "Group"
}
...
Later you can also use 'populate' to fetch 'Group' information.
...
let data = await User.findById(id).populate('groupId');
...

How can I get specific data from firebase database which key value is e-mail?

I need to get specific data from firebase. My database look like this:
and I can get numara value correctly but my other keys which are E-mail and Kullanıcı Adı I can't get it with javascript because of - character and space. How can I solve it? I really need help.
Here my sample code:
rootRef.on("value", function(snapshot) {
var user = snapshot.val();
console.log(user.numara, user."E-mail");
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
//console.log(childData);
});
});
Here console.log(user) output.
If the problem is purely the - in the field name, you can use [] notation to get that specific field. Without Firebase that'd look like this:
var user = { "numara": "0536...", "E-mail": "ekslg..." };
console.log(user.numara, user["E-mail"]);
It's hard to tell, because you don't provide a lot of information, but I noticed in your code, you're using user."E-mail" but your screen capture of the firebase UI actually shows the key as email
Could it be that ?

How to store sessionStorage as a variable so it can be stored in a database

I need to store the email of a logged in user, which I have stored into
sessionStorage with the line of code:
sessionStorage.setItem("loggedInUser", $("#email").val());
But in a different program, I need to store the email as something so that it can be sorted and posted to a php file that inserts it into my database. Here is my javascript so far.
$(document).ready(function () {
//When the submit button on the recruitment form is pressed.
$("#SubmitRecruit").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.loggedInUser;
var forename = document.getElementById("forename").value;
var surname = document.getElementById("surname").value;
var jobType = document.getElementById("jobType").value;
var phoneNo = document.getElementById("phoneNo").value;
//create an array with the details in.
var recruitdetail = {
email: email,
forename: forename,
surname: surname,
password: password,
phoneNo: phoneNo,
}
//log the forename in the console so that we know that the register has been successful.
console.log(email)
//direct the user to the login page and alert them that their registration was successful.
window.location.href = "../index.html"
alert("Your recruitment post was made, thank you. We will get back to you shortly.")
//posts the JSON object to the php file so it can fill the database, and converts the register array into JSON so it can be read.
var jqxhr = $.post("../php/recruit.php", JSON.stringify(recruitdetail)
)
}
})
On the 5th line I tried to make it equal to sessionStorage.loggedInUser with no avail. I know I need to store email as something from session surely, as then it will be passed back into php and stored in db, but I cannot figure out what or how to do this. Any help will be greatly appreciated.
In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
To get the item from session storage try using the getItem method:
var email = sessionStorage.getItem("loggedInUser");
See sessionStorage documentation.
For the ajax request, just pass the object directly to $.post and put the alert in the success callback so it only shows when the request completes successfully:
//posts the JSON object to the php file so it can fill the database, and converts the register array into JSON so it can be read.
var jqxhr = $.post("../php/recruit.php", recruitdetail, function(data) {
alert("Your recruitment post was made, thank you. We will get back to you shortly.")
});
As a side note - if you have a table of users/logins, the email of each user should stored in that table. The foreign key between your users table and other tables would then be an (auto-incrementing) ID, rather than an email address. This makes the system much more flexible (email can be changed, etc).
If by different program you mean different application on different domain, then you can try sending the email value through an AJAX request to be stored in the PHP session.
If on the same domain but just a different app running in a different tab, then you can use localStorage, with the same syntax as sessionStorage. Note that sessionStorage data is limited to the tab in which it was set.
localStorage.setItem("loggedInUser", $("#email").val());
and then
var email = localStorage.loggedInUser;
Or you can use cookies.
https://www.w3schools.com/js/js_cookies.asp

Firebase Javascript: Creating a numeric Index on File Upload to Firebase Realtime

I've got a little app that allows me to upload files, one at a time, to firebase storage. In the process it creates a database reference where it stores the user that uploaded it, the downlodurl etc.
However I have hit an issue as I want to serve back to the user their uploads at random, which is not something easily done by firebase DB at the moment (it would seem - happy to be proven wrong though!!) so I was wondering if it was possible on upload to create a numeric index field that auto increments after every upload?
Would it be as simple as querying the database pulling the max value for the current index and then +1 to it?
Below is the (fairly boilerplate) database referencing bit of the code where I would want to add the index number:
var imagekey = firebase.database().ref('images/').push().key;
var downloadURL = uploadTask.snapshot.downloadURL;
var updates = {};
var postData = {
url: downloadURL,
index:
user: user.uid
};
updates ['/images/'+imagekey] = postData;
firebase.database().ref().update(updates);
});
Ok thanks to the help of Frank below I was able to write the following function to create a data base reference of "index" and increase it by one on every single upload:
var indexRef = firebase.database().ref('index');
indexRef.transaction(function(currentRank) {
return currentRank + 1;
});
However it did have an incredibly odd effect when inserted into my upload function - the upload would continue to work, the file would appear in storage - but only the index database reference would be written, all other information would be lost and I would get an incredibly complex error in the console. Here is the updated code - any ideas as to what I may have done incorrectly?
function complete(){
//write a database reference
var indexRef = firebase.database().ref('index');
indexRef.transaction(function(currentRank) {
return currentRank + 1;
});
var imagekey = firebase.database().ref('images/').push().key;
var downloadURL = uploadTask.snapshot.downloadURL;
var updates = {};
var postData = {
url: downloadURL,
score: 1500,
index: indexRef,
user: user.uid
};
updates ['/images/'+imagekey] = postData;
firebase.database().ref().update(updates);
});
}
If you want to write a value to the database, based on a value that is currently in the database, you'll use transactions.
The trickiest bit with transactions is that they work on a single location in the database. With the data model you propose, you'd be reading from one post (highest index so far) to then write to another one. That would mean that you need a transaction on the entire images node, which is a huge problem for scalability.
What you'll likely want to do is keep a "highest used counter value" somewhere in a single spot and then "claim next value and write updated value" on that in a transaction. That means read-and-update the counter in a transaction, and then write the image with the index you just claimed.

Parse.com: Find all objects belonging to a user with objectId

I have a Class in parse, say Pictures. Each of these belongs to a user. Reference to this user is stored in the Pictures table/class as a Pointer to the user.
In my cloud code I am trying to get all Pictures belonging to a user, using master key. Following is my code:
Parse.Cloud.define("getPictures", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Pictures");
query.equalTo("user", request.params.user);
query.find({
success: function(results) {
var status = "Found " + results.length + " pictures for userId " + request.params.user;
response.success(status);
},
error: function() {
status = "No pictures exist for userId " + request.params.user;
response.error(status);
}
});
});
This code outputs that there are 0 pictures for a certain user with id 'xyz' for example. However, I can see that the user has a lot of pictures stored.
I have also verified that the problem is not with using master key, as I see in the console log that the code is being executed as master. Moreover, if I query for a picture by objectId, it does come out in the results, which means ACL is not the problem here.
I think I have to use relations/joining here, but I am not sure how to do that.
Pointers are stored as objects in Parse database, so if you try to compare a string to an object with query.equalTo() function, nothing will be found. This is how pointers are stored:
{
__type: 'Pointer',
className: '_User',
objectId: user-object-id
}
If you are querying a class with pointers and want your result comes with the whole object nested, you should set this in your query:
var query = new Parse.Query('Pictures');
query.include('user');
In my queries when I want to search by a pointer column, I compare my user object with the nested user object.
var user = new Parse.User();
// Set your id to desired user object id
user.id = your-user-id;
var query = new Parse.Query('Pictures');
// This include will make your query resut comes with the full object
// instead of just a pointer
query.include('user');
// Now you'll compare your local object to database objects
query.equalTo('user', user);
query.find({
success: function(userPicture) {
response.success(userPicture);
}
});
Anyway, seems that if you have many pictures related to an user, you probably are searching for parse relations instead of pointers: https://www.parse.com/docs/relations_guide
If you write a query to retrieve a parent object and a child object to which you have pointer, but no read access as per ACL, then the query may return only parent object and child will be null because the ACL wont let you read it.
There may be a problem with your params. If "user" is a pointer, then 'request.params.user' is incorrect, because PFObjects may not be sent as params. If "user" is a pointer, use 'request.user'. If request.params.user is a string of the userId, you could use the Id to reconstruct a PFObject shell before the query as was suggested by Murilo already, but deleting the "user" param and using request.user would shorten your code and not duplicate any values. Murilo's solution is also beneficial because you could pass a userId other than the current user's Id.

Categories