auth.js
2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* 认证中间件
* @author h1bomb
*/
var _= require('lodash');
var ipaddr = require('ipaddr.js');
var options=require('../staticConfig.js').staticDir;
/**
* 不需要权限校验配置
*/
var guestAccessList = {
"POST:/login":true,
"GET:/logout":true
}
var NO_AUTH = '没有权限!';
var WEBSITE = 1;
/**
* 认证中间件
* @param {Object} req 请求对象
* @param {Object} res 响应对象
* @param {Function} next 执行下个中间件
* @return {void} 无返回
*/
module.exports = function(req, res, next) {
//方法名称
var method = req.method;
//访问路由路径
var path = req.route?req.route.path:'';
if(req.session.user&&!checkPath(req.path,req)) {
res.status(403);
res.render('error/error_nolayout',{message:NO_AUTH,layout:false});
return;
}
//进行白名单验证和session验证
if(guestAccessList[method+":"+path]||req.session.user) {
//判断是否已存在appendData
if(!res.appendData) {
res.appendData = req.session.user;
} else {
res.appendData = _.merge(res.appendData,req.session.user);
}
//添加管理员信息到http头
if(req.session.user) {
appendAdminInfo(req,req.session.user.auth);
}
next();
} else {
req.app.logger.log('info',"CurentView:Login");
//如果是登陆界面不加载布局
res.render('pages/login',{layout:false});
}
}
/**
* 检查路径是否没有权限
* @param {String} path
* @param {Object} req
* @return {Boolean}
*/
function checkPath(path,req) {
var right = req.session.user.noRight;
var ret = true;
_.forEach(right,function(v,k){
if(path.indexOf(k)>-1) {
ret = false;
return;
}
});
return ret;
}
/**
* 附加管理员的信息
* @param {Request} req 请求对象
* @param {Number} uid 用户ID
* @param {String} name 用户名
* @return {Object} 用户信息对象
*/
function appendAdminInfo(req,auth) {
var ipObject = ipaddr.process(req.ip).octets
var ip = ipObject?ipObject.join('.'):req.ip;
req._yoheaders = {
'x-user-id':auth.pid,
'x-user-name':auth.account,
'x-site-type':WEBSITE,
'x-client-ip':ip
};
}