var filter = require('./lib/filter');
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){
// 校验
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");
}
});
};
10 回复
@Hi-Rube 不一定,session存数据库的还多一些 cnode社区的session中间件
var session = require('express-session');
app.use(session({
secret: config.session_secret,
key: 'sid',
store: new MongoStore({
db: config.db_name
}),
resave: true,
saveUninitialized: true,
}));
store用的是MongoDB