0

I have a problem with user authentification in my app that runs on Node.Js / Express.Js

Basically, when the user logs in the main interface (html), they are shown a graph, which is obtained through an API path (/api/data/json), which also requires authentification through

exports.auth = express.basicAuth(User.authenticate);

in routes/api.js

I tried "telling" routes/api.js that the user is already authorized through passing it one of the res.locals.user parameters, but it didn't help...

So my question: is there any way in Node.Js to store user's login details in a session variable (like you can do in PHP for example), so that it's passed on to all the components when authorization is needed, to avoid users having to re-authorize when they access another part of the app?

Thank you!

2 Answers 2

1

The basicAuth middleware populates req.user with the username when authentication has succeeded. To check if user is authenticated at any middleware that comes afterwards e.g. in your routes/api.js, all you have to do is check if req.user is defined:

if (req.user) {
    // User is already auth'ed; provide secret data
} else {
    // Proceed to next middleware to provide a standard error message
    next();
}

Alternatively you can also redirect to another route with res.redirect('/goToOtherpage') or you can respond with an HTTP error with res.send(401) to signal Unauthorized to the caller.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to do that but when I launch app.js with this check it says ReferenceError: req is not defined. I tried to implement a check of this kind: if (req.user && typeof req.user.userId === 'undefined') but it still didn't work...
Where are you placing this check? As I mentioned this check goes in any of following middleware or route handlers where you need to know if the user is authenticated. E.g. setting up the route for /api/endpoint you'd do: app.get('/api/endpoint', function(req, res, next) { <req.user CHECK HERE> });
0

Not sure if this will be of any use but you could hook into the HTML5 session storage. Here is an article going into it a bit more.

http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/

Here is an example taken from the article on how to use it.

//save a value
sessionStorage.setItem("name", "Nicholas");

//retrieve item
var name = sessionStorage.getItem("name");

//get the key name for the first item
var key = sessionStorage.key(0);

//remove the key
sessionStorage.removeItem(key);

//check how many key-value pairs are present
var count = sessionStorage.length;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.