temp: 临时

This commit is contained in:
lik 2020-12-04 14:31:54 +08:00
parent 4e922091e6
commit 2e2d2b6c3e

View File

@ -3,11 +3,12 @@
const crypto = require('crypto');
const Redis = require('ioredis');
function AuthToken(redisdb) {
function AuthToken(redisdb, expiresSeconds) {
this.tokenDB = redisdb;
this.defaultExpiresSeconds = expiresSeconds;
}
AuthToken.prototype.genToken = async function (userData, userkey, expiresSeconds) {
AuthToken.prototype.genToken = async function ({ userData, userapp }) {
// 生成系统内部的user token
let hash = crypto.createHash('md5');
hash.update(JSON.stringify(userData) + Date() + Math.random());
@ -16,14 +17,29 @@ AuthToken.prototype.genToken = async function (userData, userkey, expiresSeconds
// 缓存到redis
let tokenData = {
userData: userData,
userkey: userkey,
expires: { ttl: expiresSeconds, ts: Math.floor(Date.now() / 1000) }
apps: {},
createts: Math.floor(Date.now() / 1000),
ttl: this.defaultExpiresSeconds
};
await this.tokenDB.set(userToken, JSON.stringify(tokenData), 'EX', expiresSeconds);
tokenData.apps[userapp.appid] = userapp;
await this.tokenDB.set(userToken, JSON.stringify(tokenData), 'EX', this.defaultExpiresSeconds);
return userToken;
};
AuthToken.prototype.update = async function (userToken, { userData, userapp }) {
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
return JSON.parse(data);
});
if (tokenData) {
if (userData) tokenData.userData = userData;
if (userapp) tokenData.apps[userapp.appid] = userapp;
await this.tokenDB.set(userToken, JSON.stringify(tokenData), 'EX', this.defaultExpiresSeconds);
}
};
AuthToken.prototype.delToken = async function (userToken) {
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
return JSON.parse(data);
@ -34,7 +50,7 @@ AuthToken.prototype.delToken = async function (userToken) {
}
};
AuthToken.prototype.checkToken = async function (userToken, userKey, checkKey = false, updateExpire = true) {
AuthToken.prototype.checkToken = async function (userToken, updateExpire = true) {
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
return JSON.parse(data);
});
@ -44,10 +60,6 @@ AuthToken.prototype.checkToken = async function (userToken, userKey, checkKey =
return null;
}
if (checkKey && userKey != tokenData.userkey) {
return null;
}
if (updateExpire) {
tokenData.expires.ts = Math.floor(Date.now() / 1000);
this.tokenDB.set(userToken, JSON.stringify(tokenData), 'EX', tokenData.expires.ttl);
@ -88,7 +100,7 @@ AuthToken.prototype.checkTokenKoaRequest = async function (ctx, next) {
};
return;
}
ctx.userData = tokenData.userData;
return next();