npm-package/auth/index.js

111 lines
2.6 KiB
JavaScript

'use strict';
const crypto = require('crypto');
const Redis = require('ioredis');
function AuthToken(redisdb) {
this.tokenDB = redisdb;
}
AuthToken.prototype.genToken = async function (userData, userkey, expiresSeconds) {
// 生成系统内部的user token
let hash = crypto.createHash('md5');
hash.update(JSON.stringify(userData) + Date() + Math.random());
let userToken = hash.digest('hex');
// 缓存到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);
return userToken;
};
AuthToken.prototype.delToken = async function (userToken) {
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
return JSON.parse(data);
});
if (tokenData) {
this.tokenDB.del(userToken);
}
};
AuthToken.prototype.checkToken = async function (userToken, userKey, checkKey = false, updateExpire = true) {
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
return JSON.parse(data);
});
// token不存在
if (!tokenData) {
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);
}
return tokenData;
};
AuthToken.prototype.getTokenData = async function (userToken) {
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
return JSON.parse(data);
});
// token不存在
if (!tokenData) {
return null;
}
return tokenData;
};
AuthToken.prototype.checkTokenKoaRequest = async function (ctx, userkey, checkKey, next) {
let token = ctx.request.body.token
if (!token) token = ctx.header['authorization']
if (!token) token = token = ctx.header['token']
if (!token) {
ctx.body = {
result: 'fail', error: { code: 401, msg: 'Need user token.' }, data: {}
};
return;
}
let tokenData = await this.checkToken(token, userkey, checkKey);
if (!ret) {
ctx.body = {
result: 'fail', error: { code: 401, msg: 'User token error.' }, data: {}
};
return;
}
ctx.userData = tokenData.userData;
return next();
};
/*
AuthToken.prototype.checkTokenKoaRequestByAgent = async function (ctx, next) {
return this.checkTokenKoaRequest(ctx, ctx.userAgent.source, true, next);
};
*/
let tokenInstance = null;
module.exports = function getTokenInstance(redisdb) {
if (!tokenInstance) {
tokenInstance = new AuthToken(redisdb);
}
return tokenInstance;
};