nodejs/nestjs
ip filter middleware
펀치맨
2021. 8. 26. 09:56
🎇middleware 작성
@Injectable()
export class IpFilterMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
let allowIps: string[] = [];
if (process.env.NODE_ENV == 'local') {
allowIps = ['127.0.0.1'];
}
if (!allowIps.includes(req.ip.toString())) {
throw new UnauthorizedException('invalid ip');
}
next();
}
}
🎇 middleware 주입
# app.module.ts
...
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(IpFilterMiddleware).forRoutes('/**');
}
}
반응형