Protecting route in node js with passport js - javascript

I've an express app for which the main server code is in server.js file.In server.js file there is a route app.get('/dashboard',require('./dashboard/dashboard.js').
In dashboard.js file I've many routes like /profile,/editProfile etc.Now to protect all my /dashboard routes should I implement req.isAuthenticated() to each route? or is there any other way to protect all my /dashboard routes by implementing single authenticate function?

create a middleware and add it to your /dashboard like this:
app.get('/dashboard', checkAuthentication , require('./dashboard/dashboard.js')
As explained here:https://stackoverflow.com/a/38820680/2988950

You can pass a middleware function before reaching the dashboard routes.
app.get('/dashboard',
(req, res, next) => {
// Run passport isAuthenticated() here.
// If true, next();
// If false, throw
},
require('./dashboard/dashboard.js');

Related

Including seperate route files in node.js

I am developing an application and I have defined my custom routes in a different way. I am using Web Storm IDE to develop and it has a specific folder of routes where all the routes are kept individually. I have the following code in my directory /routes/about.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('about', { title: 'About Us' });
});
module.exports = router;
Now in the app.js I have written the following code to include these route and use it:
var index = require('./routes/index');
var users = require('./routes/users');
var about = require('./routes/about');
app.use('/', index);
app.use('/users', users);
app.use('/about', about);
But when I click on about link, it does not open the page. Though, if I write the route in the app.js file directly as:
app.get('/about', function (req, res) {
res.render('about');
});
then it renders the page. Also, if I do not make separate routes and use the default routes file (/routes/index.js) and include this in that file, then also the code works fine. Can anyone explain or tell is there any mapping of these route files done which is missed by me, or I am doing something syntactically wrong
You probably created a route for /about/about. To fix, change the about router from this:
router.get('/about', ...);
to this:
router.get('/', ...);
This, then goes with:
app.use('/about', router);
which already includes the /about path. Everything in that router will already have /about at the beginning of the path.
Use below code in about file
app.get('/', function (req, res) {
res.render('about');
});
You have already defined '/about' route in main file so if you want to render page on '/about' so you need to define route like this '/' in about page.
For example route '/about/us' then function will be in about page :
app.get('/us', function (req, res) {
res.render('about us');
});
The method to redirect the route is correct, but you have not pass the route to app.
so you just need to do is ,
router.use('/about', about);
app.use('/', router);
Like wise add router in app

NodeJS & Express authentication middleware not functioning correctly

I am attempting to run the function isUserAuthenticated on every request to the server by requiring it in app.js and 'using' it as so: app.use(authenticate.isUserAuthenticated).
I have an /authenticate callback route that is being POSTED to by our SAML Identity Provider which contains the information required to validate the user and the session. This is what is inside my authenticate.js file:
module.exports = router;
module.exports.isUserAuthenticated = function(req, res, next) {
console.log(req.cookies.subject);
if (req.cookies.subject) {
console.log(req.cookies.subject)
return next();
} res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");
}
As referenced, this authentication function is being required and used in app.js: authenticate = require('./routes/authenticate'), and app.use(authenticate.isUserAuthenticated).
The problem: No matter what variation of the if statement to verify if the subject cookie is present in the request, the authentication check is not being fired and the redirect to the IDP authentication route is not being redirected too. The console.log checks in the code above are returning:
undefined, and
{}.
Authentication was working on a single route when I was using the isUserAuthenticated function manually like this: router.use('/', isUserAuthenticated, function(req, res, next) {..., but I am trying to use this function globally so I don't have to manually incorporate this middleware on each route.
Any advice/suggestions would be greatly appreciated. Thank you.
as suggested in comment,
you can move the isUserAuthenticated function to app.js. It'd look something like this
app.use(function(req, res, next) {
if (req.cookies.subject) {
next();
}
else
res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");
})
This will process all the requests before they are forwarded to the routes later.
A middleware needs to be set on router object if you are using express js
router.use(isUserAuthenticated)
Don't forget to put this on the top of your routes file.
See the difference between app level and router level middleware here

Correct format for Node architecture (BASIC)

Introduction
I have built some back end functionality in Node (First time using Node). Problem is that the whole thing was built in one page (index.js) so now im following a few basic tutorials and setting out express router middleware and now trying to follow a modular MVC approach,
This code is simple but brakes when I separate into two pages Server.js and config.js. I know its a simple problem but i cant spot it. can someone help spot the problem and maybe improve the structure ?
Problem
I go to http://localhost:8080/about or a different route and I get
Cannot GET /about
rather than the correct print out.
back-end/server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// get an instance of router
var router = express.Router();
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Server has started!! ' + port);
back-end/config.js
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
router.get('/', function(req, res) {
res.send('im the home page!');
});
// sample route with a route the way we're used to seeing it
router.get('/sample', function(req, res) {
res.send('this is a sample!');
});
router.get('/about', function(req, res) {
res.send('im the about page!');
});
app.route('/login')
.get(function(req, res) {
res.send('this is the login form');
})
.post(function(req, res) {
console.log('processing'); // shows on console when post is made
res.send('processing the login form!'); // output on postman
});
app.use('/', router);
As #SLaks said in his comment, you need to import (require) your backend/config.js file. But it's not as simple as that...
In node, variables are scoped to the file in which they appear, so if you simply add require('./config') to your server.js file, that's not going to work either, because the router variable in config.js is local to that file - it's not going to know about the router variable in server.js.
The solution to this is to have the config.js file export a function which the server.js file can use to configure stuff. For example
config.js
module.exports = function(router) {
// set up your router here with router.use, etc.
};
server.js
var configure = require('./config');
// after you set up your express router...
configure(router);
// now start listening

react router and express GET conflict

I'm not able to figure out how react router and express route working together.
I have this
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
});
// routes
const apiRoutes = require('./server/routes/api');
app.use('/api', apiRoutes);
The problem is my api can't use GET because it will redirect to index.html. If I remove the wildcard route, then react-router would not be able to work properly.
Your app.get('*') statement will match any request coming in. You can fix your problem by changing the order of the statements:
// routes
const apiRoutes = require('./server/routes/api');
app.use('/api', apiRoutes);
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
});
This way, any requests whose path's start with /api will be handled by your apiRoutes router, all the others are handled by the asterisk.

Express.js: Use variables in route's path

I'm developing a web application with MEAN stack and I want this scenario:
People can sign up and after that, They must have at least one company registered.
When they register a company, the base URL will be like these:
example.com/companyName/
example.com/companyName/members
example.com/companyName/settings
example.com/companyName/etc
So, my problem is, how can I use variables in my routes to match the user's registered company name?
Is it something like app.use('/'+companyName, routes); possible in app.js?
There is a piece of my code, just in case:
app.use(function (req, res, next) {
console.log('going to '+companyUrl);
next();
});
app.use('/'+companyUrl, routes);
I'm doing some works on other modules, and now, noStartupRestrict.theStartupUrl is companyName as it should be.
But the app is not using routes. it goes all the way down to 404 route.
Try this
app.use('/:companyName/something', function(req, res, next) {
console.log(req.params.companyName);
next();
})
Did you try?
app.js
...
var path = '/companyName';
app.use(path, routes);
...

Categories

Resources