feat(identity): 完成 A1 身份认证与用户管理全栈落地
ci / 质量门禁 (push) Canceled after 0s

背景:
- 开发计划 A1 批次要求登录/刷新/登出、用户生命周期、路由与按钮权限、
  权限三态用例;视觉已选定方案 B(主从分栏 + 分屏登录)。

改动:
- packages/shared:新增 identity 契约(User/Me/Login/Refresh/Department/Role)
  与 user:view 权限点;写接口 strict 校验。
- apps/api:新增 identity 模块与 Prisma expand 迁移(departments/users/roles/
  user_roles/role_permissions/refresh_tokens);Argon2id、JWT access+refresh
  旋转与 jti 吊销、登录失败锁定、首登强改、守卫链、/me、@Audit 上下文、幂等种子。
- apps/web:按方案 B 落地 /users、/users/new、/users/:id、分屏登录与 403;
  usePermission/<Can>、路由守卫、401 单飞刷新、停用会话兜底、Semi + token。
- e2e:新增 A1-QA-01 六类端到端用例(A1_E2E 门控)。
- openapi 与前端生成类型同步;.env.example 登记认证变量;实施报告入库。

影响面:
- 新增运行时依赖 @nestjs/jwt、argon2(计划 A1-BE-02 已批准,版本精确锁定)。
- 迁移为 expand,不改既有表;本地需 prisma migrate 后重新 seed。
- 平台导航「用户与组织」由 /platform/users 调整为 /users。

回滚方式:
- 代码整体回滚本提交;迁移为 expand,回滚代码不需删表;
- 本地如需彻底回退按实施报告 §6 处理。

验证证据:
- pnpm format:check / lint / typecheck 通过;
- pnpm test:shared 95 / api 60 / web 55;
- pnpm test:int:7 个(真实 PG/Redis);
- A1_E2E=1 playwright test e2e/a1-identity.spec.ts:6/6;
- 报告:docs/开发计划/灵犀_A1身份认证与用户管理_实施报告_V0.1.md
This commit is contained in:
Stev_Wang committed 2026-11-03 00:03:33 +08:00
1 parent f0d218bd99
commit 4d9eb980af
120 files changed
+13112 -314

No files matched your search

@@ -0,0 +1,265 @@
import {
type CreateUserInput,
type DisableUserInput,
ErrorCode,
type ListResponse,
Permission,
ulid,
type UpdateUserInput,
type UserDetail,
type UserListQuery,
type UserSummary,
} from '@lingxi/shared';
import { Inject, Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { AppException } from '../../common/errors/app-exception';
import type { PrismaService } from '../../infra/prisma/prisma.service';
import { PRISMA } from '../../infra/tokens';
import { PasswordService } from './password.service';
import { toUserDetail, toUserSummary, type UserWithRelations } from './user.mapper';
const USER_INCLUDE = {
department: { include: { parent: true } },
roles: { include: { role: true } },
} satisfies Prisma.UserInclude;
function hasPermission(permissions: string[], code: string): boolean {
return permissions.includes(code);
}
/** 用户管理:列表(游标 + 筛选 + 排序)、详情、新建、更新、停用 / 启用 */
@Injectable()
export class UsersService {
constructor(
@Inject(PRISMA) private readonly prisma: PrismaService,
@Inject(PasswordService) private readonly passwords: PasswordService,
) {}
async list(query: UserListQuery): Promise<ListResponse<UserSummary>> {
const where = this.buildWhere(query);
const orderBy = this.buildOrderBy(query);
const cursor = query.cursor;
const rows = await this.prisma.user.findMany({
where,
orderBy,
take: query.limit + 1,
include: USER_INCLUDE,
...(cursor === undefined ? {} : { cursor: { id: cursor }, skip: 1 }),
});
const page = rows.slice(0, query.limit);
const next = rows.length > query.limit ? (page[page.length - 1]?.id ?? null) : null;
return { items: page.map((row) => toUserSummary(row)), next_cursor: next };
}
async detail(id: string, permissions: string[]): Promise<UserDetail> {
const user = await this.findOrThrow(id);
return toUserDetail(user, hasPermission(permissions, Permission.USER_MANAGE));
}
async create(
input: CreateUserInput,
actorId: string,
permissions: string[],
): Promise<UserDetail> {
await this.ensureDepartment(input.departmentId);
await this.ensureRoles(input.roleIds);
const account = input.account.trim().toLowerCase();
const email = `${account}@lingxi.cn`;
await this.ensureUnique({ account, phone: input.phone });
const passwordHash = await this.passwords.hash(input.password);
const id = ulid();
try {
await this.prisma.$transaction([
this.prisma.user.create({
data: {
id,
name: input.name,
account,
email,
phone: input.phone,
passwordHash,
departmentId: input.departmentId,
mustChangePassword: true,
createdBy: actorId,
...(input.remark === undefined ? {} : { remark: input.remark }),
roles: { create: input.roleIds.map((roleId) => ({ roleId })) },
},
}),
]);
} catch (error) {
throw this.mapUniqueError(error);
}
return this.detail(id, permissions);
}
async update(id: string, input: UpdateUserInput, permissions: string[]): Promise<UserDetail> {
const existing = await this.findOrThrow(id);
if (input.departmentId !== undefined) {
await this.ensureDepartment(input.departmentId);
}
if (input.roleIds !== undefined) {
await this.ensureRoles(input.roleIds);
}
if (input.phone !== undefined && input.phone !== existing.phone) {
await this.ensureUnique({ phone: input.phone });
}
const data: Prisma.UserUpdateInput = {
...(input.name === undefined ? {} : { name: input.name }),
...(input.phone === undefined ? {} : { phone: input.phone }),
...(input.departmentId === undefined
? {}
: { department: { connect: { id: input.departmentId } } }),
...(input.remark === undefined ? {} : { remark: input.remark }),
};
try {
await this.prisma.$transaction(async (tx) => {
await tx.user.update({ where: { id }, data });
if (input.roleIds !== undefined) {
await tx.userRole.deleteMany({ where: { userId: id } });
await tx.userRole.createMany({
data: input.roleIds.map((roleId) => ({ userId: id, roleId })),
});
}
});
} catch (error) {
throw this.mapUniqueError(error);
}
return this.detail(id, permissions);
}
async disable(
id: string,
input: DisableUserInput,
actorId: string,
permissions: string[],
): Promise<UserDetail> {
const existing = await this.findOrThrow(id);
if (existing.status === 'DISABLED') {
throw new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '账号已是停用状态' });
}
if (existing.id === actorId) {
throw new AppException({
code: ErrorCode.BUSINESS_RULE_VIOLATION,
message: '不能停用当前登录账号',
});
}
await this.prisma.$transaction([
this.prisma.user.update({
where: { id },
data: {
status: 'DISABLED',
disabledAt: new Date(),
...(input.reason === undefined ? {} : { remark: input.reason }),
},
}),
this.prisma.refreshToken.updateMany({
where: { userId: id, revokedAt: null },
data: { revokedAt: new Date() },
}),
]);
return this.detail(id, permissions);
}
async enable(id: string, permissions: string[]): Promise<UserDetail> {
const existing = await this.findOrThrow(id);
if (existing.status === 'ACTIVE') {
throw new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '账号已是启用状态' });
}
await this.prisma.user.update({
where: { id },
data: { status: 'ACTIVE', disabledAt: null },
});
return this.detail(id, permissions);
}
/** 客户转交占位:A3 客户模块落地前按契约返回 42201(不自造 5xx 错误码) */
transferCustomers(): never {
throw new AppException({
code: ErrorCode.BUSINESS_RULE_VIOLATION,
message: '客户转交将在客户模块(A3)提供',
});
}
private async findOrThrow(id: string): Promise<UserWithRelations> {
const user = await this.prisma.user.findUnique({ where: { id }, include: USER_INCLUDE });
if (user === null) {
throw new AppException({ code: ErrorCode.NOT_FOUND, message: '用户不存在' });
}
return user;
}
private async ensureDepartment(departmentId: string): Promise<void> {
const department = await this.prisma.department.findUnique({ where: { id: departmentId } });
if (department === null) {
throw new AppException({ code: ErrorCode.PARAM_INVALID, message: '所属部门不存在' });
}
}
private async ensureRoles(roleIds: string[]): Promise<void> {
const count = await this.prisma.role.count({
where: { id: { in: roleIds }, status: 'ACTIVE' },
});
if (count !== new Set(roleIds).size) {
throw new AppException({ code: ErrorCode.PARAM_INVALID, message: '角色不存在或已停用' });
}
}
private async ensureUnique(input: { account?: string; phone?: string }): Promise<void> {
const existing = await this.prisma.user.findFirst({
where: {
OR: [
...(input.account === undefined ? [] : [{ account: input.account }]),
...(input.phone === undefined ? [] : [{ phone: input.phone }]),
],
},
select: { account: true, phone: true },
});
if (existing !== null) {
throw new AppException({
code: ErrorCode.STATE_NOT_ALLOWED,
message: existing.account === input.account ? '登录账号已存在' : '手机号已存在',
});
}
}
private mapUniqueError(error: unknown): AppException {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
return new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '账号或手机号已存在' });
}
return error instanceof AppException
? error
: new AppException({ code: ErrorCode.INTERNAL_ERROR, message: '用户保存失败' });
}
private buildWhere(query: UserListQuery): Prisma.UserWhereInput {
const where: Prisma.UserWhereInput = {};
if (query.status !== 'all') {
where.status = query.status === 'active' ? 'ACTIVE' : 'DISABLED';
}
if (query.keyword !== undefined && query.keyword.length > 0) {
where.OR = [
{ name: { contains: query.keyword, mode: 'insensitive' } },
{ account: { contains: query.keyword, mode: 'insensitive' } },
{ phone: { contains: query.keyword } },
];
}
if (query.department_id !== undefined) {
where.department = {
OR: [{ id: query.department_id }, { parentId: query.department_id }],
};
}
if (query.role_id !== undefined) {
where.roles = { some: { roleId: query.role_id } };
}
return where;
}
private buildOrderBy(query: UserListQuery): Prisma.UserOrderByWithRelationInput[] {
const direction: Prisma.SortOrder = query.order === 'asc' ? 'asc' : 'desc';
if (query.sort === 'created_at') {
return [{ createdAt: direction }, { id: 'asc' }];
}
return [{ lastLoginAt: { sort: direction, nulls: 'last' } }, { id: 'asc' }];
}
}