Skip to content

Commit

Permalink
Merge pull request #12 from Webster-FR/fix/minor-improvements
Browse files Browse the repository at this point in the history
Merge minor improvements to Main
  • Loading branch information
Xen0Xys authored Jan 6, 2024
2 parents f011261 + 1bd330d commit 1587d5a
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 24 deletions.
9 changes: 7 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Module} from "@nestjs/common";
import {MiddlewareConsumer, Module} from "@nestjs/common";
import {AuthModule} from "./auth/auth.module";
import {VersionModule} from "./version/version.module";
import {ConfigModule} from "@nestjs/config";
Expand All @@ -12,6 +12,7 @@ import {ScheduleModule} from "@nestjs/schedule";
import {TasksModule} from "./tasks/tasks.module";
import {SecretsModule} from "./secrets/secrets.module";
import {AccountsModule} from "./accounts/accounts.module";
import {LoggerMiddleware} from "./middlewares/logger.middleware";

@Module({
imports: [
Expand All @@ -30,4 +31,8 @@ import {AccountsModule} from "./accounts/accounts.module";
AccountsModule,
],
})
export class AppModule{}
export class AppModule{
configure(consumer: MiddlewareConsumer){
consumer.apply(LoggerMiddleware).forRoutes("*");
}
}
9 changes: 5 additions & 4 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {FastifyAdapter, NestFastifyApplication} from "@nestjs/platform-fastify";
import {CustomValidationPipe} from "./pipes/custom-validation.pipe";
import {DocumentBuilder, SwaggerModule} from "@nestjs/swagger";
import {LoggerMiddleware} from "./middlewares/logger.middleware";
// import compression from "@fastify/compress";
// import helmet from "@fastify/helmet";
import {RawServerDefault} from "fastify";
Expand All @@ -12,9 +11,12 @@ import * as dotenv from "dotenv";
import * as fs from "fs";
import * as os from "os";
import {SwaggerTheme} from "swagger-themes";
import {Logger} from "@nestjs/common";

dotenv.config();

const logger: Logger = new Logger("Main");

async function bootstrap(){
switch (process.env.SERVER_TYPE){
case "http":
Expand All @@ -28,7 +30,7 @@ async function bootstrap(){
await startHttpsServer();
break;
default:
console.error("Invalid SERVER_TYPE");
logger.error("Invalid SERVER_TYPE");
process.exit(1);
}
}
Expand All @@ -53,7 +55,7 @@ function getServerAddress(bindAddress: string, port: string | number, protocol:
}

function logServerStart(bindAddress: string, port: string | number, protocol: string){
console.log(`Server started on ${getServerAddress(bindAddress, port, protocol)}`);
logger.log(`Server started on ${getServerAddress(bindAddress, port, protocol)}`);
}

async function startHttpServer(){
Expand Down Expand Up @@ -83,7 +85,6 @@ async function loadServer(server: NestFastifyApplication<RawServerDefault>, serv
});

// Middlewares
server.use(new LoggerMiddleware().use);
// await server.register(helmet, {
// contentSecurityPolicy: false,
// });
Expand Down
5 changes: 4 additions & 1 deletion src/auth/guards/at.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,17 @@ export class AtGuard implements CanActivate{
const token = AuthController.extractTokenFromHeader(request);
if(!token)
throw new UnauthorizedException("Missing access token");
const dbToken = await this.tokensService.getTokenEntity(token, false, false);
if(!dbToken)
throw new UnauthorizedException("Token not found in database");
let payload: AtPayloadModel;
try{
payload = <AtPayloadModel>this.jwtService.verifyJWT(token, this.configService.get("AT_KEY"));
}catch (e){
throw new UnauthorizedException("Invalid access token");
}
if(!payload)
throw new UnauthorizedException("Invalid access token");
throw new UnauthorizedException("Invalid or missing access token payload");
if(payload.type !== TokenType.ACCESS)
throw new UnauthorizedException("Invalid access type: " + payload.type);
if(await this.tokensService.isTokenBlacklisted(token, false))
Expand Down
5 changes: 4 additions & 1 deletion src/auth/guards/rt.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,17 @@ export class RtGuard implements CanActivate{
const token = AuthController.extractTokenFromHeader(request);
if(!token)
throw new UnauthorizedException("Missing refresh token");
const dbToken = await this.tokensService.getTokenEntity(token, true, false);
if(!dbToken)
throw new UnauthorizedException("Token not found in database");
let payload: AtPayloadModel;
try{
payload = <RtPayloadModel>this.jwtService.verifyJWT(token, this.configService.get("RT_KEY"));
}catch (e){
throw new UnauthorizedException("Invalid refresh token");
}
if(!payload)
throw new UnauthorizedException("Invalid refresh token");
throw new UnauthorizedException("Invalid or missing refresh token payload");
if(payload.type !== TokenType.REFRESH)
throw new UnauthorizedException("Invalid refresh type: " + payload.type);
if(await this.tokensService.isTokenBlacklisted(token, true)){
Expand Down
21 changes: 8 additions & 13 deletions src/middlewares/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
import {Injectable, NestMiddleware} from "@nestjs/common";
import {Injectable, Logger, NestMiddleware} from "@nestjs/common";
import {FastifyReply, FastifyRequest} from "fastify";

@Injectable()
export class LoggerMiddleware implements NestMiddleware{
private static getCurrentTime(): string{
const now = new Date();
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
const seconds = String(now.getSeconds()).padStart(2, "0");
return `[${hours}:${minutes}:${seconds}]`;
}

static logger: Logger = new Logger(LoggerMiddleware.name);

use(req: FastifyRequest["raw"], res: FastifyReply["raw"], next: () => void){
const startTime = Date.now();
res.on("finish", () => {
const currentTime = LoggerMiddleware.getCurrentTime();
res.end = () => {
const httpOrHttps = req.connection.localPort.toString() === process.env.HTTPS_PORT ? "HTTPS" : "HTTP";
const method = req.method;
const path = req.url;
const statusCode = res.statusCode;
const duration = Date.now() - startTime;
const resSize = res.getHeader("Content-Length") || "N/A";
console.log(`${currentTime} ${httpOrHttps} ${method} ${path} ${statusCode} ${duration}ms ${resSize}`);
});
const resSize = res.getHeader("content-length") || "N/A";
LoggerMiddleware.logger.log(`${httpOrHttps} ${method} ${path} ${statusCode} ${duration}ms ${resSize}`);
return null;
};
next();
}
}
9 changes: 6 additions & 3 deletions src/services/tokens.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,23 @@ export class TokensService{
return this.jwtService.generateJWT({...payload}, this.configService.get<string>("VC_DURATION") + "m", this.configService.get("CT_KEY"));
}

async getTokenEntity(token: string, isRefresh: boolean): Promise<TokenEntity>{
async getTokenEntity(token: string, isRefresh: boolean, exception: boolean = true): Promise<TokenEntity>{
const sum = this.encryptionService.getSum(token).substring(0, 10);
const tokens = await this.prismaService.tokens.findMany({
where: {
sum: sum,
is_refresh: isRefresh,
},
});
if(!tokens)
if(!tokens && exception)
throw new NotFoundException("Token not found");
for(const dbToken of tokens)
if(await this.encryptionService.compareHash(dbToken.token, token))
return dbToken;
throw new NotFoundException("Token not found");
if(exception)
throw new NotFoundException("Token not found");
else
return null;
}

async blacklistToken(token: string, isRefresh: boolean){
Expand Down

0 comments on commit 1587d5a

Please sign in to comment.