Is the req.user passed to the client? - node.js

I'm using node.js, express, express-session and passport.js to handle authentication in my project. In my routes.js I handle get-requests like this:
app.get('...', isLoggedIn, function(req, res, next) {
var user = req.user;
...
});
Inside the function I can get the user from the request parameter. My question is where the user object comes from? Is the user object passed to the client and back? Can the client change the user object in an attempt to inject code into my database?
Thanks in advance!

req.user is intialized when session is created. req.user is equal to object user stored in session. Watch this video for more informations about authentication in node.js .And no, client cannot interact with you database through that.

Related

Authentication without Passport

I'm using active directory to authenticate users, so I thought I didn't need to use Passport and that all I would need to do is after the password checks out is to create a global(?) boolean with res.locals to indicate that the user has been authenticated.
I've tried something like this in a controller function:
ad.authenticate(username,password, function(err,auth) {
//some of the things I tried unsuccessfully -- should be true after logged in
res.locals.auth = auth
app.locals.auth = auth //app not defined
})
However, I've discovered that when I call a later function checking if the user is logged in as part of middleware for a diff route, res.locals.auth and app.locals.auth are either false or undefined. I've tried setting both vars in my server.js file at the beg with the code below but that didn't work either...
app.use((req, res, next) => {
app.locals.auth = false;
res.locals.auth = false;
next();
});
So my question is, what var/where should I be saving the authenticated status? Or should I just use passport instead because there's some security concern that I was unaware of? What is the point of the isMemberOf in passport setup example?
https://www.npmjs.com/package/passport-activedirectory
All I want to do is just check user credentials and basically recreate req.isAuthenticated in Passport because I couldn't figure out how to use it because of the isMemberOf.
Usually the server sends back a token containing some useful data (user or session id, expiration date) either by cookies or by JWT (json web token).
Then a client puts the token into every request to the server . The server validates expiration date and handles requests.
Cookies will be put into a request by the browser automatically. JWT should be put into a request by your client code.

How to have global currentUser variable in Controller for Express using Passportjs?

I'm using the MEAN stack with passportjs for authentication. I know I can automatically pass currentUser to every view, through this code:
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
However, I also would like to access currentUser throughout my controller, for certain database queries. For example, checking whether or not a user has liked a post, before sending the relevant information to the view. Is there a similarly easy way to access currentUser in all of my different routes/controller logic?
I know I can use req.user to get the user within the logic of a route. But ideally I don't have to do var currentUser = req.user at the top of each route's logic.
Thanks in advance for your help!!

node JS express framework sendFile("home.html",{context?})

I'm reading the Express framework docs, making my basic login/redirect page routes.
The following route accepts the submission:
app.post('/',function(req,res){
//console.log("USERNAME: "+req.body.username);
//console.log("PASSWORD: "+req.body.password);
res.redirect('/chat');
});
and this:
app.get('/chat', function(req, res){
res.sendFile(__dirname + '/templates/chat.html');
//console.log("request");
});
takes the user to a new page.
How do I send context? Should I be using res.render()? Neither function seems to contain an option for data like {username:req.body.username}. How should data be passed between routes?
Generally to handle logins with express you'd use something like passport's local strategy, which attaches a user object to the request object (req.user) for you for each route. I don't know that what you're trying will work in a larger context -- you'd need some kind of session-based middleware like express-session at the very least, so you can attach variables per session (I think it gives you req.session). By default, express has the capability to store information for one request/response cycle (res.locals) or for the entire instance of the app (i.e. for all users) (app.locals).
As far as getting data into views, you would use res.render with something like EJS, pug, or another view engine. For example, if in your route, you had something like:
route.get('/', (req, res) => {
res.render('template', { username: 'yourname' })
}
you can refer to that in your ejs template like so:
<h1>Hello, <%= username %>!</h1>
which will get sent back as this:
<h1>Hello, yourname!</h1>
So, to answer your question:
You would use res.render to get variables & data into your views
You don't share data across routes by default except app-level data that applies to all users, which can be set on app.locals
You can use authentication middleware like passport and session middleware like express-session to keep track of user information across routes per session.
Hope this helps! Good luck with express!

How to persist additional data added on fly in Passport sessions

I have a simple authentication system built on Passport.js on top of Node.js. I have a use case where I need to persist Organisation ID in the session which is to be updated on hitting of a particular route.
I did this using the middleware:
app.use('/switchOrganization',function(req, res, next) {
if(req.user) req.session.passport.user.activeOrg = 'my org';
next();
});
But this doesn't persist the data in other routes:
app.route('/someRoute').post(function(req,res){
console.log(req.session.passport.user);
});
It doesn't contains the 'activeOrg' value. Where I am going wrong?
The user object is deserialized into req.user in the deserializeUser function. This happens on each request. So if you make change to req.user in one of the route handlers, and expect it to be persisted for the route handlers that follow it, it'll only be the case for that particular request. If /someRoute is requested anew, it will not have the the changes you made in another route which wasn't invoked in the new request.
You should instead persist the changes to database so that when the deserializeUser function is called for the next request, it'll have your data from the beginning.
I am using redis sessionStore. And if I write to req.session, then data persists on redis store:
req.session.access_token = result.access_token;
req.session.refresh_token = result.refresh_token;
req.session.instance_url = result.instance_url;
Redis Screenshot

Node, express, passport - updating session after updating record

I'm rather new to node, I have started writing a small app and am working on my user auth and profile. I'm using express, passport and ejs. I've got passport working and have my user redirecting to a profile page that requires additional data before the user begin's to use the application. My question is:
What's the proper way to update the user's session (created at passport.authentication) when a user updates their profile data? I would like to update the user session in order to hit it rather than the data base for basic user data.
If your using express you have middleware that looks like:
function (res, req, next){}
When you get session data you can add it to the req object.
function (res, req, next){
// get the session here...
req.session = session;
}
Then any other middleware will have access to the req.session object which will contain the user's session.

Resources