feat: auth openapi key

This commit is contained in:
archer
2023-04-07 23:33:59 +08:00
parent f6c4b4c96d
commit ea1681e1eb
6 changed files with 37 additions and 8 deletions

View File

@@ -1,8 +1,10 @@
import type { NextApiRequest } from 'next';
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
import tunnel from 'tunnel';
import { ChatItemType } from '@/types/chat';
import { encode } from 'gpt-token-utils';
import { OpenApi } from '../mongo';
/* 密码加密 */
export const hashPassword = (psw: string) => {
@@ -41,6 +43,30 @@ export const authToken = (token?: string): Promise<string> => {
});
};
/* 校验 open api key */
export const authOpenApiKey = (req: NextApiRequest) => {
return new Promise<string>(async (resolve, reject) => {
const { apikey: apiKey } = req.headers;
if (!apiKey) {
reject('api key is empty');
return;
}
try {
const openApi = await OpenApi.findOne({ apiKey });
if (!openApi) {
return reject('api key is error');
}
await OpenApi.findByIdAndUpdate(openApi._id, {
lastUsedTime: new Date()
});
resolve(String(openApi.userId));
} catch (error) {
reject(error);
}
});
};
/* 代理 */
export const httpsAgent =
process.env.AXIOS_PROXY_HOST && process.env.AXIOS_PROXY_PORT