feat: 完善登录鉴权和超级管理员重置
This commit is contained in:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user