use useragent as user key for check token

This commit is contained in:
lik 2020-02-25 15:41:50 +08:00
parent 679c784ead
commit eee4614161
2 changed files with 17 additions and 5 deletions

View File

@ -7,7 +7,7 @@ function AuthToken(redisdb) {
this.tokenDB = redisdb;
}
AuthToken.prototype.genToken = async function(userData, expiresSeconds) {
AuthToken.prototype.genToken = async function(userData, userkey, expiresSeconds) {
// 生成系统内部的user token
let hash = crypto.createHash('md5');
hash.update(JSON.stringify(userData) + Date() + Math.random());
@ -16,6 +16,7 @@ AuthToken.prototype.genToken = async function(userData, expiresSeconds) {
// 缓存到redis
let tokenData = {
userData: userData,
userkey: userkey,
expires: {ttl: expiresSeconds, ts: Math.floor(Date.now() / 1000)}
};
await this.tokenDB.set(userToken, JSON.stringify(tokenData), 'EX', expiresSeconds);
@ -33,7 +34,7 @@ AuthToken.prototype.delToken = async function (userToken) {
}
};
AuthToken.prototype.checkToken = async function (userToken) {
AuthToken.prototype.checkToken = async function (userToken, userkey) {
let tokenData = await this.tokenDB.get(userToken).then(function(data) {
return JSON.parse(data);
});
@ -43,6 +44,10 @@ AuthToken.prototype.checkToken = async function (userToken) {
return false;
}
if (userkey != tokenData.userkey) {
return false;
}
//
tokenData.expires.ts = Math.floor(Date.now() / 1000);
this.tokenDB.set(userToken, JSON.stringify(tokenData), 'EX', tokenData.expires.ttl);
@ -50,7 +55,7 @@ AuthToken.prototype.checkToken = async function (userToken) {
return true;
};
AuthToken.prototype.checkTokenKoaRequest = async function (ctx, next) {
AuthToken.prototype.checkTokenKoaRequest = async function (ctx, userkey, next) {
if (!ctx.request.body.token) {
ctx.body = {
result: 'fail', error: { code: 401, msg: 'Need user token.' }, data: {}
@ -68,6 +73,13 @@ AuthToken.prototype.checkTokenKoaRequest = async function (ctx, next) {
return;
}
if (userkey != tokenData.userkey) {
ctx.body = {
result: 'fail', error: { code: 403, msg: 'User token has risk.' }, data: {}
};
return;
}
ctx.userData = tokenData.userData;
//
@ -79,7 +91,7 @@ AuthToken.prototype.checkTokenKoaRequest = async function (ctx, next) {
AuthToken.prototype.checkTokenKoaRequestPost = async function (ctx, next) {
if (ctx.req.method === 'POST') {
return this.checkTokenKoaRequest(ctx, next);
return this.checkTokenKoaRequest(ctx, ctx.userAgent.source, next);
}
next();

View File

@ -1,6 +1,6 @@
{
"name": "@ehason/auth",
"version": "1.2.4",
"version": "1.2.9",
"description": "User auth lib",
"main": "index.js",
"scripts": {