2017-11-13 12:26:31 +08:00
|
|
|
|
//基础的路由定义
|
|
|
|
|
const router = require('express')();
|
|
|
|
|
const response = require('../helper/Response');
|
|
|
|
|
const permssion = require('../helper/Permission');
|
2018-04-21 14:15:20 +08:00
|
|
|
|
const TokenManager = require('../helper/TokenManager');
|
2017-11-13 12:26:31 +08:00
|
|
|
|
const counter = require('../core/counter');
|
2018-04-03 08:36:45 +08:00
|
|
|
|
const UUID = require('uuid');
|
2018-04-20 12:55:59 +08:00
|
|
|
|
const loginedContainer = require('../helper/LoginedContainer');
|
2018-04-20 12:35:21 +08:00
|
|
|
|
|
|
|
|
|
function getRandToken() {
|
|
|
|
|
return permssion.randomString(6) + UUID.v4().replace(/-/igm, "");
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-13 12:26:31 +08:00
|
|
|
|
//Token
|
|
|
|
|
router.get('/', function (req, res) {
|
2018-04-03 15:41:49 +08:00
|
|
|
|
let username = req.session['username'] || undefined;
|
2017-11-13 12:26:31 +08:00
|
|
|
|
//ajax 会受到浏览器跨域限制,姑不能对其进行csrf攻击获取token,尽管它可伪造。
|
2018-04-21 14:46:12 +08:00
|
|
|
|
if (req.xhr) {
|
2018-04-21 14:43:42 +08:00
|
|
|
|
|
2018-04-21 10:26:51 +08:00
|
|
|
|
if (!username || !loginedContainer.isLogined(req.sessionID)) {
|
2018-04-21 14:43:42 +08:00
|
|
|
|
MCSERVER.log('[ Token ]', '未登录用户 ', username, ' 请求更新令牌 | 已经阻止');
|
2018-04-03 08:36:45 +08:00
|
|
|
|
//用户未登录,返回一个随机的 token 给它,并且这个 token 与正常的 token 几乎一模一样
|
|
|
|
|
response.returnMsg(res, 'token', {
|
2018-04-20 12:35:21 +08:00
|
|
|
|
token: getRandToken(),
|
2018-04-03 08:36:45 +08:00
|
|
|
|
username: username,
|
|
|
|
|
});
|
|
|
|
|
return;
|
|
|
|
|
}
|
2018-04-20 10:04:22 +08:00
|
|
|
|
|
2018-04-21 14:15:20 +08:00
|
|
|
|
//删除原先可能存在的
|
2018-04-21 14:43:42 +08:00
|
|
|
|
TokenManager.delToken(req.session['token'] || null);
|
2018-04-21 14:15:20 +08:00
|
|
|
|
|
|
|
|
|
//永远生产一个新的
|
|
|
|
|
let newtoken = getRandToken();
|
|
|
|
|
TokenManager.addToken(newtoken, username);
|
|
|
|
|
req.session['token'] = newtoken;
|
2018-04-03 15:41:49 +08:00
|
|
|
|
req.session.save();
|
2018-04-21 14:15:20 +08:00
|
|
|
|
|
2018-04-21 14:43:42 +08:00
|
|
|
|
MCSERVER.log('[ Token ]', '用户 ', username, ' 请求更新令牌 | 准许');
|
|
|
|
|
|
2017-11-13 12:26:31 +08:00
|
|
|
|
response.returnMsg(res, 'token', {
|
|
|
|
|
token: req.session['token'],
|
2018-04-02 23:53:48 +08:00
|
|
|
|
username: username,
|
2017-11-13 12:26:31 +08:00
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
counter.plus('csrfCounter');
|
|
|
|
|
res.send('<h1>CSRF 防御策略</h1><hr><p>您不能直接访问本页面,这是为了防御 CSRF 攻击,务必直接访问首页!</p>' +
|
|
|
|
|
'<p>具体信息我们将统计到非法 API 请求,这可能需要值得您注意.</p>');
|
|
|
|
|
}
|
2018-04-03 15:41:49 +08:00
|
|
|
|
res.end();
|
2017-11-13 12:26:31 +08:00
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//模块导出
|
|
|
|
|
module.exports = router;
|
|
|
|
|
|
2018-04-02 23:53:48 +08:00
|
|
|
|
// res.header('X-Powered-By','Mcserver Manager HTT_P_SERVER');
|
|
|
|
|
//res.cookie('token_to',permssion.randomString(32));
|