doomiaichat
Version:
Doomisoft OpenAI
80 lines (79 loc) • 3.44 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorzAuthorization = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const api_1 = require("@coze/api");
class CorzAuthorization {
constructor(appid, setting) {
this.appid = appid;
this.expiresAt = 0;
this.secret = setting["keyid"];
this.pemfile = setting["pemfile"] || "private.pem";
this.sessionName = setting["sessionName"] || "default";
}
/**
* 获取授权令牌
* @returns
*/
getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
// 检查令牌是否存在且未过期,如果有效直接放回
if (this.accessToken && Date.now() < this.expiresAt)
return this.accessToken;
// 开始新的授权
const result = yield this.doAuthorize();
if (!result.successed)
return null;
// 缓存授权令牌和过期时间
this.accessToken = result.accessToken;
// 将 expires_in 转换为绝对时间戳
this.expiresAt = result.expires_in * 1000; // 将秒转换为毫秒
return this.accessToken;
});
}
/**
* 进行授权
* @returns
*/
doAuthorize() {
return __awaiter(this, void 0, void 0, function* () {
try {
// 提取您的 COZE API 授权参数
//const keyid = "H7rAk-5s0TPOs9-rXnCr7pvkPhpJZGArT__UuMyhbkg";
const aud = "api.coze.cn";
// 读取私钥
const fileFullPath = path_1.default.join(process.cwd(), this.pemfile);
if (!fs_1.default.existsSync(fileFullPath))
return { successed: false, error: `${fileFullPath} not existed` };
const privateKey = fs_1.default.readFileSync(fileFullPath).toString();
// 获取JWT令牌
const result = yield (0, api_1.getJWTToken)({
baseURL: api_1.COZE_CN_BASE_URL,
appId: this.appid,
aud,
keyid: this.secret,
privateKey,
sessionName: this.sessionName,
});
return { successed: true, accessToken: result.access_token, expires_in: result.expires_in };
}
catch (error) {
return { successed: true, error };
}
});
}
}
exports.CorzAuthorization = CorzAuthorization;