![](/img/trans.png)
[英]How to prevent certain users from accessing a route and any subroutes in React?
[英]How check a users name when accessing a route
大家好,我花了最后3個小時來嘗試完成這項工作,因此,我們將不勝感激。 因此,我制作了一個具有管理頁面的快速Webapp。 我已經使用護照完成了注冊和登錄,我可以檢查用戶是否使用該功能登錄
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');}
我在單擊管理路線的鏈接時想檢查用戶名是否等於示例,是否允許其進入頁面。 到目前為止,我的代碼是
var isAdmin = function (req, res, next) {
if (req.session.username === 'example') {
return next();
}else{
// if the user is not authenticated then redirect him to the login page
res.redirect('/');
}
我的路線是
router.get('/admin', isAdmin, function(req, res){
res.render('admin', { title : 'admin' });
});
我的索引路由文件中有這兩個代碼片段。 我遇到的問題是,當我嘗試使用名為example的用戶登錄時,它使我返回登錄頁面。 任何想法如何解決?
只要安裝了會話包,就可以執行此操作。 您還需要安裝主體解析器軟件包。
router.get('/admin', function(req, res){
if (req.session.passport.user === undefined || req.session.passport.user !== 'example') {
res.redirect('/login');
} else{
res.render('admin', {title: 'admin'});
}
});
我讓它工作了:)
app.get('/admin', function(req, res){
if (req.user.username === undefined || req.user.username !== 'example') {
res.redirect('/');
} else{
res.render('admin', {title: 'admin'});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.