middleware for setting security headers

This commit is contained in:
smart_ex 2022-04-12 19:26:03 +10:00 committed by Danil Kovtonyuk
parent 32af0c955b
commit a935bea718
3 changed files with 23 additions and 8 deletions

View File

@ -1,8 +1,9 @@
import { Module } from '@nestjs/common';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { baseConfig } from '@/config';
import { QueueModule, ApiModule } from '@/modules';
import { setHeadersMiddleware } from '@/modules/api/set-headers.middleware';
@Module({
imports: [
@ -14,4 +15,8 @@ import { QueueModule, ApiModule } from '@/modules';
QueueModule,
],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(setHeadersMiddleware).forRoutes('/');
}
}

View File

@ -1,4 +1,4 @@
import { Controller, Body, Param, Res, Get, Post, HttpStatus } from '@nestjs/common';
import { Body, Controller, Get, HttpStatus, Param, Post, Res } from '@nestjs/common';
import { Response } from 'express';
import { ApiService } from './api.service';
@ -9,13 +9,13 @@ export class ApiController {
constructor(private readonly service: ApiService) {}
@Get('/status')
async status(): Promise<Status> {
return await this.service.status();
async status(@Res() res: Response): Promise<Response<Status>> {
return res.json(await this.service.status());
}
@Get('/')
async root(): Promise<string> {
return this.service.root();
root(@Res() res: Response): Response<string> {
return res.send(this.service.root());
}
@Get('/job/:jobId')
@ -25,7 +25,6 @@ export class ApiController {
if (!job) {
return res.status(HttpStatus.BAD_REQUEST).json({ error: "The job doesn't exist" });
}
return res.json(job);
}

View File

@ -0,0 +1,11 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class setHeadersMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
}
}