控制器中的条件路由不工作节点快速



我已经构建了一些条件逻辑来控制对子域的访问(producer.localhost:3000)

只有具有角色"管理员"的用户才能访问该网站,其他所有人(具有"用户"角色)都应重定向到他们的个人资料页面。

这是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')
};
};

问题是它会重定向到所有用户角色(而不仅仅是那些以"user"作为角色的角色)

对我来说似乎不是一个明确的问题,请尝试这样的事情


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')
})

这应该在 100% 的时间内有效,唯一合乎逻辑的结论是你的 if 语句没有返回正确的值。

在这种情况下,您可以尝试使用

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

代码不应该冲突,只是将它们放在彼此下面


//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');
}

不确定我是否理解您的问题

最新更新