redirect before loading URL - node.js

I'm developing a node.js app where I'm using passport to build OAuth authentication system. I can access the user through request object in each resource load after configurating it. But my question is: How can I do to check before every URL load - resources defined with app.get('/', function(..) {...}) - if user is loged and redirect the client if it's not loged. I could do it just adding a test in every method, but this is not what I want.
Thanks!

You want a middleware that checks whether the user is logged in.
isAuthenticated = function (req, res, next) {
if (req.user)
return next(); // All good, let the route handler process the request.
else
res.redirect('/login'); // Not logged in.
}
And to use it on every route that needs to be logged in:
app.get('/something', isAuthenticated, function (req, res) {
// Only in here if the user is authenticated.
});
You can also use the middleware on every route, by doing app.use(isAuthenticated), but you will need to have extra logic in the method to not create infinite redirect loops to /login, etc.

Related

How do I redirect a failed login attempt in node-oidc-provider

I'm setting up an OpenID Connect Provider using node.js, express.js, and node-oidc-provider. I've been working my way through the examples at https://github.com/panva/node-oidc-provider-example/tree/master/03-oidc-views-accounts, but it never deals with a failed authentication. How do I redirect the user back to the login page if they mis-type their password?
expressApp.get('/interaction/:grant', async (req, res) => {
// The initial route hit by the client (Relying Party) that renders the login view if needed.
...
});
expressApp.post('/interaction/:grant/login', parse, (req, res, next) => {
User.authenticate(req.body.email, req.body.password)
.then((users) => {
// returns an array of user objects that match the credentials
if(!users.length)
{
// What now? I can't just redirect back to /interaction/:grant - I get session not found
}
// the rest works well enough (for now)....
...
}).catch(next);
});
Just like in any express app. Think of it this way. Only resolve the interactions with success, or error if you wish to exit the interactions and return control back to the client.
I tend to develop interactions separately and only plug them to oidc-provider when they’re done.

Stop duplication of passportjs isAuthenticated code in Express route files

I am using passportjs for my authentication.
I have lots of different routes throughout the project, 95% of them require the following function:
// Middleware functions
function isAuthenticated(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/login');
}
At the moment, I am putting this function at the bottom of EVERY route file.
Is there a way to write it once, and be able to use it in all the route files?
If you add that middleware before the routes that require it, all requests will pass through it before they get forwarded to the correct route handler:
// doesn't require an authenticated request
app.use(router1);
// add the middleware just once
app.use(isAuthenticated);
// all following route(r)s require an authenticated request
app.use(router2);
app.use(router3);
...

How to use authenticated middleware properly in nodejs

I just started working on node using express framework.
app.use('/', auth, users);
and this is my route file
router.get('/' , function(req, res, next) {
render("dashboard");
});
router.get('/first' , function(req, res, next) {
//first request
});
router.get('/second' , function(req, res, next) {
//second request
});
so on...
My question is, when i pass middleware it checks for every request whether its authenticated or not using passportjs, but suppose i have a dashboard and i am sending 10 ajax requests to grab data for the widgets. So only for dashboard it will call deserialize function 11 times ,first to render the page and then for 10 ajax request. I read answer given over here,
How to properly use Passport.js?
But is it fine to go with this approach?
Yes, it is fine to go with this approach if you don't want to have security issues. You have to check the user for every request, it is very simple someone to check the network tab in the browser debugger, understand what's going on and then start spoofing your requests. You can't sacrifice security for performance because you want to execute few query less.

StormPath groups authorization using express-stormpath

Using stormpath.groupsRequired middleware call,
router.get('/', stormpath.loginRequired, stormpath.groupsRequired(['org1-admin']), function (req, res) {
res.render('index', {});
});
I can not hardcode the ‘org1-admin’ role, what options do I have? If I put this into a session , the session is not available for middleware. Any thoughts?
The user role ‘org1-admin’ will be identified when the app is launched based on the org1 param passed in the initial launch request url and ‘admin’ role read from config entry.
After the initial launch , this role should be available for subsequent routes to authorize. Appreciate your feedback!
If the group to check is determined on a per-request basis, you’ll need to modify the flow to use the groupsRequired middleware more like a function:
app.get('/', stormpath.loginRequired, function (req, res) {
var group = 'foo'; // grab the group from your request context
stormpath.groupsRequired([group])(req,res,function(){
// If we got here, the user is in the group. Otherwise the groupsRequired middleware would have ended the response with 403
res.render('index', {});
});
});
I hope this helps! This is a good use-case and I’d like to add something to this library which makes it easier to do this.

allow access to html page only to logged in users

I have app.html in a public folder which is serving static files to express.
I have used code from here.
But instead of profile.ejs from views folder(as per the code in link), I want to serve app.html from inside of public folder.
app.get('/app.html', isLoggedIn, function(req, res) {
res.render('app.html'/*, {
user : req.user // get the user out of session and pass to template
}*/);
console.log("APP.HTML");
});
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
But it does not restrict the access to loggedIn users and I am able to access it directly after logging out as well.
What could be wrong here?
The problem is most likely that you have express.static() before your app.get() line. The static middleware checks if the file exists and sends it if it does. So you need to put that app.get() before your express.static() middleware.

Resources