请现场设计一个用户注册与登录的完整 NestJS 模块,包括 DTO、Service、Controller、Guard 和测试。
解读
国内一线/二线公司面试时,这道题常作为“手写核心模块”环节出现,重点考察:
- 是否真正理解 NestJS 的 IoC、装饰器、模块化与分层思想;
- 是否能把“注册-登录-鉴权”这一高频场景做扎实,涵盖参数校验、密码加密、JWT 签发、守卫、异常处理、单元测试;
- 是否具备安全意识(密码加盐、防重复注册、防爆破、防明文存储);
- 代码是否可维护、可测试、可扩展,能否在 15 分钟内让面试官一眼看懂。
知识点
- ValidationPipe + class-validator:国内项目强制要求参数校验,避免手动 if/else。
- bcryptjs:Node.js 环境下过等保、国密合规的常用哈希库。
- JWT Strategy:Passport 官方策略,国内普遍采用“access_token + 刷新令牌”双 Token 方案,但面试现场先给出最简 access_token 即可。
- Custom Guard:演示“角色守卫”扩展点,国内 RBAC 刚需。
- Dependency Inversion:Service 只依赖接口(Repository),方便后续切 MySQL、Mongo、TiDB。
- Testing Module:NestJS 官方 testing 包,必须写单元测试,国内面试加分项。
- 全局异常过滤器:统一返回 { code, message, data },贴合国内前端规范。
- ConfigModule:生产环境密码、JWT 密钥走环境变量,过等保测评。
答案
以下代码可直接在空项目 nest new user-demo 中跑通,依赖安装:
npm i @nestjs/passport passport passport-local passport-jwt bcryptjs class-validator class-transformer
npm i -D @types/bcryptjs @types/passport-local @types/passport-jwt
目录结构(简洁):
src/
├─ auth/
│ ├─ dto/
│ ├─ entities/
│ ├─ auth.service.ts
│ ├─ auth.controller.ts
│ ├─ jwt.strategy.ts
│ ├─ local.strategy.ts
│ ├─ auth.guard.ts
│ ├─ auth.module.ts
├─ common/
│ ├─ filters/
│ ├─ decorators/
├─ app.module.ts
main.ts
- DTO(防重复、防注入)
// auth/dto/register.dto.ts
import { IsEmail, IsString, MinLength, Matches } from 'class-validator';
export class RegisterDto {
@IsEmail({}, { message: '邮箱格式错误' })
email: string;
@IsString()
@MinLength(6, { message: '密码最少6位' })
@Matches(/^[a-zA-Z0-9!@#$%^&*]+$/, { message: '密码含非法字符' })
password: string;
}
// auth/dto/login.dto.ts
export class LoginDto {
@IsEmail()
email: string;
@IsString()
password: string;
}
- Entity(TypeORM 风格,面试可简写 interface)
// auth/entities/user.entity.ts
export class User {
id: number;
email: string;
passwordHash: string;
createdAt: Date;
}
- Repository(接口 + 内存实现,方便单测)
// auth/user.repository.ts
export abstract class UserRepository {
abstract findByEmail(email: string): Promise<User | null>;
abstract create(email: string, passwordHash: string): Promise<User>;
}
// auth/user-memory.repository.ts
@Injectable()
export class UserMemoryRepository extends UserRepository {
private store = new Map<string, User>();
async findByEmail(email: string) {
return this.store.get(email) || null;
}
async create(email: string, passwordHash: string) {
const user = { id: Date.now(), email, passwordHash, createdAt: new Date() };
this.store.set(email, user);
return user;
}
}
- Service(核心逻辑)
// auth/auth.service.ts
@Injectable()
export class AuthService {
constructor(
private readonly userRepo: UserRepository,
private readonly jwtService: JwtService,
) {}
async register(dto: RegisterDto) {
const { email, password } = dto;
const exist = await this.userRepo.findByEmail(email);
if (exist) throw new ConflictException('邮箱已注册');
const hash = await bcrypt.hash(password, 10);
const user = await this.userRepo.create(email, hash);
return { id: user.id, email: user.email };
}
async validateUser(email: string, pass: string) {
const user = await this.userRepo.findByEmail(email);
if (user && (await bcrypt.compare(pass, user.passwordHash))) {
const { passwordHash, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const payload = { email: user.email, sub: user.id };
return { access_token: this.jwtService.sign(payload) };
}
}
- Passport 策略
// auth/local.strategy.ts
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string) {
const user = await this.authService.validateUser(email, password);
if (!user) throw new UnauthorizedException('账号或密码错误');
return user;
}
}
// auth/jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET || 'dev',
});
}
async validate(payload: any) {
return { userId: payload.sub, email: payload.email };
}
}
- Guard(演示 RBAC 扩展点)
// auth/auth.guard.ts
export const JwtAuthGuard = AuthGuard('jwt');
// 可选:RolesGuard
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext) {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) return true;
const { user } = context.switchToHttp().getRequest();
return roles.includes(user.role); // user.role 由 JWT payload 带
}
}
- Controller(REST 风格)
// auth/auth.controller.ts
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('register')
@HttpCode(HttpStatus.CREATED)
async register(@Body() dto: RegisterDto) {
return this.authService.register(dto);
}
@UseGuards(AuthGuard('local'))
@Post('login')
@HttpCode(HttpStatus.OK)
async login(@Request() req) {
return this.authService.login(req.user);
}
@Get('profile')
@UseGuards(JwtAuthGuard)
profile(@Request() req) {
return req.user;
}
}
- Module 组装
// auth/auth.module.ts
@Module({
imports: [
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET || 'dev',
signOptions: { expiresIn: '7d' },
}),
],
controllers: [AuthController],
providers: [
AuthService,
LocalStrategy,
JwtStrategy,
{ provide: UserRepository, useClass: UserMemoryRepository },
],
exports: [AuthService],
})
export class AuthModule {}
- 全局异常过滤器(国内规范)
// common/filters/http-exception.filter.ts
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof HttpException
? exception.getResponse()
: '服务器内部错误';
response.status(status).json({
code: status,
message: typeof message === 'string' ? message : (message as any).message,
data: null,
});
}
}
- main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
app.useGlobalFilters(new AllExceptionsFilter());
app.setGlobalPrefix('api');
await app.listen(3000);
}
bootstrap();
- 单元测试(必须现场手写)
// auth/auth.service.spec.ts
describe('AuthService', () => {
let service: AuthService;
let userRepo: UserRepository;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthService,
{ provide: UserRepository, useClass: UserMemoryRepository },
{ provide: JwtService, useValue: { sign: jest.fn(() => 'fake-jwt') } },
],
}).compile();
service = module.get<AuthService>(AuthService);
userRepo = module.get<UserRepository>(UserRepository);
});
it('注册成功', async () => {
const dto = { email: 'a@b.com', password: '123456' };
const res = await service.register(dto);
expect(res.email).toBe('a@b.com');
const user = await userRepo.findByEmail('a@b.com');
expect(user).toBeDefined();
});
it('重复注册抛 409', async () => {
const dto = { email: 'a@b.com', password: '123456' };
await service.register(dto);
await expect(service.register(dto)).rejects.toThrow(ConflictException);
});
it('登录成功返回 token', async () => {
await service.register({ email: 'a@b.com', password: '123456' });
const user = await service.validateUser('a@b.com', '123456');
const token = await service.login(user);
expect(token.access_token).toBe('fake-jwt');
});
});
跑测试:
npm run test
全部绿灯即完成。
拓展思考
- 国内等保 2.0 要求密码定期更换、复杂度策略,可扩展
PasswordPolicyService,在注册/修改密码时校验历史密码、弱口令字典。 - 防暴力破解:登录错误次数累计,Redis 记录 IP+邮箱维度,超限锁定 15 分钟;NestJS 可封装
ThrottlerGuard。 - 双 Token 机制:access_token 5 分钟 + refresh_token 7 天,refresh 走
/auth/refresh,需额外实现RefreshJwtStrategy,并存储 refresh_token 到 Redis 或数据库,支持主动吊销。 - 手机号 + 验证码登录:国内主流,接入阿里云/腾讯云短信,验证码 5 分钟有效期,同样用 Redis 存储。
- 微信/QQ OAuth:走
@nestjs/passport的passport-wechat策略,注册时自动绑定openid,实现“一键登录”。 - 分库分表:用户量过亿时,使用
userId哈希分片,Repository 层抽象ShardingUserRepository,对 Service 无侵入。 - 国密 SM4/SM3:金融场景下替换 bcrypt 与 JWT 签名,可封装
SmCryptoService,保持接口不变,通过 Config 切换。 - 单元测试覆盖率:国内大厂要求行覆盖 > 90%,使用
jest --coverage,对异常分支、并发场景补充测试。 - 容器化部署:多阶段构建
Dockerfile,先npm ci --only=production,再dist,镜像 < 100 MB;K8s 配置livenessProbe与readinessProbe,滚动发布零中断。 - 灰度发布:基于 Header
x-canary=1转发到新版本 Pod,NestJS 用Middleware读取 Header 写日志,方便回滚。
把以上十点在面试结尾主动抛出,可瞬间拉开与其他候选人的差距。