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

+174
View File
@@ -0,0 +1,174 @@
import { ErrorCode, SPECIAL_PERMISSIONS } from '@lingxi/shared';
import { type CanActivate, type ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AppException } from '../errors/app-exception';
import type { AuthContext, AuthenticatedRequest } from './auth.types';
import { IS_PUBLIC_KEY, PERMISSIONS_KEY } from './decorators';
import { PermissionService } from './permission.service';
import { RequestContextService } from './request-context';
import { TokenService } from './token.service';
const MUST_CHANGE_ALLOWED_PATHS: readonly string[] = [
'/api/v1/me',
'/api/v1/auth/change-password',
'/api/v1/auth/logout',
'/api/v1/auth/refresh',
];
const SPECIAL_PERMISSION_SET: ReadonlySet<string> = new Set<string>(SPECIAL_PERMISSIONS);
function extractBearer(header: string | undefined): string | null {
if (!header?.startsWith('Bearer ')) {
return null;
}
const token = header.slice('Bearer '.length).trim();
return token.length > 0 ? token : null;
}
function isMustChangeAllowed(url: string): boolean {
const path = url.split('?')[0] ?? url;
return MUST_CHANGE_ALLOWED_PATHS.includes(path);
}
function isPublic(reflector: Reflector, context: ExecutionContext): boolean {
const value: unknown = reflector.getAllAndOverride(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
return value === true;
}
function requiredPermissions(reflector: Reflector, context: ExecutionContext): string[] {
const value: unknown = reflector.getAllAndOverride(PERMISSIONS_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!Array.isArray(value)) {
return [];
}
return value.filter((code): code is string => typeof code === 'string');
}
function authOf(context: ExecutionContext): AuthContext | null {
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
return request.auth ?? null;
}
function requireAuth(context: ExecutionContext): AuthContext {
const auth = authOf(context);
if (auth === null) {
throw new AppException({ code: ErrorCode.UNAUTHENTICATED });
}
return auth;
}
/**
* 1) JWT 校验 → 每请求解析权限 → 强制改密拦截。
* 守卫顺序由 SecurityModule 的 APP_GUARD 注册顺序保证:
* JwtAuthGuard → PermissionGuard → SpecialPermissionGuard → ScopeGuard。
*/
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
@Inject(Reflector) private readonly reflector: Reflector,
@Inject(TokenService) private readonly tokens: TokenService,
@Inject(PermissionService) private readonly permissions: PermissionService,
@Inject(RequestContextService) private readonly requestContext: RequestContextService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
if (isPublic(this.reflector, context)) {
return true;
}
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
const token = extractBearer(request.headers.authorization);
if (token === null) {
throw new AppException({ code: ErrorCode.UNAUTHENTICATED });
}
const payload = this.tokens.verifyAccess(token);
const auth = await this.permissions.resolveAuth(payload.sub);
if (auth === null) {
throw new AppException({ code: ErrorCode.UNAUTHENTICATED });
}
if (auth.status === 'disabled') {
throw new AppException({ code: ErrorCode.PERMISSION_DENIED, message: '账号已停用' });
}
if (auth.mustChangePassword && !isMustChangeAllowed(request.url)) {
throw new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '请先修改初始密码' });
}
request.auth = auth;
this.requestContext.patch({
userId: auth.userId,
account: auth.account,
permissions: auth.permissions,
});
return true;
}
}
/** 2) 普通权限点校验;特殊权限留给 SpecialPermissionGuard(40301 与 40303 分开) */
@Injectable()
export class PermissionGuard implements CanActivate {
constructor(@Inject(Reflector) private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
if (isPublic(this.reflector, context)) {
return true;
}
const normal = requiredPermissions(this.reflector, context).filter(
(code) => !SPECIAL_PERMISSION_SET.has(code),
);
if (normal.length === 0) {
return true;
}
const auth = requireAuth(context);
const missing = normal.filter((code) => !auth.permissions.includes(code));
if (missing.length > 0) {
throw new AppException({ code: ErrorCode.PERMISSION_DENIED, details: { missing } });
}
return true;
}
}
/** 3) 特殊权限(导出 / AI 配置 / 审计导出 / 行业发布 / 客户字段审批)单独校验 */
@Injectable()
export class SpecialPermissionGuard implements CanActivate {
constructor(@Inject(Reflector) private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
if (isPublic(this.reflector, context)) {
return true;
}
const special = requiredPermissions(this.reflector, context).filter((code) =>
SPECIAL_PERMISSION_SET.has(code),
);
if (special.length === 0) {
return true;
}
const auth = requireAuth(context);
const missing = special.filter((code) => !auth.permissions.includes(code));
if (missing.length > 0) {
throw new AppException({
code: ErrorCode.SPECIAL_PERMISSION_REQUIRED,
details: { missing },
});
}
return true;
}
}
/**
* 4) 数据范围守卫骨架:A2 按 dataScope 注入 ScopeContext(部门 / 客户集合)。
* A1 identity 接口不返回客户数据,非全局范围暂直接放行。
*/
@Injectable()
export class ScopeGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const auth = authOf(context);
if (auth !== null && auth.dataScope.type !== 'all') {
// TODO(A2-BE-04):按 dataScope 注入 ScopeContext,并在 Repository 强制带 customer_id 过滤
}
return true;
}
}