我已經構建了一些條件邏輯來控制對子域的訪問(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')
};
};
問題是它重定向所有用戶角色(而不僅僅是那些以“用戶”為角色的角色)
uj5u.com熱心網友回復:
對我來說似乎不是一個明確的問題,試試這樣的
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)
uj5u.com熱心網友回復:
代碼不應該沖突,只需將它們放在彼此下方
//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');
}
不確定我是否理解您的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449378.html
上一篇:帶快遞的動態端點
