Node & Express + jQuery: After authenticating save for session - javascript

I managed to make the user able to authenticate using name/pass. What I'm trying to achieve is, a disabled dropdown, when he authenticates, it gets enabled, then he can access files through the dropdown list. All of that I managed to make, one thing I'm puzzled with is how can I check if he already authenticated or not? So no one would inspect the html code and get access to the files.
I need a way to identify if a client (jQuery) has authenticated or not, something like session variables that ends with closing the page.
EDIT: I need it to be secured, I want to store a boolean that will allow the client to view all the log files.

Store this boolean in an Express session, and select which page to send to the client.
// enable session support
app.use(express.cookieParser());
app.use(express.session({
secret: 'secret key for signed cookies'
}));
app.get('/foo', function(req, res) {
req.session.authenticated = true;
});
app.get('/bar', function(req, res) {
if (req.session.authenticated) {
// send page with files
} else {
// send page without files
}
});

Related

Is this a secure enough method to recover data?

I'd love to know if this method I'm using is secure enough to use on a public project, since I can't really find any other way to retrieve my id from my currently logged in user, but it's a fairly straightforward method , I find. If this method is not secure would it be possible to have a way to proceed? Thanks in advance.
I have a button for example when I use the send of the html that there is inside my div userid on the server to then use this information to make SQL queries from my app.js server.
I use socket.io hbs express node js jwt mysql
From my pages.js file generated with the express library where the main roads of my website are located, I send my user ID.
router.get('/accueil', authController.isLoggedIn, (req, res) => {
if(req.user) {
res.render('./accueil', {
data: req.user.id
});
} else {
res.redirect('/');
}
});
With Handlebars I display this data in my index.hbs (display: none;).
<div id="iduser">{{data}}</div>
Then I get my iduser div on my client.js
let userid = document.getElementById('iduser').innerHTML;
// (My method to display this div)
socket.on('uid', (data) => {
pargent.innerHTML = JSON.stringify(data.data[0].argent);
})
//
So I want to use this userid variable to make SQL queries from my app.js.
(let userid = document.getElementById('iduser').innerHTML;)
I am using socket.io for communication between client and server to send my userid data
Example :
db.query('UPDATE users SET money = money + ? WHERE id = ?', [100, theUserId]);
No
Never trust user supplied data.
References:
https://www.oreilly.com/library/view/http-developers-handbook/0672324547/0672324547_ch22lev1sec1.html
https://flylib.com/books/en/1.290.1.90/1/
https://www.garybell.co.uk/never-trust-user-input/
https://medium.com/#berniedurfee/never-trust-a-client-not-even-your-own-2de342723674
https://www.invicti.com/blog/web-security/input-validation-errors-root-of-all-evil/
https://laravel-news.com/never-trust-your-users
https://www.wearenova.co.uk/nova-blog/when-it-comes-to-online-security-why-you-should-never-trust-a-client
It depends on your authController.isLoggedIn logic,
But I would like to suggest an alternative solution simple as that;
iron-session
Read their docs, it's matches your use case and easy to use; here is equivalent of the snippet you provided with iron session:
//initiate session middleware yourself
router.use(session)
// later here
router.get('/accueil', (req, res) => {
if(req.session.user) {
res.render('./accueil', {
data: req.user.id
});
} else {
res.redirect('/');
}
});

How do i set a cookie on different node js routes?

I'm developing a user based project, using node ( express, mongoose etc. )
I currently use JWT and the token has the user id in it, I know how to send a cookie when someone logs in, but I don't know how to make the cookie work on all routes, like basically when a user is logged in and goes on route /test the cookie is still there.
I think what I'm trying to achieve is called "session/cookie based authentication", could be wrong idk.
Once you set a cookie, from within any route, with
const myCookieValue = 'whatever'
res.cookie('myCookieName', myCookieValue, {
maxAge: 3600*1000, /* one hour */
httpOnly: true
})
you can retrieve its value, from within any route, with
const myCookieValue = req.cookies.myCookieName || 'yo! no cookie! something is wrong!'
The cookie-parser package makes this possible, handling the gnarliness of the the HTTP header for you.

How to get the params in a Express route when I am using app.use() for the home page in my server

So, basically I have this middleware on my server.js file: app.use(express.static(__dirname + '/public')) for the home page.
It's possible to show the same home page when a user hit this route: app.get('/ref=:refId') and still show localhost:3000/ref=Asldoe2231sSLexe2 in the address bar?
Now I know that I can achieve this behavior using query string like so: localhost:3000/?ref=Asldoe2231sSLexe2 and then get the query string using req.query.ref on the server, the problem is I cannot use app.use(express.static(__dirname + '/public')) directly if I have this route app.get('/', (req, res) => {.... How can I solve this?
My goal is either grab the refId value on the client, send it to the server and check if exists in the database or check it directly as soon as the client hit the route, I rather prefer the second option which is a cleaner way of doing it.
What you want to do don't have a relationship with
app.use(express.static(__dirname + '/public')). It is used for giving the path to static files such as CSS, images in your application.
You can get refId by req.query.ref and pass it to the page you are rendering.
One way is :
res.locals.refId = req.query.ref and in your view use refid
Second way is :
res.render('<file_you_are_rendering>',{refId:req.query.ref})

How can I dynamically assign a database path in Express.js based on login?

I have a backend service that I would like to use as a single point of entry for my web application, and dynamically assign a database path based on the user login.
I realize that this is not a scalable solution. I intend to use it during a testing period with several clients (accessing the ALPHA database), and also setting up a demo (accessing the SAND database).
I have the following module that I have written as a simple test to see if the login is for the demo user, all other logins will go to the other resource:
config.js
var express = require('express');
var app = express();
module.exports.dbPath = function (login){
console.log('login - ', login);
if (login === 'demo#mysite.com'){
return process.env.DB_SAND;
} else {
return process.env.DB_ALPHA;
}
};
My question is, how can I manage each unique login and assign a globally accessible reference for that session to direct each user session consistently to the correct database?
Am I overcomplicating this? If there is a different approach that would be a better practice I would welcome a suggestion in another direction.
I would use it as a middleware, and attach it to the req object for each user, something similar this:
module.exports = {
dbPath: function(req, res, next){
var login = req.body.login;
console.log('login - ', login);
if (login === 'demo#mysite.com'){
req.dbPath = 'DB_SAND';
} else {
req.dbPath = 'DB_ALPHA';
}
next();
}
};

meteorjs persistent setUserId to switch user

i'm trying to use meteor this.setUserId() server side and Meteor.connection.setUserId() client side . It is to let admin have control on all users accounts and to be able to login without passwords.
Server side:
Meteor.methods( {
"switchUser": function(user_id) {
this.setUserId(user_id);
return user_id;
}
});
client side:
Meteor.call("switchUser", user_id , function(error, idUser) {
Meteor.connection.setUserId(idUser);
Router.go('/profile');
});
It's working but is not persistent. After refresh or moving to another page ,the logged-in user is restored to the first (admin).
How can i swith user permanently with meteorjs ?
I dont know if it works but if you look on local storage you see that its set a login token Meteor.loginToken also among with user id Meteor.userId, maybe you have to set that too for the new user when you switch. Or you should consider making a method for login without password https://github.com/meteor/meteor/blob/master/packages/accounts-base/accounts_server.js#L107

Categories