2017-04-21 58 views
0

我創建了一個簡單的身份驗證系統。用戶提交用戶名,路由會檢查用戶是否存在於數據庫中,如果有,則將已簽名的cookie分配給用戶以訪問所有其他路由。該系統適用於保護所有其他路線;然而,保護服務器索引文件的最終角度路徑似乎存在問題。ExpressJs不保護/跳過受保護的文件

app.use()服務角文件之前,如果沒有用戶cookie,我放置了一個重定向到登錄頁面的中間件。問題是,如果你沒有正確的用戶cookie去到localhost:3000,你將被髮送到角度應用程序,但是對api路線的保護已到位並將被阻止。如果你去localhost:3000/randomwords沒有cookie,你會被髮送到用戶登錄頁面。在我的應用程序流程中似乎有些東西缺失。

那麼我該如何正確保護角度路由,以便沒有cookie的用戶總是被髮送到auth頁面並且可以從那裏登錄。

此外,我甚至刪除了角度路線,保存並重新啓動應用程序,它仍然服務於角度應用程序。這怎麼可能?!

登錄後提交申請

module.exports.submitLoginForm = function(req,res, next){ 

    let foundUser = User.findOne({'userName': userName}); 

    foundUser 
     .then(user=>{ 

     if(tester){ 
      res.cookie('user', user._id, {signed: true}) 
      res.redirect('/'); 
     } 
      res.redirect('/auth/'); 
     }) 
     .catch(error=>{ 
      console.log(error) 
    }); 
} 

app.js

//how all other routes are protect in app.js (This works!) 

authMiddleWare = function(req,res,next){ 
    if (req.signedCookies['user']) { 
     next(); 

    } else { 
     sendJSONresponse(res, 400, {err:"error"}) 
    } 
} 

app.use('/api/info', authMiddleWare,infoApi); 


//middleware and angular route 

app.use(function(req, res, next) { 

    if (req.signedCookies['user']) { 
     next() 

    } else { 
     res.redirect('/auth/'); 
    } 

}); 

app.use(function (req, res, next) { 

     res.sendFile(path.join(__dirname, 'public/dist', 'index.html')); 
}); 

回答

0

因此,對於任何人都可能會遇到這個問題。上面更遠的app.js文件我使用的標準

app.use(express.static(path.join(__dirname, 'public')));

爲靜態文件。出於某種原因,這會導致Express無論如何都會爲Angular應用程序的index.html文件提供服務。我把它移到了auth中間件下面,現在它可以工作了!

app.use(function(req, res, next) { 

    if (req.session.user) { 
     next() 

    } else { 
     res.redirect('/auth/'); 
    } 

}); 

app.use(express.static(path.join(__dirname, 'server/public/dist'))); 

app.use(function(req, res) { 
    res.sendFile(path.join(__dirname, 'server/public/dist', 'index.html')); 
});