Home > Net >  Conditional routing in controller not working Node Express
Conditional routing in controller not working Node Express

Time:03-25

I've built some conditional logic to control access to a subdomain (producer.localhost:3000)

Only users with role 'admin' should be able to access the site, everyone else (with role of 'user') should be redirected to their profile page.

This is the code inside producerController.js :

index = (req, res, next) => {
if ((req.oidc.user['https://localhost:3000.com/roles']).includes("user")){
  res.redirect('http://localhost:3000/user/profile')
} 
else {
  res.render('producer/index')
  };
};

The problem is that it redirects for ALL user roles (rather than just those with ‘user’ as a role)

CodePudding user response:

Doesn't seem like an express issue to me, try something like this


const express = require('express');
const app = require('express');

//Only allows users to continue to route if admin is one of their roles
const adminRoute = (req, res, next) =>{
    if(req.oidc.user['https://localhost:3000.com/roles'].includes('admin'))
        next();
    else
        res.redirect('http://localhost:300/user/profile');
}


//Example use case
//Everything affected by this app.use() (in this case anything underneath it) will only be accessible to users with the admin role
app.use('*', adminRoute)

app.get('/protectedRoute', (req, res) =>{
    res.send('Protected route')
})

//Or you can use it directly inside the route
app.get('/protectedRoute', adminRoute, (req, res) =>{
    res.send('Protected route')
})


app.listen('80', () =>{
    console.log('Listening on port 80')
})

This should work 100% of the time, the only logical conclusion is that your if statement isn't returning the proper value.

In which case you can try using

if(array.indexOf('admin') !== -1)

CodePudding user response:

The code shouldn't conflict just put them underneath eachother


//Executes this first
app.use((req, res, next) =>{
   doThing();
   next();
})

//Then executes the next route/use
app.use((req, res, next) =>{
   doOtherThing();
   if(something == false) return res.redirect('https://test.com');
   next();
})

//Lastly if next was called in every use statement before this access route
app.get('/someRoute', (req, res) =>{
   res.send('Accessed some route');
}

Not sure if I understand your issue

  • Related