feat: 接入真实登录与成员权限

- auth/members/messages: 新增超级管理员登录、成员权限和密码消息流程
- agent-config/agent: 支持服务端保存 Agent 配置并取消未配置 mock 成功结果
- projects/deploy-runs/settings: 按当前用户权限保护真实接口
- prisma: 新增用户、项目权限和平台消息表结构
This commit is contained in:
湛兮
2026-06-12 00:38:23 +08:00
parent cf1bebf625
commit bc3aa31289
83 changed files with 3844 additions and 378 deletions
+6
View File
@@ -0,0 +1,6 @@
import { SetMetadata } from '@nestjs/common';
export const ADMIN_ONLY_MESSAGE_KEY = 'adminOnlyMessage';
export const AdminOnlyMessage = (message: string) =>
SetMetadata(ADMIN_ONLY_MESSAGE_KEY, message);
+143
View File
@@ -0,0 +1,143 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHmac, timingSafeEqual } from 'crypto';
import { AppError } from '../common/errors/app-error';
import { EnvConfig } from '../config/env.schema';
import { AUTH_TOKEN_VERSION } from './auth.constants';
import { AuthenticatedUser } from './auth.types';
import { UserRepository } from './user.repository';
type TokenPayload = {
ver: typeof AUTH_TOKEN_VERSION;
sub: string;
account: string;
role: AuthenticatedUser['role'];
passwordVersion: number;
iat: number;
exp: number;
};
@Injectable()
export class AuthTokenService {
constructor(
private readonly config: ConfigService<EnvConfig, true>,
private readonly userRepository: UserRepository,
) {}
sign(user: AuthenticatedUser): { token: string; expiresAt: string } {
const now = Math.floor(Date.now() / 1000);
const ttlSeconds = this.config.get('AUTH_TOKEN_TTL_SECONDS', {
infer: true,
});
const payload: TokenPayload = {
ver: AUTH_TOKEN_VERSION,
sub: user.id,
account: user.account,
role: user.role,
passwordVersion: user.passwordVersion,
iat: now,
exp: now + ttlSeconds,
};
const encodedPayload = Buffer.from(JSON.stringify(payload)).toString(
'base64url',
);
const signature = this.signPayload(encodedPayload);
return {
token: `${AUTH_TOKEN_VERSION}.${encodedPayload}.${signature}`,
expiresAt: new Date(payload.exp * 1000).toISOString(),
};
}
async verify(token: string): Promise<AuthenticatedUser> {
const payload = this.parseToken(token);
const user = await this.userRepository.findById(payload.sub);
if (!user) {
throw new AppError('AUTH_REQUIRED', '登录已失效,请重新登录', 401);
}
if (user.status !== 'active') {
throw new AppError('FORBIDDEN', '账号已被禁用,请联系超级管理员', 403);
}
if (user.passwordVersion !== payload.passwordVersion) {
throw new AppError('AUTH_REQUIRED', '密码已变更,请重新登录', 401);
}
return this.toAuthenticatedUser(user);
}
private parseToken(token: string): TokenPayload {
const [version, encodedPayload, signature] = token.split('.');
if (version !== AUTH_TOKEN_VERSION || !encodedPayload || !signature) {
throw new AppError('AUTH_REQUIRED', '登录已失效,请重新登录', 401);
}
const expectedSignature = this.signPayload(encodedPayload);
const actual = Buffer.from(signature);
const expected = Buffer.from(expectedSignature);
if (
actual.length !== expected.length ||
!timingSafeEqual(actual, expected)
) {
throw new AppError('AUTH_REQUIRED', '登录已失效,请重新登录', 401);
}
let payload: TokenPayload;
try {
payload = JSON.parse(
Buffer.from(encodedPayload, 'base64url').toString('utf8'),
) as TokenPayload;
} catch {
throw new AppError('AUTH_REQUIRED', '登录已失效,请重新登录', 401);
}
if (payload.exp < Math.floor(Date.now() / 1000)) {
throw new AppError('AUTH_REQUIRED', '登录已过期,请重新登录', 401);
}
return payload;
}
private signPayload(encodedPayload: string): string {
return createHmac('sha256', this.resolveSecret())
.update(encodedPayload)
.digest('base64url');
}
private resolveSecret(): string {
const secret =
this.config.get('AUTH_TOKEN_SECRET', { infer: true }) ??
this.config.get('SECRET_ENCRYPTION_KEY', { infer: true });
if (secret) {
return secret;
}
if (this.config.get('NODE_ENV', { infer: true }) === 'production') {
throw new AppError(
'CONFIG_MISSING',
'生产环境缺少 AUTH_TOKEN_SECRET,不能签发登录令牌',
500,
);
}
return 'devops-platform-local-auth-secret';
}
private toAuthenticatedUser(user: AuthenticatedUser): AuthenticatedUser {
return {
id: user.id,
account: user.account,
displayName: user.displayName,
role: user.role,
status: user.status,
mustChangePassword: user.mustChangePassword,
passwordVersion: user.passwordVersion,
};
}
}
+13
View File
@@ -0,0 +1,13 @@
export const SUPER_ADMIN_SEED = {
id: 'user_super_admin_zhanxi',
account: 'zhanxi',
displayName: '超级管理员',
} as const;
export const LOCAL_SUPER_ADMIN_INITIAL_PASSWORD = 'devops-local-admin';
export const MEMBER_INITIAL_PASSWORD = '111111';
export const AUTH_COOKIE_NAME = 'devops_auth_token';
export const AUTH_TOKEN_VERSION = 'v1';
+78
View File
@@ -0,0 +1,78 @@
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import {
ApiBody,
ApiCreatedResponse,
ApiOkResponse,
ApiTags,
} from '@nestjs/swagger';
import { ZodValidationPipe } from '../common/pipes/zod-validation.pipe';
import { AuthGuard } from './auth.guard';
import {
ChangePasswordDto,
ChangePasswordInput,
ForgotPasswordDto,
ForgotPasswordInput,
LoginDto,
LoginInput,
changePasswordSchema,
forgotPasswordSchema,
loginSchema,
} from './auth.dto';
import { AuthService } from './auth.service';
import { CurrentUser } from './current-user.decorator';
import { AuthenticatedUser, LoginResult } from './auth.types';
@ApiTags('登录鉴权')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('login')
@ApiBody({ type: LoginDto })
@ApiCreatedResponse({ description: '登录成功,返回登录令牌和当前账号信息。' })
async login(
@Body(new ZodValidationPipe(loginSchema)) body: LoginInput,
): Promise<LoginResult> {
return this.authService.login(body);
}
@Get('me')
@UseGuards(AuthGuard)
@ApiOkResponse({ description: '获取当前登录账号信息。' })
getCurrentUser(@CurrentUser() user: AuthenticatedUser): AuthenticatedUser {
return user;
}
@Post('change-password')
@UseGuards(AuthGuard)
@ApiBody({ type: ChangePasswordDto })
@ApiOkResponse({ description: '修改当前登录账号密码。' })
async changePassword(
@CurrentUser() user: AuthenticatedUser,
@Body(new ZodValidationPipe(changePasswordSchema))
body: ChangePasswordInput,
): Promise<AuthenticatedUser> {
return this.authService.changePassword(user, body);
}
@Post('forgot-password')
@ApiBody({ type: ForgotPasswordDto })
@ApiCreatedResponse({
description: '普通成员忘记密码时通知超级管理员处理。',
})
async forgotPassword(
@Body(new ZodValidationPipe(forgotPasswordSchema))
body: ForgotPasswordInput,
): Promise<{ message: string }> {
return this.authService.forgotPassword(body);
}
@Post('logout')
@UseGuards(AuthGuard)
@ApiOkResponse({ description: '退出登录。' })
logout(): { message: string } {
return {
message: '已退出登录',
};
}
}
+43
View File
@@ -0,0 +1,43 @@
import { ApiProperty } from '@nestjs/swagger';
import { z } from 'zod';
export const loginSchema = z.object({
account: z.string().trim().min(1).max(80),
password: z.string().min(1).max(200),
});
export type LoginInput = z.infer<typeof loginSchema>;
export class LoginDto {
@ApiProperty({ example: 'zhanxi', description: '登录账号' })
account!: string;
@ApiProperty({ example: 'change-me-from-server-env', description: '登录密码' })
password!: string;
}
export const changePasswordSchema = z.object({
currentPassword: z.string().min(1).max(200),
newPassword: z.string().min(6).max(200),
});
export type ChangePasswordInput = z.infer<typeof changePasswordSchema>;
export class ChangePasswordDto {
@ApiProperty({ description: '当前密码' })
currentPassword!: string;
@ApiProperty({ description: '新密码,至少 6 位' })
newPassword!: string;
}
export const forgotPasswordSchema = z.object({
account: z.string().trim().min(1).max(80),
});
export type ForgotPasswordInput = z.infer<typeof forgotPasswordSchema>;
export class ForgotPasswordDto {
@ApiProperty({ example: 'member01', description: '普通成员账号' })
account!: string;
}
+47
View File
@@ -0,0 +1,47 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { AUTH_COOKIE_NAME } from './auth.constants';
import { AuthTokenService } from './auth-token.service';
import { RequestWithUser } from './auth.types';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly authTokenService: AuthTokenService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<RequestWithUser>();
const token = this.resolveToken(request);
if (!token) {
throw new AppError('AUTH_REQUIRED', '登录已失效,请重新登录', 401);
}
request.user = await this.authTokenService.verify(token);
return true;
}
private resolveToken(request: RequestWithUser): string | undefined {
const authorization = this.firstHeader(request.headers.authorization);
if (authorization?.startsWith('Bearer ')) {
return authorization.slice('Bearer '.length).trim();
}
const cookie = this.firstHeader(request.headers.cookie);
if (!cookie) {
return undefined;
}
const entries = cookie.split(';').map((item) => item.trim().split('='));
const tokenEntry = entries.find(([name]) => name === AUTH_COOKIE_NAME);
return tokenEntry?.[1] ? decodeURIComponent(tokenEntry[1]) : undefined;
}
private firstHeader(
value: string | string[] | undefined,
): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
}
+36
View File
@@ -0,0 +1,36 @@
import { Global, Module, forwardRef } from '@nestjs/common';
import { AuditModule } from '../audit/audit.module';
import { MessagesModule } from '../messages/messages.module';
import { AuthController } from './auth.controller';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
import { AuthTokenService } from './auth-token.service';
import { PasswordChangeGuard } from './password-change.guard';
import { PasswordService } from './password.service';
import { SuperAdminGuard } from './super-admin.guard';
import { UserRepository } from './user.repository';
@Global()
@Module({
imports: [AuditModule, forwardRef(() => MessagesModule)],
controllers: [AuthController],
providers: [
AuthGuard,
AuthService,
AuthTokenService,
PasswordChangeGuard,
PasswordService,
SuperAdminGuard,
UserRepository,
],
exports: [
AuthGuard,
AuthService,
AuthTokenService,
PasswordChangeGuard,
PasswordService,
SuperAdminGuard,
UserRepository,
],
})
export class AuthModule {}
+179
View File
@@ -0,0 +1,179 @@
import { AuditService } from '../audit/audit.service';
import { MessagesService } from '../messages/messages.service';
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 { 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);
const memberHash = await passwordService.hashPassword(MEMBER_INITIAL_PASSWORD);
const users = new Map<string, UserRecord>();
const admin: UserRecord = {
id: 'user_admin',
account: 'zhanxi',
displayName: '超级管理员',
role: 'super_admin',
status: 'active',
passwordHash: adminHash,
mustChangePassword: false,
passwordVersion: 1,
createdAt: '2026-06-11T00:00:00.000Z',
updatedAt: '2026-06-11T00:00:00.000Z',
projectPermissions: [],
};
const member: UserRecord = {
id: 'user_member',
account: 'member01',
displayName: '成员一',
role: 'member',
status: 'active',
passwordHash: memberHash,
mustChangePassword: true,
passwordVersion: 1,
createdAt: '2026-06-11T00:00:00.000Z',
updatedAt: '2026-06-11T00:00:00.000Z',
projectPermissions: [],
};
users.set(admin.id, admin);
users.set(member.id, member);
const repository = {
ensureSuperAdmin: jest.fn(),
findByAccount: jest.fn((account: string) =>
Promise.resolve(
[...users.values()].find((user) => user.account === account) ?? null,
),
),
findById: jest.fn((id: string) => Promise.resolve(users.get(id) ?? null)),
markLogin: jest.fn(() => Promise.resolve()),
updatePassword: jest.fn(
(id: string, passwordHash: string, mustChangePassword: boolean) => {
const user = users.get(id);
if (!user) {
return Promise.reject(new Error('成员不存在'));
}
const updatedUser: UserRecord = {
...user,
passwordHash,
mustChangePassword,
passwordVersion: user.passwordVersion + 1,
};
users.set(id, updatedUser);
return Promise.resolve(updatedUser);
},
),
getProjectPermissionLevel: jest.fn(),
listAllowedProjectKeys: jest.fn(),
} satisfies Partial<UserRepository>;
const token = {
sign: jest.fn(() => ({
token: 'token_001',
expiresAt: '2026-06-11T12:00:00.000Z',
})),
} satisfies Pick<AuthTokenService, 'sign'>;
const messages = {
createPasswordResetRequest: jest.fn(() =>
Promise.resolve({
id: 'message_001',
type: 'password_reset_request' as const,
status: 'pending' as const,
title: '成员密码重置请求',
content: '账号 member01 的成员请求重置密码,请及时处理。',
requesterId: 'user_member',
requesterAccount: 'member01',
createdAt: '2026-06-11T00:00:00.000Z',
updatedAt: '2026-06-11T00:00:00.000Z',
}),
),
} satisfies Pick<MessagesService, 'createPasswordResetRequest'>;
const audit = {
record: jest.fn(() => Promise.resolve()),
} satisfies Pick<AuditService, 'record'>;
const config = {
get: jest.fn((key: keyof EnvConfig) => {
if (key === 'SUPER_ADMIN_INITIAL_PASSWORD') {
return TEST_ADMIN_PASSWORD;
}
if (key === 'NODE_ENV') {
return 'test';
}
return undefined;
}),
};
return {
admin,
audit,
member,
messages,
repository,
service: new AuthService(
config as unknown as ConfigService<EnvConfig, true>,
repository as unknown as UserRepository,
passwordService,
token as unknown as AuthTokenService,
messages as unknown as MessagesService,
audit as unknown as AuditService,
),
};
}
it('使用内置超级管理员账号登录成功', async () => {
const { repository, service } = await createService();
const result = await service.login({
account: 'zhanxi',
password: TEST_ADMIN_PASSWORD,
});
expect(result.token).toBe('token_001');
expect(result.user.role).toBe('super_admin');
expect(repository.markLogin).toHaveBeenCalledWith('user_admin');
});
it('拒绝超级管理员使用忘记密码流程', async () => {
const { service } = await createService();
await expect(
service.forgotPassword({ account: 'zhanxi' }),
).rejects.toBeInstanceOf(AppError);
});
it('普通成员忘记密码会生成通知消息', async () => {
const { messages, service } = await createService();
const result = await service.forgotPassword({ account: 'member01' });
expect(result.message).toBe('已通知超级管理员协助重置密码');
expect(messages.createPasswordResetRequest).toHaveBeenCalledWith(
expect.objectContaining({ account: 'member01' }),
);
});
it('普通成员改密不能继续使用初始密码', async () => {
const { member, service } = await createService();
await expect(
service.changePassword(member, {
currentPassword: MEMBER_INITIAL_PASSWORD,
newPassword: MEMBER_INITIAL_PASSWORD,
}),
).rejects.toBeInstanceOf(AppError);
});
});
+252
View File
@@ -0,0 +1,252 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AuditService } from '../audit/audit.service';
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,
} from './auth.constants';
import { AuthTokenService } from './auth-token.service';
import {
ChangePasswordInput,
ForgotPasswordInput,
LoginInput,
} from './auth.dto';
import {
AuthenticatedUser,
LoginResult,
ProjectPermissionLevel,
UserRecord,
} from './auth.types';
import { PasswordService } from './password.service';
import { UserRepository } from './user.repository';
@Injectable()
export class AuthService implements OnModuleInit {
constructor(
private readonly config: ConfigService<EnvConfig, true>,
private readonly userRepository: UserRepository,
private readonly passwordService: PasswordService,
private readonly authTokenService: AuthTokenService,
private readonly messagesService: MessagesService,
private readonly auditService: AuditService,
) {}
async onModuleInit(): Promise<void> {
const passwordHash = await this.passwordService.hashPassword(
this.resolveSuperAdminInitialPassword(),
);
await this.userRepository.ensureSuperAdmin(passwordHash);
}
async login(input: LoginInput): Promise<LoginResult> {
const user = await this.userRepository.findByAccount(input.account);
if (!user) {
throw new AppError('AUTH_REQUIRED', '账号或密码错误', 401);
}
if (user.status !== 'active') {
throw new AppError('FORBIDDEN', '账号已被禁用,请联系超级管理员', 403);
}
const passwordMatched = await this.passwordService.verifyPassword(
input.password,
user.passwordHash,
);
if (!passwordMatched) {
throw new AppError('AUTH_REQUIRED', '账号或密码错误', 401);
}
await this.userRepository.markLogin(user.id);
await this.auditService.record({
action: 'USER_LOGIN',
resourceType: 'user',
resourceId: user.id,
actorId: user.id,
actorName: user.account,
after: {
role: user.role,
mustChangePassword: user.mustChangePassword,
},
});
const authenticatedUser = this.toAuthenticatedUser(user);
const tokenResult = this.authTokenService.sign(authenticatedUser);
return {
token: tokenResult.token,
expiresAt: tokenResult.expiresAt,
user: authenticatedUser,
};
}
async changePassword(
currentUser: AuthenticatedUser,
input: ChangePasswordInput,
): Promise<AuthenticatedUser> {
const user = await this.requireUser(currentUser.id);
const passwordMatched = await this.passwordService.verifyPassword(
input.currentPassword,
user.passwordHash,
);
if (!passwordMatched) {
throw new AppError('VALIDATION_FAILED', '当前密码不正确', 400);
}
if (input.currentPassword === input.newPassword) {
throw new AppError('VALIDATION_FAILED', '新密码不能与当前密码相同', 400);
}
if (user.role === 'member' && input.newPassword === MEMBER_INITIAL_PASSWORD) {
throw new AppError(
'VALIDATION_FAILED',
'新密码不能继续使用初始密码',
400,
);
}
const passwordHash = await this.passwordService.hashPassword(
input.newPassword,
);
const updatedUser = await this.userRepository.updatePassword(
user.id,
passwordHash,
false,
);
await this.auditService.record({
action: 'USER_PASSWORD_CHANGED',
resourceType: 'user',
resourceId: user.id,
actorId: user.id,
actorName: user.account,
after: {
mustChangePassword: false,
},
});
return this.toAuthenticatedUser(updatedUser);
}
async forgotPassword(
input: ForgotPasswordInput,
): Promise<{ message: string }> {
const user = await this.userRepository.findByAccount(input.account);
if (!user) {
throw new AppError('RESOURCE_NOT_FOUND', '账号不存在,请确认后重试', 404);
}
if (user.role === 'super_admin') {
throw new AppError(
'FORBIDDEN',
'超级管理员不能使用忘记密码流程,请通过服务器运维方式安全重置',
403,
);
}
if (user.status !== 'active') {
throw new AppError('FORBIDDEN', '账号已被禁用,请联系超级管理员', 403);
}
await this.messagesService.createPasswordResetRequest(user);
await this.auditService.record({
action: 'PASSWORD_RESET_REQUESTED',
resourceType: 'user',
resourceId: user.id,
actorId: user.id,
actorName: user.account,
after: {
requestMerged: true,
},
});
return {
message: '已通知超级管理员协助重置密码',
};
}
async requireProjectPermission(
user: AuthenticatedUser,
projectKey: string,
requiredLevel: Exclude<ProjectPermissionLevel, 'none'>,
): Promise<void> {
if (user.role === 'super_admin') {
return;
}
const level = await this.userRepository.getProjectPermissionLevel(
user,
projectKey,
);
if (level === 'none') {
throw new AppError('FORBIDDEN', '无权限访问该项目', 403, {
projectKey,
});
}
if (requiredLevel === 'build' && level !== 'build') {
throw new AppError('FORBIDDEN', '无权限执行该项目构建', 403, {
projectKey,
});
}
}
async listAllowedProjectKeys(user: AuthenticatedUser): Promise<string[]> {
return this.userRepository.listAllowedProjectKeys(user);
}
assertSuperAdmin(user: AuthenticatedUser, message = '无权限访问该功能'): void {
if (user.role !== 'super_admin') {
throw new AppError('FORBIDDEN', message, 403);
}
}
toAuthenticatedUser(user: UserRecord): AuthenticatedUser {
return {
id: user.id,
account: user.account,
displayName: user.displayName,
role: user.role,
status: user.status,
mustChangePassword: user.mustChangePassword,
passwordVersion: user.passwordVersion,
};
}
private async requireUser(userId: string): Promise<UserRecord> {
const user = await this.userRepository.findById(userId);
if (!user) {
throw new AppError('AUTH_REQUIRED', '登录已失效,请重新登录', 401);
}
return user;
}
private resolveSuperAdminInitialPassword(): string {
const password = this.config.get('SUPER_ADMIN_INITIAL_PASSWORD', {
infer: true,
});
if (password) {
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;
}
}
+57
View File
@@ -0,0 +1,57 @@
export type AuthRole = 'super_admin' | 'member';
export type AuthStatus = 'active' | 'disabled';
export type ProjectPermissionLevel = 'none' | 'read' | 'build';
export type AuthenticatedUser = {
id: string;
account: string;
displayName: string;
role: AuthRole;
status: AuthStatus;
mustChangePassword: boolean;
passwordVersion: number;
};
export type UserRecord = AuthenticatedUser & {
passwordHash: string;
createdAt: string;
updatedAt: string;
lastLoginAt?: string;
createdById?: string;
projectPermissions: UserProjectPermission[];
};
export type UserProjectPermission = {
projectId: string;
projectKey: string;
projectName: string;
level: Exclude<ProjectPermissionLevel, 'none'>;
};
export type UserSummary = Omit<UserRecord, 'passwordHash'> & {
hasPendingPasswordResetRequest: boolean;
};
export type CreateMemberInput = {
account: string;
displayName: string;
permissions?: ProjectPermissionInput[];
};
export type ProjectPermissionInput = {
projectKey: string;
level: ProjectPermissionLevel;
};
export type LoginResult = {
token: string;
user: AuthenticatedUser;
expiresAt: string;
};
export type RequestWithUser = {
headers: Record<string, string | string[] | undefined>;
user?: AuthenticatedUser;
};
+9
View File
@@ -0,0 +1,9 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { AuthenticatedUser, RequestWithUser } from './auth.types';
export const CurrentUser = createParamDecorator(
(_data: unknown, context: ExecutionContext): AuthenticatedUser => {
const request = context.switchToHttp().getRequest<RequestWithUser>();
return request.user as AuthenticatedUser;
},
);
+21
View File
@@ -0,0 +1,21 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { RequestWithUser } from './auth.types';
@Injectable()
export class PasswordChangeGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (user?.role === 'member' && user.mustChangePassword) {
throw new AppError(
'PASSWORD_CHANGE_REQUIRED',
'首次登录必须修改密码后才能访问平台功能',
403,
);
}
return true;
}
}
+40
View File
@@ -0,0 +1,40 @@
import { Injectable } from '@nestjs/common';
import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'crypto';
import { promisify } from 'util';
const scrypt = promisify(scryptCallback);
const PASSWORD_HASH_PREFIX = 'scrypt-sha256-v1';
const PASSWORD_KEY_LENGTH = 64;
@Injectable()
export class PasswordService {
async hashPassword(password: string): Promise<string> {
const salt = randomBytes(16).toString('base64url');
const derivedKey = (await scrypt(
password,
salt,
PASSWORD_KEY_LENGTH,
)) as Buffer;
return [
PASSWORD_HASH_PREFIX,
salt,
derivedKey.toString('base64url'),
].join(':');
}
async verifyPassword(password: string, passwordHash: string): Promise<boolean> {
const [prefix, salt, encodedHash] = passwordHash.split(':');
if (prefix !== PASSWORD_HASH_PREFIX || !salt || !encodedHash) {
return false;
}
const expected = Buffer.from(encodedHash, 'base64url');
const actual = (await scrypt(password, salt, expected.length)) as Buffer;
return (
expected.length === actual.length && timingSafeEqual(expected, actual)
);
}
}
+29
View File
@@ -0,0 +1,29 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AppError } from '../common/errors/app-error';
import {
ADMIN_ONLY_MESSAGE_KEY,
} from './admin-only-message.decorator';
import { RequestWithUser } from './auth.types';
@Injectable()
export class SuperAdminGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (user?.role !== 'super_admin') {
const message =
this.reflector.getAllAndOverride<string>(ADMIN_ONLY_MESSAGE_KEY, [
context.getHandler(),
context.getClass(),
]) ?? '无权限访问该功能';
throw new AppError('FORBIDDEN', message, 403);
}
return true;
}
}
+514
View File
@@ -0,0 +1,514 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
Prisma,
ProjectPermissionLevel as PrismaProjectPermissionLevel,
UserRole as PrismaUserRole,
UserStatus as PrismaUserStatus,
} from '@prisma/client';
import { AppError } from '../common/errors/app-error';
import { EnvConfig } from '../config/env.schema';
import { PrismaService } from '../prisma/prisma.service';
import { seedProjects } from '../projects/project.seed';
import { SUPER_ADMIN_SEED } from './auth.constants';
import {
AuthenticatedUser,
CreateMemberInput,
ProjectPermissionInput,
ProjectPermissionLevel,
UserRecord,
} from './auth.types';
type UserRecordWithPermissions = Prisma.UserGetPayload<{
include: {
projectPermissions: {
include: {
project: true;
};
};
};
}>;
type CreateUserRecordInput = CreateMemberInput & {
id?: string;
passwordHash: string;
role: AuthenticatedUser['role'];
mustChangePassword: boolean;
createdById?: string;
};
@Injectable()
export class UserRepository {
private readonly memoryUsers: UserRecord[] = [];
constructor(
private readonly config: ConfigService<EnvConfig, true>,
private readonly prisma: PrismaService,
) {}
async ensureSuperAdmin(passwordHash: string): Promise<UserRecord> {
if (!this.useDatabase()) {
const existing = await this.findByAccount(SUPER_ADMIN_SEED.account);
if (existing) {
existing.role = 'super_admin';
existing.status = 'active';
existing.displayName = SUPER_ADMIN_SEED.displayName;
existing.mustChangePassword = false;
existing.updatedAt = new Date().toISOString();
return existing;
}
return this.createUser({
id: SUPER_ADMIN_SEED.id,
account: SUPER_ADMIN_SEED.account,
displayName: SUPER_ADMIN_SEED.displayName,
passwordHash,
role: 'super_admin',
mustChangePassword: false,
});
}
const user = await this.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,
passwordHash,
role: PrismaUserRole.SUPER_ADMIN,
status: PrismaUserStatus.ACTIVE,
mustChangePassword: false,
},
update: {
displayName: SUPER_ADMIN_SEED.displayName,
role: PrismaUserRole.SUPER_ADMIN,
status: PrismaUserStatus.ACTIVE,
mustChangePassword: false,
},
include: this.includePermissions(),
});
return this.toRecord(user);
}
async findByAccount(account: string): Promise<UserRecord | null> {
if (!this.useDatabase()) {
return (
this.memoryUsers.find((user) => user.account === account.trim()) ?? null
);
}
const user = await this.prisma.user.findUnique({
where: {
account: account.trim(),
},
include: this.includePermissions(),
});
return user ? this.toRecord(user) : null;
}
async findById(id: string): Promise<UserRecord | null> {
if (!this.useDatabase()) {
return this.memoryUsers.find((user) => user.id === id) ?? null;
}
const user = await this.prisma.user.findUnique({
where: { id },
include: this.includePermissions(),
});
return user ? this.toRecord(user) : null;
}
async listUsers(): Promise<UserRecord[]> {
if (!this.useDatabase()) {
return [...this.memoryUsers].sort((left, right) =>
left.createdAt.localeCompare(right.createdAt),
);
}
const users = await this.prisma.user.findMany({
include: this.includePermissions(),
orderBy: [
{
role: 'desc',
},
{
createdAt: 'asc',
},
],
});
return users.map((user) => this.toRecord(user));
}
async createUser(input: CreateUserRecordInput): Promise<UserRecord> {
if (!this.useDatabase()) {
const now = new Date().toISOString();
const user: UserRecord = {
id: input.id ?? `user_${Date.now()}_${this.memoryUsers.length + 1}`,
account: input.account.trim(),
displayName: input.displayName.trim(),
role: input.role,
status: 'active',
passwordHash: input.passwordHash,
mustChangePassword: input.mustChangePassword,
passwordVersion: 1,
createdById: input.createdById,
createdAt: now,
updatedAt: now,
projectPermissions: [],
};
this.memoryUsers.push(user);
return user;
}
const user = await this.prisma.user.create({
data: {
id: input.id,
account: input.account.trim(),
displayName: input.displayName.trim(),
passwordHash: input.passwordHash,
role: this.toPrismaRole(input.role),
status: PrismaUserStatus.ACTIVE,
mustChangePassword: input.mustChangePassword,
createdById: input.createdById,
},
include: this.includePermissions(),
});
return this.toRecord(user);
}
async updatePassword(
userId: string,
passwordHash: string,
mustChangePassword: boolean,
): Promise<UserRecord> {
if (!this.useDatabase()) {
const user = this.requireMemoryUser(userId);
user.passwordHash = passwordHash;
user.mustChangePassword = mustChangePassword;
user.passwordVersion += 1;
user.updatedAt = new Date().toISOString();
return user;
}
const user = await this.prisma.user.update({
where: { id: userId },
data: {
passwordHash,
mustChangePassword,
passwordVersion: {
increment: 1,
},
},
include: this.includePermissions(),
});
return this.toRecord(user);
}
async markLogin(userId: string): Promise<void> {
if (!this.useDatabase()) {
const user = this.memoryUsers.find((item) => item.id === userId);
if (user) {
user.lastLoginAt = new Date().toISOString();
}
return;
}
await this.prisma.user.update({
where: { id: userId },
data: {
lastLoginAt: new Date(),
},
});
}
async setStatus(
userId: string,
status: Exclude<AuthenticatedUser['status'], 'disabled'> | 'disabled',
): Promise<UserRecord> {
if (!this.useDatabase()) {
const user = this.requireMemoryUser(userId);
user.status = status;
user.updatedAt = new Date().toISOString();
return user;
}
const user = await this.prisma.user.update({
where: { id: userId },
data: {
status:
status === 'active'
? PrismaUserStatus.ACTIVE
: PrismaUserStatus.DISABLED,
},
include: this.includePermissions(),
});
return this.toRecord(user);
}
async deleteUser(userId: string): Promise<void> {
if (!this.useDatabase()) {
const index = this.memoryUsers.findIndex((user) => user.id === userId);
if (index >= 0) {
this.memoryUsers.splice(index, 1);
}
return;
}
await this.prisma.user.delete({
where: { id: userId },
});
}
async replaceProjectPermissions(
userId: string,
permissions: ProjectPermissionInput[],
): Promise<UserRecord> {
const normalizedPermissions = permissions.filter(
(permission) => permission.level !== 'none',
);
if (!this.useDatabase()) {
const user = this.requireMemoryUser(userId);
user.projectPermissions = normalizedPermissions.map((permission) => {
const project = this.findSeedProject(permission.projectKey);
return {
projectId: project.id,
projectKey: project.key,
projectName: project.name,
level: permission.level as Exclude<ProjectPermissionLevel, 'none'>,
};
});
user.updatedAt = new Date().toISOString();
return user;
}
const projects = await this.prisma.project.findMany({
where: {
key: {
in: normalizedPermissions.map((permission) => permission.projectKey),
},
},
});
const missingProjectKeys = normalizedPermissions
.map((permission) => permission.projectKey)
.filter((projectKey) =>
projects.every((project) => project.key !== projectKey),
);
if (missingProjectKeys.length > 0) {
throw new AppError(
'RESOURCE_NOT_FOUND',
`项目不存在:${missingProjectKeys.join('、')}`,
404,
{ projectKeys: missingProjectKeys },
);
}
await this.prisma.$transaction(async (tx) => {
await tx.projectMemberPermission.deleteMany({
where: { userId },
});
if (normalizedPermissions.length > 0) {
await tx.projectMemberPermission.createMany({
data: normalizedPermissions.map((permission) => {
const project = projects.find(
(item) => item.key === permission.projectKey,
);
if (!project) {
throw new Error('项目授权校验异常');
}
return {
userId,
projectId: project.id,
level: this.toPrismaPermissionLevel(permission.level),
};
}),
});
}
});
const user = await this.findById(userId);
if (!user) {
throw new AppError('RESOURCE_NOT_FOUND', '成员不存在', 404, { userId });
}
return user;
}
async getProjectPermissionLevel(
user: AuthenticatedUser,
projectKey: string,
): Promise<ProjectPermissionLevel> {
if (user.role === 'super_admin') {
return 'build';
}
if (!this.useDatabase()) {
const currentUser = this.memoryUsers.find((item) => item.id === user.id);
return (
currentUser?.projectPermissions.find(
(permission) => permission.projectKey === projectKey,
)?.level ?? 'none'
);
}
const permission = await this.prisma.projectMemberPermission.findFirst({
where: {
userId: user.id,
project: {
key: projectKey,
},
},
});
return permission ? this.toPermissionLevel(permission.level) : 'none';
}
async listAllowedProjectKeys(user: AuthenticatedUser): Promise<string[]> {
if (user.role === 'super_admin') {
if (!this.useDatabase()) {
return seedProjects.map((project) => project.key);
}
const projects = await this.prisma.project.findMany({
select: {
key: true,
},
});
return projects.map((project) => project.key);
}
if (!this.useDatabase()) {
const currentUser = this.memoryUsers.find((item) => item.id === user.id);
return (
currentUser?.projectPermissions.map(
(permission) => permission.projectKey,
) ?? []
);
}
const permissions = await this.prisma.projectMemberPermission.findMany({
where: {
userId: user.id,
},
include: {
project: true,
},
});
return permissions.map((permission) => permission.project.key);
}
private requireMemoryUser(userId: string): UserRecord {
const user = this.memoryUsers.find((item) => item.id === userId);
if (!user) {
throw new AppError('RESOURCE_NOT_FOUND', '成员不存在', 404, { userId });
}
return user;
}
private findSeedProject(projectKey: string) {
const project = seedProjects.find((item) => item.key === projectKey);
if (!project) {
throw new AppError(
'RESOURCE_NOT_FOUND',
`项目不存在:${projectKey}`,
404,
{ projectKey },
);
}
return project;
}
private includePermissions(): {
projectPermissions: {
include: {
project: true;
};
};
} {
return {
projectPermissions: {
include: {
project: true,
},
},
};
}
private toRecord(user: UserRecordWithPermissions): UserRecord {
return {
id: user.id,
account: user.account,
displayName: user.displayName,
role:
user.role === PrismaUserRole.SUPER_ADMIN ? 'super_admin' : 'member',
status: user.status === PrismaUserStatus.ACTIVE ? 'active' : 'disabled',
passwordHash: user.passwordHash,
mustChangePassword: user.mustChangePassword,
passwordVersion: user.passwordVersion,
lastLoginAt: user.lastLoginAt?.toISOString(),
createdById: user.createdById ?? undefined,
createdAt: user.createdAt.toISOString(),
updatedAt: user.updatedAt.toISOString(),
projectPermissions: user.projectPermissions.map((permission) => ({
projectId: permission.projectId,
projectKey: permission.project.key,
projectName: permission.project.name,
level: this.toPermissionLevel(permission.level),
})),
};
}
private toPrismaRole(role: AuthenticatedUser['role']): PrismaUserRole {
return role === 'super_admin'
? PrismaUserRole.SUPER_ADMIN
: PrismaUserRole.MEMBER;
}
private toPermissionLevel(
level: PrismaProjectPermissionLevel,
): Exclude<ProjectPermissionLevel, 'none'> {
return level === PrismaProjectPermissionLevel.BUILD ? 'build' : 'read';
}
private toPrismaPermissionLevel(
level: ProjectPermissionLevel,
): PrismaProjectPermissionLevel {
return level === 'build'
? PrismaProjectPermissionLevel.BUILD
: PrismaProjectPermissionLevel.READ;
}
private useDatabase(): boolean {
return (
this.config.get('USE_DATABASE_READS', { infer: true }) &&
Boolean(this.config.get('DATABASE_URL', { infer: true }))
);
}
}