fix permissions and teacher attendance workflows
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import { Controller, Post, Body, Get, Request, Req, UseGuards } from '@nestjs/common';
|
||||
import { Controller, Post, Body, Get, Request, Req } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/auth.dto';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { Public } from './decorators/public.decorator';
|
||||
import { Authenticated } from './decorators/authenticated.decorator';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
@@ -45,8 +45,7 @@ export class AuthController {
|
||||
}
|
||||
}
|
||||
|
||||
@Public()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Authenticated()
|
||||
@Get('profile')
|
||||
getProfile(@Request() req: any) {
|
||||
return req.user;
|
||||
|
||||
29
apps/server/src/auth/auth.service.spec.ts
Normal file
29
apps/server/src/auth/auth.service.spec.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService — super admin identity', () => {
|
||||
it('marks the preset 超管 role as super admin in the JWT payload', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
name: '管理员',
|
||||
passwordHash: await bcrypt.hash('secret', 4),
|
||||
isActive: true,
|
||||
roles: [{ name: '超管', status: 1 }],
|
||||
}),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const jwtService = { sign: jest.fn().mockReturnValue('token') };
|
||||
const rbacService = {
|
||||
getUserPermissions: jest.fn().mockResolvedValue(['attendance:create']),
|
||||
};
|
||||
const service = new AuthService(userRepo as never, jwtService as never, rbacService as never);
|
||||
|
||||
await service.login({ username: 'admin', password: 'secret' }, '127.0.0.1');
|
||||
|
||||
expect(jwtService.sign).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ isSuperAdmin: true }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -59,7 +59,12 @@ export class AuthService {
|
||||
|
||||
// 获取用户权限
|
||||
const permissions = await this.rbacService.getUserPermissions(user.id);
|
||||
const isSuperAdmin = user.roles?.some((r) => r.name === 'super_admin') ?? false;
|
||||
const isSuperAdmin =
|
||||
user.roles?.some(
|
||||
(role) =>
|
||||
role.status === 1 &&
|
||||
(role.name === '超管' || role.name === 'super_admin' || role.code === 'super_admin'),
|
||||
) ?? false;
|
||||
const payload = { sub: user.id, username: user.username, permissions, isSuperAdmin };
|
||||
|
||||
// 获取角色名称列表
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const AUTHENTICATED_KEY = 'authenticatedOnly';
|
||||
|
||||
/**
|
||||
* 标记为“只需要登录”的接口:仍由全局 JwtAuthGuard 校验 JWT,
|
||||
* 但 PermissionGuard 不要求具体业务权限。
|
||||
*/
|
||||
export const Authenticated = () => SetMetadata(AUTHENTICATED_KEY, true);
|
||||
50
apps/server/src/auth/guards/permission.guard.spec.ts
Normal file
50
apps/server/src/auth/guards/permission.guard.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { PermissionGuard } from './permission.guard';
|
||||
|
||||
describe('PermissionGuard', () => {
|
||||
const createContext = (user: unknown) =>
|
||||
({
|
||||
getHandler: () => function handler() {},
|
||||
getClass: () => class Controller {},
|
||||
switchToHttp: () => ({ getRequest: () => ({ user }) }),
|
||||
}) as never;
|
||||
|
||||
it('denies routes that forgot to declare permissions', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: jest.fn().mockReturnValue(false),
|
||||
getAllAndMerge: jest.fn().mockReturnValue(undefined),
|
||||
};
|
||||
const guard = new PermissionGuard(reflector as never);
|
||||
|
||||
expect(guard.canActivate(createContext({ permissions: ['dashboard:view'] }))).toBe(false);
|
||||
});
|
||||
|
||||
it('allows explicitly public routes without a user', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: jest.fn().mockReturnValue(true),
|
||||
getAllAndMerge: jest.fn(),
|
||||
};
|
||||
const guard = new PermissionGuard(reflector as never);
|
||||
|
||||
expect(guard.canActivate(createContext(undefined))).toBe(true);
|
||||
});
|
||||
|
||||
it('allows authenticated-only routes for logged-in users without requiring profile:view', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: jest.fn().mockReturnValueOnce(false).mockReturnValueOnce(true),
|
||||
getAllAndMerge: jest.fn(),
|
||||
};
|
||||
const guard = new PermissionGuard(reflector as never);
|
||||
|
||||
expect(guard.canActivate(createContext({ permissions: [] }))).toBe(true);
|
||||
});
|
||||
|
||||
it('denies authenticated-only routes when no authenticated user is present', () => {
|
||||
const reflector = {
|
||||
getAllAndOverride: jest.fn().mockReturnValueOnce(false).mockReturnValueOnce(true),
|
||||
getAllAndMerge: jest.fn(),
|
||||
};
|
||||
const guard = new PermissionGuard(reflector as never);
|
||||
|
||||
expect(guard.canActivate(createContext(undefined))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -2,18 +2,19 @@ import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
import { PERMISSION_KEY } from '../decorators/permission.decorator';
|
||||
import { AUTHENTICATED_KEY } from '../decorators/authenticated.decorator';
|
||||
|
||||
/**
|
||||
* 权限守卫 — 默认放行策略(⚠️ 安全关键)
|
||||
* 权限守卫 — 默认拒绝策略(安全关键)
|
||||
*
|
||||
* 当 handler/controller 上不存在 @RequirePermission 时,守卫放行(仅需登录即可访问)。
|
||||
* 这是有意的设计选择:所有敏感路由必须显式标注 @RequirePermission。
|
||||
* 当 handler/controller 上不存在 @RequirePermission、@Authenticated 且未标记 @Public 时,守卫拒绝访问。
|
||||
* 所有路由必须显式声明公开、仅登录或所需权限。
|
||||
*
|
||||
* ⚠️ 新增路由时务必添加 @RequirePermission,否则该路由对所有已认证用户开放!
|
||||
* ⚠️ 新增路由时务必添加 @RequirePermission、@Authenticated 或 @Public。
|
||||
* 建议配合 lint 规则确保无遗漏。
|
||||
*/
|
||||
@Injectable()
|
||||
export class PermissionGuard implements CanActivate {
|
||||
@Injectable()
|
||||
export class PermissionGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
@@ -24,20 +25,28 @@ import { PERMISSION_KEY } from '../decorators/permission.decorator';
|
||||
]);
|
||||
if (isPublic) return true;
|
||||
|
||||
// 2. 获取所需权限(getAllAndMerge 合并 handler+class 层的所有 metadata)
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
|
||||
// 2. @Authenticated() 只要求已登录,具体 JWT 有效性由 JwtAuthGuard 负责。
|
||||
const authenticatedOnly = this.reflector.getAllAndOverride<boolean>(AUTHENTICATED_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (authenticatedOnly) return !!user;
|
||||
|
||||
// 3. 获取所需权限(getAllAndMerge 合并 handler+class 层的所有 metadata)
|
||||
const requiredPermissions = this.reflector.getAllAndMerge<string[]>(PERMISSION_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
// 无装饰器 = 仅需登录即可,放行
|
||||
if (!requiredPermissions || requiredPermissions.length === 0) return true;
|
||||
// 无权限声明且非 @Public/@Authenticated:默认拒绝,避免新增接口意外裸奔
|
||||
if (!requiredPermissions || requiredPermissions.length === 0) return false;
|
||||
|
||||
// 3. 从 JWT payload 获取用户权限
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
// 4. 从 JWT payload 获取用户权限
|
||||
if (!user || !user.permissions || !Array.isArray(user.permissions)) return false;
|
||||
|
||||
// 4. OR 匹配:用户拥有 requiredPermissions 中任一权限即可通过
|
||||
// 5. OR 匹配:用户拥有 requiredPermissions 中任一权限即可通过
|
||||
return requiredPermissions.some((p) => user.permissions.includes(p));
|
||||
}
|
||||
}
|
||||
|
||||
48
apps/server/src/auth/strategies/jwt.strategy.spec.ts
Normal file
48
apps/server/src/auth/strategies/jwt.strategy.spec.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
|
||||
describe('JwtStrategy', () => {
|
||||
const config = { get: jest.fn().mockReturnValue('secret') };
|
||||
|
||||
it('refreshes permissions from the database instead of trusting stale JWT permissions', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 7,
|
||||
username: 'teacher',
|
||||
isActive: true,
|
||||
isArchived: false,
|
||||
roles: [
|
||||
{
|
||||
name: '老师',
|
||||
status: 1,
|
||||
permissions: [{ code: 'class:view' }, { code: 'attendance:view' }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
const strategy = new JwtStrategy(config as never, userRepo as never);
|
||||
|
||||
await expect(
|
||||
strategy.validate({ sub: 7, username: 'teacher', permissions: ['user:delete'] }),
|
||||
).resolves.toEqual({
|
||||
id: 7,
|
||||
username: 'teacher',
|
||||
permissions: ['class:view', 'attendance:view'],
|
||||
isSuperAdmin: false,
|
||||
roles: ['老师'],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ id: 7, isActive: false, isArchived: false, roles: [] }],
|
||||
[{ id: 7, isActive: true, isArchived: true, roles: [] }],
|
||||
[null],
|
||||
])('rejects disabled, archived, or deleted users', async (user) => {
|
||||
const userRepo = { findOne: jest.fn().mockResolvedValue(user) };
|
||||
const strategy = new JwtStrategy(config as never, userRepo as never);
|
||||
|
||||
await expect(strategy.validate({ sub: 7, username: 'teacher' })).rejects.toBeInstanceOf(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,18 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request } from 'express';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { User } from '../../entities/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(config: ConfigService) {
|
||||
constructor(
|
||||
config: ConfigService,
|
||||
@InjectRepository(User) private readonly userRepo: Repository<User>,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromExtractors([
|
||||
// 1. Standard Bearer header (existing behavior)
|
||||
@@ -25,12 +31,32 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
async validate(payload: { sub?: number; username?: string }) {
|
||||
if (!payload.sub) throw new UnauthorizedException('登录状态无效');
|
||||
const user = await this.userRepo.findOne({
|
||||
where: { id: payload.sub },
|
||||
relations: ['roles', 'roles.permissions'],
|
||||
});
|
||||
if (!user || !user.isActive || user.isArchived) {
|
||||
throw new UnauthorizedException('账号已失效,请重新登录');
|
||||
}
|
||||
|
||||
const permissions = new Set<string>();
|
||||
const roles: string[] = [];
|
||||
let isSuperAdmin = false;
|
||||
for (const role of user.roles ?? []) {
|
||||
if (role.status !== 1) continue;
|
||||
roles.push(role.name);
|
||||
if (role.name === '超管' || role.name === 'super_admin') isSuperAdmin = true;
|
||||
for (const permission of role.permissions ?? []) permissions.add(permission.code);
|
||||
}
|
||||
|
||||
return {
|
||||
id: payload.sub,
|
||||
username: payload.username,
|
||||
permissions: payload.permissions || [],
|
||||
isSuperAdmin: payload.isSuperAdmin || false,
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
permissions: [...permissions],
|
||||
isSuperAdmin,
|
||||
roles,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user