我创建了一个简单的身份验证系统。用户提交用户名,路由会检查用户是否存在于数据库中,如果有,则将已签名的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'));
});