filter中判断是否已经登录如果登录了则过去,否则跳转到登录页
exports.authorize = function(req, res, next) {
if (!req.session.user_id) {
res.redirect('/admin/login');
} else {
next();
}
}
在configure中使用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){
// 校验 这里获取的的是get或者post请求过来的参数去做判断
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");
}
});
};
以下是在dsp项目中看到同事的写法,值得借鉴
//请求接口时,定义请求规则,去调用定义好的过滤参数方法 var reqRule = []; reqRule.push({'filed': 'type', 'rule': {'notEmpty': '订单类型未传', 'isIn': '订单类型不合法'}, 'option': [1, 2]}); reqRule.push({'filed': 'id', 'rule': {'notEmpty': '订单id未传', 'isInt': '订单id不合法'}}); //dsp中封装过滤参数方法 exports.checkReqRuld = function(req, reqRule){ var rsMsg = {'code': 0, 'msg':'ok', 'message':'成功', 'childMessages':[], 'data':[]}; if(reqRule != undefined && reqRule.length>0){ var i = 0, j = 0, filed = null, rule = null, option = null; for (i in reqRule){ filed = reqRule[i].filed; rule = reqRule[i].rule; if(reqRule[i].option != undefined){ option = reqRule[i].option; } for (j in rule){ switch(j){ case 'notEmpty': req.assert(filed, rule[j]).notEmpty(); break; case 'isInt': req.assert(filed, rule[j]).isInt(option); break; case 'is_date': req.assert(filed, rule[j]).isDate(); break; case 'isIn': req.assert(filed, rule[j]).isIn(option); break; case 'isFloat': req.assert(filed, rule[j]).isFloat(option); break; case 'isJSON': req.assert(filed, rule[j]).isJSON(); break; } } } var errors = req.validationErrors(); if(errors && errors.length>0){ rsMsg.code = -100; rsMsg.msg = 'error'; rsMsg.message = '失败'; for (var i = 0; i < errors.length; i++) { rsMsg.childMessages.push(errors[i].msg); break; } } } return rsMsg; }
转载自:http://cnodejs.org/topic/516517a56d38277306c614da