feat: 完善登录鉴权和超级管理员重置
This commit is contained in:
@@ -57,6 +57,7 @@ describe('AgentService', () => {
|
||||
getRun: jest.fn((id: string) =>
|
||||
Promise.resolve({
|
||||
id,
|
||||
version: 1,
|
||||
projectKey: 'role-user',
|
||||
environment: 'production' as const,
|
||||
ref: 'master',
|
||||
|
||||
@@ -4,7 +4,7 @@ export const SUPER_ADMIN_SEED = {
|
||||
displayName: '超级管理员',
|
||||
} as const;
|
||||
|
||||
export const LOCAL_SUPER_ADMIN_INITIAL_PASSWORD = 'devops-local-admin';
|
||||
export const SUPER_ADMIN_INITIAL_PASSWORD = 'zx123456@';
|
||||
|
||||
export const MEMBER_INITIAL_PASSWORD = '111111';
|
||||
|
||||
|
||||
@@ -4,19 +4,22 @@ import { AppError } from '../common/errors/app-error';
|
||||
import { EnvConfig } from '../config/env.schema';
|
||||
import { AuthTokenService } from './auth-token.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { MEMBER_INITIAL_PASSWORD } from './auth.constants';
|
||||
import {
|
||||
MEMBER_INITIAL_PASSWORD,
|
||||
SUPER_ADMIN_INITIAL_PASSWORD,
|
||||
} from './auth.constants';
|
||||
import { PasswordService } from './password.service';
|
||||
import { UserRepository } from './user.repository';
|
||||
import { UserRecord } from './auth.types';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
const TEST_ADMIN_PASSWORD = 'test-admin-password';
|
||||
|
||||
describe('AuthService', () => {
|
||||
const passwordService = new PasswordService();
|
||||
|
||||
async function createService() {
|
||||
const adminHash = await passwordService.hashPassword(TEST_ADMIN_PASSWORD);
|
||||
async function createService(options?: { superAdminPassword?: string }) {
|
||||
const adminPassword =
|
||||
options?.superAdminPassword ?? SUPER_ADMIN_INITIAL_PASSWORD;
|
||||
const adminHash = await passwordService.hashPassword(adminPassword);
|
||||
const memberHash = await passwordService.hashPassword(MEMBER_INITIAL_PASSWORD);
|
||||
const users = new Map<string, UserRecord>();
|
||||
const admin: UserRecord = {
|
||||
@@ -106,7 +109,7 @@ describe('AuthService', () => {
|
||||
const config = {
|
||||
get: jest.fn((key: keyof EnvConfig) => {
|
||||
if (key === 'SUPER_ADMIN_INITIAL_PASSWORD') {
|
||||
return TEST_ADMIN_PASSWORD;
|
||||
return options?.superAdminPassword;
|
||||
}
|
||||
|
||||
if (key === 'NODE_ENV') {
|
||||
@@ -139,7 +142,7 @@ describe('AuthService', () => {
|
||||
|
||||
const result = await service.login({
|
||||
account: 'zhanxi',
|
||||
password: TEST_ADMIN_PASSWORD,
|
||||
password: SUPER_ADMIN_INITIAL_PASSWORD,
|
||||
});
|
||||
|
||||
expect(result.token).toBe('token_001');
|
||||
@@ -147,6 +150,19 @@ describe('AuthService', () => {
|
||||
expect(repository.markLogin).toHaveBeenCalledWith('user_admin');
|
||||
});
|
||||
|
||||
it('允许通过服务器环境变量覆盖超级管理员初始化密码', async () => {
|
||||
const { service } = await createService({
|
||||
superAdminPassword: 'server-only-password',
|
||||
});
|
||||
|
||||
const result = await service.login({
|
||||
account: 'zhanxi',
|
||||
password: 'server-only-password',
|
||||
});
|
||||
|
||||
expect(result.user.role).toBe('super_admin');
|
||||
});
|
||||
|
||||
it('拒绝超级管理员使用忘记密码流程', async () => {
|
||||
const { service } = await createService();
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ import { AppError } from '../common/errors/app-error';
|
||||
import { EnvConfig } from '../config/env.schema';
|
||||
import { MessagesService } from '../messages/messages.service';
|
||||
import {
|
||||
LOCAL_SUPER_ADMIN_INITIAL_PASSWORD,
|
||||
MEMBER_INITIAL_PASSWORD,
|
||||
SUPER_ADMIN_INITIAL_PASSWORD,
|
||||
} from './auth.constants';
|
||||
import { AuthTokenService } from './auth-token.service';
|
||||
import {
|
||||
@@ -278,14 +278,6 @@ export class AuthService implements OnModuleInit {
|
||||
return password;
|
||||
}
|
||||
|
||||
if (this.config.get('NODE_ENV', { infer: true }) === 'production') {
|
||||
throw new AppError(
|
||||
'CONFIG_MISSING',
|
||||
'生产环境缺少 SUPER_ADMIN_INITIAL_PASSWORD,不能初始化超级管理员',
|
||||
500,
|
||||
);
|
||||
}
|
||||
|
||||
return LOCAL_SUPER_ADMIN_INITIAL_PASSWORD;
|
||||
return SUPER_ADMIN_INITIAL_PASSWORD;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { PrismaClient, UserRole, UserStatus } from '@prisma/client';
|
||||
import {
|
||||
SUPER_ADMIN_INITIAL_PASSWORD,
|
||||
SUPER_ADMIN_SEED,
|
||||
} from './auth.constants';
|
||||
import { PasswordService } from './password.service';
|
||||
|
||||
loadProductionEnv();
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
const passwordService = new PasswordService();
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const password = process.env.SUPER_ADMIN_RESET_PASSWORD?.trim()
|
||||
? process.env.SUPER_ADMIN_RESET_PASSWORD.trim()
|
||||
: SUPER_ADMIN_INITIAL_PASSWORD;
|
||||
const passwordHash = await passwordService.hashPassword(password);
|
||||
|
||||
await prisma.user.upsert({
|
||||
where: {
|
||||
account: SUPER_ADMIN_SEED.account,
|
||||
},
|
||||
create: {
|
||||
id: SUPER_ADMIN_SEED.id,
|
||||
account: SUPER_ADMIN_SEED.account,
|
||||
displayName: SUPER_ADMIN_SEED.displayName,
|
||||
role: UserRole.SUPER_ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
passwordHash,
|
||||
mustChangePassword: false,
|
||||
passwordVersion: 1,
|
||||
},
|
||||
update: {
|
||||
displayName: SUPER_ADMIN_SEED.displayName,
|
||||
role: UserRole.SUPER_ADMIN,
|
||||
status: UserStatus.ACTIVE,
|
||||
passwordHash,
|
||||
mustChangePassword: false,
|
||||
passwordVersion: {
|
||||
increment: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log(
|
||||
`超级管理员 ${SUPER_ADMIN_SEED.account} 密码已通过服务器脚本安全重置。`,
|
||||
);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : '未知错误';
|
||||
console.error(`重置超级管理员密码失败:${message}`);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
function loadProductionEnv(): void {
|
||||
const envFile = resolve(process.cwd(), '.env.production');
|
||||
|
||||
if (!existsSync(envFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lines = readFileSync(envFile, 'utf8').split(/\r?\n/);
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
|
||||
if (!trimmed || trimmed.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separatorIndex = trimmed.indexOf('=');
|
||||
|
||||
if (separatorIndex <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = trimmed.slice(0, separatorIndex).trim();
|
||||
const rawValue = trimmed.slice(separatorIndex + 1).trim();
|
||||
|
||||
if (process.env[key] !== undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
process.env[key] = unquoteEnvValue(rawValue);
|
||||
}
|
||||
}
|
||||
|
||||
function unquoteEnvValue(value: string): string {
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
return value.slice(1, -1);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -125,10 +125,12 @@ describe('DeployExecutionService', () => {
|
||||
repository: DeployRunRepository,
|
||||
idempotencyKey: string,
|
||||
): Promise<DeployRunSummary> {
|
||||
return repository.create({
|
||||
const result = await repository.create({
|
||||
...input,
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
return result.run;
|
||||
}
|
||||
|
||||
function step(run: DeployRunSummary, bpmnNodeId: string) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { DeployRunsService } from './deploy-runs.service';
|
||||
describe('DeployRunsService', () => {
|
||||
const baseRun: DeployRunSummary = {
|
||||
id: 'run_001',
|
||||
version: 1,
|
||||
projectKey: 'access-manage',
|
||||
environment: 'test',
|
||||
ref: 'develop',
|
||||
@@ -61,13 +62,16 @@ describe('DeployRunsService', () => {
|
||||
),
|
||||
create: jest.fn((input: CreateDeployRunInput) =>
|
||||
Promise.resolve({
|
||||
...baseRun,
|
||||
id: input.idempotencyKey ?? 'generated_run',
|
||||
projectKey: input.projectKey,
|
||||
environment: input.environment,
|
||||
ref: input.ref,
|
||||
operator: input.operator,
|
||||
trigger: input.trigger ?? 'manual',
|
||||
run: {
|
||||
...baseRun,
|
||||
id: input.idempotencyKey ?? 'generated_run',
|
||||
projectKey: input.projectKey,
|
||||
environment: input.environment,
|
||||
ref: input.ref,
|
||||
operator: input.operator,
|
||||
trigger: input.trigger ?? 'manual',
|
||||
},
|
||||
created: true,
|
||||
}),
|
||||
),
|
||||
updateRun: jest.fn((id: string, patch: { status?: DeployRunStatus }) =>
|
||||
@@ -270,6 +274,10 @@ describe('DeployRunsService', () => {
|
||||
environment: 'production',
|
||||
ref: 'master',
|
||||
operator: 'ops-admin',
|
||||
productionConfirmation: {
|
||||
confirmed: true,
|
||||
summary: '测试已确认生产发布风险',
|
||||
},
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AppError);
|
||||
expect(repository.create).not.toHaveBeenCalled();
|
||||
@@ -308,6 +316,10 @@ describe('DeployRunsService', () => {
|
||||
ref: 'master',
|
||||
operator: 'ops-admin',
|
||||
idempotencyKey: 'self-managed-master',
|
||||
productionConfirmation: {
|
||||
confirmed: true,
|
||||
summary: '测试已确认生产发布风险',
|
||||
},
|
||||
});
|
||||
|
||||
expect(run.id).toBe('self-managed-master');
|
||||
|
||||
@@ -11,6 +11,7 @@ import { NotificationOutboxService } from '../outbox/notification-outbox.service
|
||||
describe('DeployNotificationService', () => {
|
||||
const run: DeployRunSummary = {
|
||||
id: 'run_001',
|
||||
version: 1,
|
||||
projectKey: 'access-manage',
|
||||
environment: 'test',
|
||||
ref: 'develop',
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { EnvConfig } from '../config/env.schema';
|
||||
import { GiteaClient } from '../integrations/gitea/gitea.client';
|
||||
import { JenkinsClient } from '../integrations/jenkins/jenkins.client';
|
||||
import { ProjectRepository } from './project.repository';
|
||||
import { ProjectSummary } from './project.types';
|
||||
import { ProjectsService } from './projects.service';
|
||||
@@ -73,15 +76,24 @@ describe('ProjectsService', () => {
|
||||
AuthService,
|
||||
'listAllowedProjectKeys' | 'requireProjectPermission'
|
||||
>;
|
||||
const jenkins = {
|
||||
healthSummary: jest.fn(() => ({ status: 'not_configured' as const })),
|
||||
} satisfies Pick<JenkinsClient, 'healthSummary'>;
|
||||
const config = {
|
||||
get: jest.fn(() => undefined),
|
||||
} satisfies Pick<ConfigService<EnvConfig, true>, 'get'>;
|
||||
|
||||
return {
|
||||
auth,
|
||||
gitea,
|
||||
jenkins,
|
||||
repository,
|
||||
service: new ProjectsService(
|
||||
repository as unknown as ProjectRepository,
|
||||
gitea as unknown as GiteaClient,
|
||||
jenkins as unknown as JenkinsClient,
|
||||
auth as unknown as AuthService,
|
||||
config as unknown as ConfigService<EnvConfig, true>,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -238,6 +238,7 @@ export class SettingsService {
|
||||
configured,
|
||||
missing,
|
||||
...(definition.optional ? { optional: [...definition.optional] } : {}),
|
||||
...this.booleanFlagGroups(definition),
|
||||
...(definition.note ? { note: definition.note } : {}),
|
||||
...(definition.variableHelp
|
||||
? { variableHelp: this.pickVariableHelp(definition) }
|
||||
@@ -270,6 +271,7 @@ export class SettingsService {
|
||||
configured,
|
||||
missing,
|
||||
...(definition.optional ? { optional: [...definition.optional] } : {}),
|
||||
...this.booleanFlagGroups(definition),
|
||||
note:
|
||||
provider && !providerWebhook
|
||||
? `NOTIFICATION_PROVIDER=${provider} 暂不支持;可选 wecom、feishu、generic。`
|
||||
@@ -312,6 +314,25 @@ export class SettingsService {
|
||||
return !PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(value));
|
||||
}
|
||||
|
||||
private booleanFlagGroups(
|
||||
definition: IntegrationDefinition,
|
||||
): Pick<IntegrationConfigStatus, 'enabled' | 'disabled'> {
|
||||
const booleanKeys = (definition.optional ?? []).filter(
|
||||
(key) => typeof this.config.get(key, { infer: true }) === 'boolean',
|
||||
);
|
||||
const enabled = booleanKeys.filter(
|
||||
(key) => this.config.get(key, { infer: true }) === true,
|
||||
);
|
||||
const disabled = booleanKeys.filter(
|
||||
(key) => this.config.get(key, { infer: true }) === false,
|
||||
);
|
||||
|
||||
return {
|
||||
...(enabled.length > 0 ? { enabled } : {}),
|
||||
...(disabled.length > 0 ? { disabled } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
private resolveStatus(
|
||||
configuredCount: number,
|
||||
missingCount: number,
|
||||
|
||||
@@ -24,6 +24,8 @@ export type IntegrationConfigStatus = {
|
||||
configured: string[];
|
||||
missing: string[];
|
||||
optional?: string[];
|
||||
enabled?: string[];
|
||||
disabled?: string[];
|
||||
note?: string;
|
||||
variableHelp?: Record<string, IntegrationVariableHelp>;
|
||||
};
|
||||
|
||||
@@ -51,6 +51,7 @@ describe('GiteaWebhookService', () => {
|
||||
createRun: jest.fn(() =>
|
||||
Promise.resolve({
|
||||
id: 'gitea:delivery-1:access-manage:develop:abc123',
|
||||
version: 1,
|
||||
projectKey: 'access-manage',
|
||||
environment: 'test' as const,
|
||||
ref: 'develop',
|
||||
|
||||
Reference in New Issue
Block a user