How do I make my node express page uniqe to every new user - node.js

What I am using - EJS, JS, NODE, Express.
I am new to this and have been getting away with googling stuff so far.
So I am making a website and I want it to be unique for every new tab. Right now, if one person clicks a button that displays a message, and I go to a different tab and open the link, I can see the message that the first person set. I read something about express-session and session Id and sending the requests through the sessionID to make sure it is sent to the right person. But I don't know how to implement them here
EDIT: Here is my best attempt trying to make sense out of this.
router.post("/", (req, res, next) => {
Actors.find({}, (err, actorFound) => {
if (err) {
throw err
} else {
res.render("welcome", {
actors: actorFound,
findItems: suggested
})
}
})
})
When I "call" this on local host it would basically dump everything from the data base. Which is what it is supposed to do. However, if I open localhost using a different web browser, (trying to simulate a different visitor) I would find that my data from actors is already dumped on the page. Does this make sense. I will try to explain anything specific if you have any question and thank you very much.

Related

In node.js with express, is there a way of changing the url of a link on the fly?

I have a link on a page:
Back
which of course takes the user to '/application-reference'. However, if the session has timed out, I want the user to taken to '/session-ended' instead. Session timed out is detected by the absence of request.session.
I've tried changing the href to send the user back to the same page (i.e. the link is in 'security-code' and takes the user to 'security-code') with the idea that the handling code can look for request.session and decide which page to redirect to, only I can find no way for the code to detect that the page has been called by itself via the back button.
I think the answer is to put something in my express module so that the router.get call that redirects to '/application-reference' will under the right circumstances redirect to '/session-ended'. But I have no idea how to go about this.
I suppose the ideal would be for the '/session-ended' screen to be invoked any time the user clicks on any screen once the session has timed out.
Any suggestions?
Inside your /application-reference-handler you could check if the session on the req-object is still valid. If not redirect the request to /session-ended:
app.get('/application-reference', (req, res) => {
if(!req.session) { // or a more detailed check for the session's validity
return res.redirect("/session-ended");
}
// rest of the handler-code ...
});
An better way to do this is to define a separate middleware to check the user's session - this allows you to reuse this middleware and not having to duplicate the check in your handlers:
function validateSession(req,res,next) {
if(!req.session) { // or a more detailed check for the session's validity
return res.redirect("/session-ended");
}
// all is good, go to the next middleware
next();
});
app.get('/application-reference', validateSession, (req, res) => { ... });

Get time a button is clicked, store it in the database then display on page in React

This is a bit of a large question I know. I am building a website in the MERN stack- and I want to be able to have a user click a button "checking in" and then have the time that they clicked stored in the database. Then in the React component display the time that was logged from the button click.
the node.js part of the question is the part I am stuck on. how would you suggest I do this?
what I have
router.get('/', auth, async (req, res) =>{});
I really have no clue where to start.. any help would be appreciated! a general idea would be helpful or documentation that points me in the right direction.
If you're trying to get the time the user checked in when they click on the check-in button, you can use the in-built javascript Date function to get the current date and time.
In the onCLick method from the frontend, you can grab the current time by declaring a new Date variable like:
var timeCheckedIn = new Date()
then you can send timeCheckedIn to the API
In your API, you can accept the time via the object or form data you're sending to the API like:
router.get('/', auth, async (req, res) => {
const { timeCheckedIn } = req.body
});
you can read more on using expressJS to handle the body of a request here
To display the date stored in the database, that will also depend on how you're retrieving the data from the server.
you can try the above to see if it helps

MongoDB, Node, Express, EJS - Pass a array/variable from backend to frontend (from route to client)

I've been trying to figure out a better way to push a variable from the backend to the frontend. Right now I do something like this.
I have a MVC-pattern, so when hitting the route
app.get('/fil', middleWare.isLoggedIn, user.fil)
... trough node does some querying the DB, and pass on the data.
exports.fil = async (req, res) => {
try {
faktura = await Lan.find().populate('client', 'namn kundnr')
res.status(200).render('pages/createInvoice', {
faktura: faktura
});
} catch (err) {
return res.status(500).send({
message: err.message || "Some error occurred while retrieving datas."
});
};
};
... it generates the page, with the help of EJS (i love EJS) and then pass it on to the client/user.
And in the .ejs-file that is served to the client/user I add the following
<script>
var fakturor = <%- JSON.stringify(faktura) %>;
</script>
which then means that I use up the variable and work with it with JS.
And this is where my question pops up. Is this a good way to do it or is there any other way to handle it?
I guess one idea is to let the user to query the DB straight from the page, but in my case I believe it wouldn't actually be better for the user to do so (the user will reieve like 100 different rows that they will be able to filter and then download a file of)
But is there any other ways I could do this without the script-tag? Like i said, I guess a ajax-call from JS/the client could be used but could you do it any other way? Can EJS do it any other way?
ejs is used for static pages mainly, if you want to build a dynamic page I would look for a single page application framework like angular and react.
if you still want to use ejs you can use ajax call to the server to load a variable from the DB.
I would never query directly from Front end to DB because then you are not controlling the security of the server, always go through the BE.
also try to think if you really need a variable in the front end, can you solve your problem using rendering only?

Is it bad practice to wrap express app within socketio connection?

I'm making a webgame, and if I have a route that looks like:
app.post('/create_account', (req, res) => {
var email = req.body.email
var pass = req.body.pass
res.json({response: "created"})
})
Anyone can post data to mywebsite.com/create_account using postman, or curl or something, and my website will start creating account for them even though they are not even on my webpage.
I found an interesting workaround, and I wanted to know if this is safe, or even a good idea. Basically I wrap my app routes within a socket.io connection:
io.on('connection', function(socket) {
app.post('/create_account', (req, res) => {
//code goes here
})
})
I tested it, and it seems that this way you can only post to /create_account if you are actually connected to the webpage.
What (if any) are the disadvantages to doing this? If this is a bad idea, whats's a better way to prevent people from posting data if they aren't on my site.
#Ruslan's suggestion about CSRF tokens is sound and probably your best option, wrapping everything in socket.io seems like too much complexity. Here's a library that does that: https://github.com/expressjs/csurf

Authorization in node.js

Coding a news website,I'm trying to make authorization so that only the author (who posted the article) is able to edit and delete it (these buttons appear at the bottom of the page and are visible to all the users).
But then there are certain news/websites which don't have a login/sign up option. For example : http://www.denofgeek.com/us .
Because they have no authentication, does this mean that they have no authorization?
How are they able to edit/delete the articles if the settings for the authors are the same as the rest of the users ?
Code:
app.get("/blog/:id/:title/edit", function(req,res) {
Blog.findById(req.params.id, function(err, foundBlog) {
if(err) {
res.redirect("/blog");
} else {
res.render("editBlog", {blog : foundBlog});
}
})
})
//UPDATE BLOG
app.put("/blog/:id/:title", function(req,res) {
req.body.blog.body = req.sanitize(req.body.blog.body);
Blog.findByIdAndUpdate(req.params.id, req.body.blog,{new: true}, function(err,updatedBlog) {
if(err) {
res.redirect("/blog");
} else {
res.redirect("/blog/" + req.params.id + "/" + req.params.title);
}
})
})
How should I go about editing/deleting the articles if I don't want to use authentication?
P.S : I can, of course, remove the edit and delete buttons appearing on the page and send PUT and DELETE requests via Postman, but it's obviously a bad idea!
After going though the website you mentioned the have one for users and one is separate for admin where author can login and make updates add new post and delete old once.
It is not possible that without any authentication you can make edits / delete for a specific user.
So you should do it like just create a separate panel for author and set a login page for that so only the authorized person can enter the page and there you can implement the functionality of deleting/updating even I would advice you to use authorization so if anyone came to know about your apis they cant make edits until they have the token to that you can use this jsonwebtoken to implement authorization.
Hope this helps.

Resources