一. 使用cookie-parser、express-session来处理cookie和session。
const cookieParser = require('cookie-parser');
const session = require('express-session');
app.use(cookieParser('swq'));
app.use(session({
secret: 'swq',
resave: false,
saveUninitialized: true
}))
二. 登陆成功后,将用户ID生成cookie。
home.login = (req, res, next) => {
let data = req.body;
if(data.username == '') {
return res.send({resultCode: 400, resultMsg: '用户名为空'});
} else if(data.password == '') {
return res.send({resultCode: 400, resultMsg: '密码为空'});
} else {
User.findOne({name: data.name}).then(user => {
if(!user) {
return res.send({resultCode: 400, resultMsg: '用户不存在'});
}
if(data.password != user.password) {
return res.send({resultCode: 400, resultMsg: '密码错误'});
}
//生成cookie
auth.gen_session(user, res);
return res.send({resultCode: 200, resultMsg: '登录成功'});
})
}
}
// 生成cookie
gen_session: (user, res) => {
let auth_user = `${user._id}`;
res.cookie('suweiqing', auth_user, {
path: '/',
signed: true,//对cookie密码进行加密的话, 需要使用到cookieParser
httpOnly: true,
maxAge: 30 * 24 * 60 * 60 * 1000
});
},
三. 编写中间件,判断用户是否登录(判断session中是否有用户信息)。
app.use(auth.authUser);
authUser: (req, res, next) => {
if(req.session.user) {
next();
}
else {
let auth_token = req.signedCookies['suweiqing'];
if (!auth_token) {
next();
}
else {
let user_id = auth_token;
User.findOne({_id: user_id}, (err, user) => {
if (err) {
return res.end(err);
}
else {
if (!user) {
next();
}
else {
req.session.user = user;
next();
}
}
})
}
}
}
Created with Raphaël 2.1.2 判断是否有req.session.user next() 获取cookie 判断是否有cookie 根据cookie,从数据库得到user 判断是否有user 保存user到session yes no yes no yes no
四. 设置已登录用户和未登录用户的权限。
(1)已登录用户不能访问未登录界面
//判断用户未登录的中间件
userRequired: (req, res, next) => {
if(!req.session || !req.session.user || !req.session.user._id) {
return res.redirect('/login');
}
next();
}
(2)未登录用户不能访问已登录界面
//判断用户已登录的中间件
userNotRequired: (req, res, next) => {
if(req.session.user != undefined) {
return res.redirect('back');
}
next();
}
(3) 使用权限中间件
router.get('/', auth.userRequired,home.index);
router.get('/login', auth.userNotRequired, home.loginPage)