express-session: send extra detail in 401 response - node.js

I am using express-session and was wondering if its possible to send some additional details in the 401 response express will send back when a session is no longer found.
I would like to distinguish when a session has expired vs when no session is found, so I can send some extra details in the response body that the client can use to then show some information text to the user that their session has expired.
Is this possible?
Hopefully I am making sense with this question!

If I understand you correctly, then you can send some json with status 401 to let client know more about the issue.
e.g.
res.status(401);
res.json({'message': 'session has expired'});

Related

Axios Interceptors Prevent Error logging into console

Using interceptors for the first time to refresh an expired JSON Web Token. The response interceptor I implemented works successfully in refreshing the token every time, but still logs the error I throw at the server end from the jwt.verify. (I see 403 forbidden each time before token refreshes).
If I'm doing it correctly on the server end and in the client end, should this error even be logging in the browser? I don't want this error to be logging into console. Now I'm thinking I have to refresh the token before it even expires and not even use interceptors.
check the order of responses from the server. Judging by the description, you are not waiting for the generation of a new token. If in JS terms check async/ await sequence

What is a good approach for a /forgot route to respond?

So when you are responding (server-side) to a /forgot-password route what is the best response to it? ( In the situation that you don't want to expose what users you have in the DB and still hint the app that the user does not exist)
I was faced today with this scenario in which I respond in that route with 200 but my colleague that is working on his app wanted me to send an error so he could implement an SMS recovery form.
Imagine this:
POST /forget-password
Body: { username: 'test' }
And you respond with 404/400 and an error message like:
{
statusCode: 404,
message: 'User not found'
}
Is this a good practice? Or not?
Why I am asking this? When you are responding to a client with 404 you expose what usernames you have in your database and this might be a security breach.
What is the best approach for this, and why?
In my opinion, I'm guessing that you should respond with 200, in either case, to not let any kind of scenarios for the client.
You had it correct at the beginning. You should return an HTTP 200. This is to prevent someone from looping through with various usernames to figure out who exists, etc.
What I typically do is accept whatever they put in, then email the provided information either a "sorry, that account doesn't exist, create one here" or "here's your link to reset your password".

How to Get Current User in Backend with Firebase in Node.js?

I am so confused,
all the Firebase authentication tutorial online are teaching how to login in frontend,
of course you can get the token and send it to server for verification if its a post request,
but what about normal get request like a page request? I have installed firebase-admin already but i didnt find any method for getting current user........
i am using node and express
for example
app.get('/', function(req, res) {
const idToken = (where can i get the token??)
console.log(idToken);
res.render('index.ejs');
});
You still have to arrange for the auth token to be sent in the HTTP request. You can do that with a header in the request. Sample code showing exactly this case can be found in the official samples. This will work for any HTTP method, and is a lot better than trying to use a POST body.
The sample uses the Authorization header to transmit the token and verifyIdToken() to make sure it's valid.

How to create sessions in a strong way and store them in cookies in node js?

In my login module once I log in I pass my request to a header to store a session here is the code
var series = rand.generate(16);
var token = rand.generate(16);
var loginToken = new LoginTokens({
userId: req.user._id,
series: series,
token: token
});
loginToken.save(function(err, l) {
if (err) {
console.log(err);
} else {
console.log(l);
res.cookie('loginToken', JSON.stringify({
series: series,
token: passwordHash.generate(token)
}));
res.status(200);
res.set('Content-Type', 'application/json');
res.end(JSON.stringify({
'success': req.params.res
}));
}
});
Though this code was pre-written and I don't understand it much(I don't get the point of randomly generating 16 digit number and saving it if somebody does please explain)
I have been tasked with implementing log out and As I don't understand the rationale behind above code I want to implement my own session module such that even if the same user logs in from a different device, both sessions will be maintained and logging out from one device will not log out someone from all device.
So now the point comes that the session id will not be based on user id. Also there is a module called express-session which I don't know if I should use or not, personally I feel that after reading it up on GitHub that what it will do is create a session id for me, which again I will have to save in my database, so why to import a module, instead I will base64 encode a random number like above and use it.
So what I want to ask is the real question
How do you implement sessions in node js?
My understanding of life cycle
A user signs up you see if he/she exists in the database and if he does you raise an error message and if he/she doesn't you create a username for him, probably by email id.
You then via code log him in. In that process, you first check if he is there in the database. If he is you go ahead take the _id field and try and create a session object. Ques what does your session table should look like? What all parameters should be present in sessions table? Then how do save them into res.cookies? Then what do you do with all those cookies, like on client side?
While implementing logout. My thinking is using passport.logout will remove the user object from request header but, I will have to first remove the entry from sessions table somehow empty the cookies and then do req.logout?
Can somebody please answer the above doubts?
I asked a very specific question but realised after the comment that what I need is logical clarity and I did not find one on youtube videos nor on SO posts, so if someone can share their views mostly in code, with some explanation it would be great.
Cookies get deleted by sending a new cookie with the same name (some invalid data would be good) and an expiry in the past.
passport.logout() removes the session cookie that passport uses to maintain the current user, the next request will no longer have the cookie and will appear as an invalid request.
I'm not sure why there's a loginToken as well as passport authentication, apart from allowing you to invalidate sessions server side (by deleting the appropriate token from the database) Check if your passport strategy configuration has any checks against LoginToken during it's deserialize user step (this is where passport takes the session cookie and turns it into a user against the request)

jwt on node - how does the client pass the token back to the server

okay.
I think I have failed to understand an elemental part of token based authentication.
I am using node with express and am using jwt to prevent access to my site if you haven't logged in. I can create a token on the login page, and I can send it back to the client and store it in localStorage/cookie. Now if the user wants to navigate to another page they will type in a url and trigger a get request.
How do I access that token from localStorage/cookie and pass it to the server before I load the page as part of the get request. My assumption is that there should be a way of passing the token to the server - intercepting it in the middleware - and loading the page if the token is legit, or redirecting to the login page if the token isn't validated correctly.
On a post request this would be much simpler as you can fetch the token and pass it as part of an ajax call, after the page has loaded.
I have seen references to including the token as part of the request header (authorization bearer). I assume this only works for post, because if you were able to set the header parameter 'globally' then why would you bother storing on the client side in a cookie/localStorage.
So as you can see I am a little confused by the workflow. It seems like I am going against the grain somehow. Any clarity would be much appreciated.
If you are using localStoage in order to store the JWT, then the easiest way to pass it to the server is by retrieving first the token from the localStorage with localStorage.getItem('token') (or whatever your token name is) and then inserting it in the header of the request (either it is GET or POST/PUT/DELETE). Depeding on the library you are using to handle your http requests on the client, there are different ways of doing so. In jQuery for example, you can do the following inside the AJAX request:
$.ajax({
url: API_URL + "/endpoint",
method: "GET",
beforeSend: function(request){
request.setRequestHeader("Authorization", "BEARER " + localStorage.getItem('token'));
}
})
After this, on the server side simply access the parameters by accessing request.header options just as you would normally do. Hope this helps!

Resources