v4.0.17企业微信API插件优化
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import {
|
||||
WECOM_PLUGIN_PERMISSIONS,
|
||||
parseWecomPluginPermissions,
|
||||
type WecomPluginPermission,
|
||||
} from '@dukang/shared-types';
|
||||
import { isWecomPluginEnabled, matchWecomPluginByApiKey } from '@dukang/domain';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import type { WecomPluginRuntime } from './wecom-plugin.types';
|
||||
|
||||
@Injectable()
|
||||
export class WecomPluginAuthService implements OnModuleInit {
|
||||
private readonly logger = new Logger(WecomPluginAuthService.name);
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.migrateFromEnv().catch((e) => {
|
||||
this.logger.warn(
|
||||
`wecom plugin env migrate skipped: ${e instanceof Error ? e.message : String(e)}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async resolveByApiKey(provided: string): Promise<WecomPluginRuntime | null> {
|
||||
const key = String(provided ?? '').trim();
|
||||
if (!key) return null;
|
||||
const rows = await this.prisma.wecomApiPlugin.findMany({
|
||||
where: { enabled: true },
|
||||
select: { id: true, name: true, apiKey: true, permissions: true },
|
||||
});
|
||||
const hit = matchWecomPluginByApiKey(key, rows);
|
||||
if (!hit) return null;
|
||||
return {
|
||||
id: hit.id.toString(),
|
||||
name: hit.name,
|
||||
permissions: parseWecomPluginPermissions(hit.permissions),
|
||||
};
|
||||
}
|
||||
|
||||
private async migrateFromEnv() {
|
||||
if (!isWecomPluginEnabled(process.env)) return;
|
||||
const count = await this.prisma.wecomApiPlugin.count();
|
||||
if (count > 0) return;
|
||||
const apiKey = String(process.env.WECOM_PLUGIN_API_KEY ?? '').trim();
|
||||
if (!apiKey) return;
|
||||
await this.prisma.wecomApiPlugin.create({
|
||||
data: {
|
||||
name: '迁移自 env',
|
||||
apiKey,
|
||||
permissions: JSON.stringify([...WECOM_PLUGIN_PERMISSIONS] as WecomPluginPermission[]),
|
||||
remark: '由 WECOM_PLUGIN_API_KEY 一次性导入',
|
||||
enabled: true,
|
||||
sortOrder: 0,
|
||||
},
|
||||
});
|
||||
this.logger.log('wecom api plugin migrated from env');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user