This commit is contained in:
张成
2026-04-01 13:42:29 +08:00
parent 1d22fb28e2
commit 2d900ef2ac
9 changed files with 187 additions and 8 deletions

View File

@@ -2,6 +2,7 @@ const crypto = require("crypto");
const Sequelize = require("sequelize");
const op = Sequelize.Op;
const baseModel = require("../../middleware/baseModel");
const biz_token_secret_cipher = require("../utils/biz_token_secret_cipher");
const MAX_TOKENS_PER_USER = 5;
@@ -53,12 +54,14 @@ async function createToken(body) {
const plain = generatePlainToken();
const token_hash = hashPlainToken(plain);
const secret_cipher = biz_token_secret_cipher.encrypt_plain_for_storage(plain);
const row = await baseModel.biz_api_token.create({
user_id,
plan_id,
token_name: token_name || "default",
token_hash,
secret_cipher,
status: "active",
expire_at,
});
@@ -75,7 +78,7 @@ async function revokeToken(body) {
if (id == null) throw new Error("缺少 id");
const row = await baseModel.biz_api_token.findByPk(id);
if (!row) throw new Error("Token 不存在");
await row.update({ status: "revoked" });
await row.update({ status: "revoked", secret_cipher: null });
return row;
}
@@ -98,10 +101,12 @@ async function regenerateToken(body) {
const plain = generatePlainToken();
const token_hash = hashPlainToken(plain);
const secret_cipher = biz_token_secret_cipher.encrypt_plain_for_storage(plain);
await row.update({
token_hash,
plan_id,
secret_cipher,
});
await row.reload();
@@ -115,7 +120,7 @@ async function regenerateToken(body) {
async function revokeAllForUser(userId) {
if (userId == null) throw new Error("缺少 user_id");
const [n] = await baseModel.biz_api_token.update(
{ status: "revoked" },
{ status: "revoked", secret_cipher: null },
{ where: { user_id: userId, status: "active" } }
);
return n;