修改生成系统token逻辑

This commit is contained in:
whyour 2022-08-11 19:37:14 +08:00
parent a7117e4442
commit db8dfb32cf
2 changed files with 17 additions and 48 deletions

View File

@ -145,7 +145,7 @@ export default class OpenService {
} }
} }
public async findSystemToken(): Promise<{ public async generateSystemToken(): Promise<{
value: string; value: string;
expiration: number; expiration: number;
}> { }> {
@ -158,22 +158,13 @@ export default class OpenService {
scopes: ['crons', 'system'], scopes: ['crons', 'system'],
} as App); } as App);
} }
const nowTime = Math.round(Date.now() / 1000); const { data } = await this.authToken({
let token; client_id: systemApp.client_id,
if ( client_secret: systemApp.client_secret,
!systemApp.tokens || });
!systemApp.tokens.length || return {
nowTime > [...systemApp.tokens].pop()!.expiration ...data,
) { value: data.token,
const authToken = await this.authToken({ };
client_id: systemApp.client_id,
client_secret: systemApp.client_secret,
});
token = authToken.data;
token.value = token.token;
} else {
token = [...systemApp.tokens].pop();
}
return token;
} }
} }

View File

@ -10,41 +10,19 @@ const tokenFile = path.join(config.configPath, 'token.json');
async function getToken() { async function getToken() {
try { try {
const data = await readFile(); Container.set('logger', LoggerInstance);
const nowTime = Math.round(Date.now() / 1000); const openService = Container.get(OpenService);
if (data.value && data.expiration > nowTime) { const appToken = await openService.generateSystemToken();
console.log(data.value); console.log(appToken.value);
} else { await writeFile({
Container.set('logger', LoggerInstance); value: appToken.value,
const openService = Container.get(OpenService); expiration: appToken.expiration,
const appToken = await openService.findSystemToken(); });
console.log(appToken.value);
await writeFile({
value: appToken.value,
expiration: appToken.expiration,
});
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }
} }
async function readFile() {
return new Promise<any>((resolve, reject) => {
fs.readFile(
path.join(config.configPath, 'token.json'),
{ encoding: 'utf8' },
(err, data) => {
if (err) {
resolve({});
} else {
resolve(JSON.parse(data));
}
},
);
});
}
async function writeFile(data: any) { async function writeFile(data: any) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
fs.writeFile(tokenFile, JSON.stringify(data), { encoding: 'utf8' }, () => { fs.writeFile(tokenFile, JSON.stringify(data), { encoding: 'utf8' }, () => {