var filter = require('./lib/filter');
判断是否已经登录如果登录了则过去,否则跳转到登录页
exports.authorize = function(req, res, next) {
if (!req.session.user_id) {
res.redirect('/admin/login');
} else {
next();
}
}
在配置中加上使用session
app.use(express.cookieParser('sctalk admin manager'));
app.use(express.session());
路由控制,在需要登录验证的路由上加上filter.authorize
app.get('/admin/login',admin.login);
app.get('/admin/logout',admin.logout);
app.get('/admin/:action',filter.authorize, function(req, res, next){
if(admin[req.params.action])
{
admin[req.params.action](req, res, next);
}
else
{
res.status(404);
res.end();
}
});
最后在登录判断时候添加session即可
exports.dologin = function(req, res,next){
// 校验
req.assert('username', "用户名不能为空").notEmpty();
req.assert('password', "密码不能为空").notEmpty();
var errors = req.validationErrors();
if(errors && errors.length>0)
{
var ermsg = [];
for(var i=0;i<errors.length;i++)
{
ermsg.push(errors[i].msg);
}
var json={title:'管理后台-- 请先登录',error:ermsg.join("\n")};
res.render('admin/login', json);
return;
}
var userid = req.body.username;
var pwd = req.body.password;
var ip = req.ip;
userbiz.checkUser(userid,pwd,ip,function(err,user){
if(!!err){
var json={title:'管理后台-- 请先登录',error:err};
res.render('admin/login', json);
}
else{
req.session.user_id = user.user_id;
req.session.user = user;
res.redirect("/admin/index");
}
});
};