"dependencies": {
"express": "^4.12.3",
"jsonwebtoken": "^5.0.0",
"mongoose": "^4.0.2",
"redis-fast-driver": "0.0.9",
}
function get_interface_token(req, res) {
Jiekou.findOne({username: req.query.username}, function (err, interface_find) {
if (err) throw err;
if (!interface_find) {
res.json({success: false, message: ‘认证失败,用户名找不到‘});
} else if (interface_find) {
// 检查密码
if (interface_find.password != req.query.password) {
res.json({success: false, message: ‘认证失败,密码错误‘});
} else {
//为接口加入token创建时间,使得每次获取的token都不一样
var time = new Date();
interface_find.token_create_time = time;
// 创建token
var token = jwt.sign(interface_find, config.secret, {
expiresInMinutes: 1440 // 设置过期时间
});
r.rawCall([‘hmset‘, req.query.username, ‘token‘, token], function (err, d) {
if (err) throw err;
});
r.rawCall([‘EXPIRE‘, req.query.username, config.token_expire_time], function (err, d) {
if (err) throw err;
});
// json格式返回token
res.json({
success: true,
message: ‘Enjoy your token!‘,
token: token
});
}
}
})
}
function checktoken(req, res, next) {
//检查post的信息或者url查询参数或者头信息
var token = req.body.token || req.query.token || req.headers[‘x-access-token‘];
// 解析 token
if (token) {
// 确认token
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
return res.json({success: false, message: ‘token信息错误.‘});
} else {
console.log(decoded.username);
r.rawCall([‘HEXISTS‘, decoded.username, ‘token‘], function (err, d) {
if (err) throw err;
console.log(d)
if (d === 1) {
// 如果没问题就把解码后的信息保存到请求中,供后面的路由使用
req.decoded = decoded;
next();
} else {
return res.status(403).send({
success: false,
message: ‘token已经过期!‘
});
next()
}
})
}
});
} else {
// 如果没有token,则返回错误
return res.status(403).send({
success: false,
message: ‘没有提供token!‘
});
}
}
原文地址:http://blog.csdn.net/smallfish1983/article/details/46373107