Home > database >  How to use only PART of the functionality in nested routes NodeJS
How to use only PART of the functionality in nested routes NodeJS

Time:10-01

So I have a router schoolsRouter where all the school-specific functionality is being handled { login school, adding a new teacher, ...etc.). And I want the admin of the app to be able to add and delete new schools. Now the pattern I'm using encapsulates all the routing functionality in one file schools.routes.js where the School model is exposed. So the createSchool and deleteSchool routes are in the schools.routes.js but I need only the admin to be able to perform those operations and that seems pretty easy with merged routes like this (in admins.routes.js):

adminsRouter.use('/schools/', schoolsRouter);

but the problem is that now the admin can access all the other routes in schools.routes.js like schools/login which is something that I don't want to happen. So how can I make the adminsRouter use the create and delete operations from the schoolsRotuer without being able to access all these other functionalities? (Keeping in mind I'm using JWT authentication).

CodePudding user response:

You could use middlewares in the routes that you wish to controll.

This is the middleware that I will name of admin-middleware.js

module.exports = (req, res, next) => {    
    if (user.admin === true) {
        return next();
    } else {
        return res.status(403).send('Unauthorized')
    }
}

So, this is your route declaration at schools.routes.js

const adminMiddleware = require('../YOUR_FOLDERS/admin-middleware.js');

schools.delete('/:id', adminMiddleware, (req, res) => {
    return res.send('ok');
});

If you wish disregard a route, you can use this validation at your code in the middleware.

if(req.originalUrl.includes('/schools/login'))
    return next();

I hope that it works to you.

  • Related