Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OV-221: Adjust Backend Respond when Endpoint is not found #248

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 40 additions & 32 deletions backend/src/common/plugins/auth/auth-jwt.plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,48 +10,56 @@ import { isRouteInWhiteList } from './utils/utils.js';

type Options = {
routesWhiteList: Route[];
availableRoutes: Route[];
};

const authenticateJWT = fp<Options>((fastify, { routesWhiteList }, done) => {
fastify.decorateRequest('user', null);
const authenticateJWT = fp<Options>(
(fastify, { routesWhiteList, availableRoutes }, done) => {
fastify.decorateRequest('user', null);

fastify.addHook(Hook.PRE_HANDLER, async (request) => {
if (isRouteInWhiteList(routesWhiteList, request)) {
return;
}
fastify.addHook(Hook.PRE_HANDLER, async (request) => {
if (
isRouteInWhiteList(routesWhiteList, request) ||
!isRouteInWhiteList(availableRoutes, request)
) {
return;
}

const authHeader = request.headers[HttpHeader.AUTHORIZATION];
const authHeader = request.headers[HttpHeader.AUTHORIZATION];

if (!authHeader) {
throw new HttpError({
message: ErrorMessage.MISSING_TOKEN,
status: HttpCode.UNAUTHORIZED,
});
}
if (!authHeader) {
throw new HttpError({
message: ErrorMessage.MISSING_TOKEN,
status: HttpCode.UNAUTHORIZED,
});
}

const [, token] = authHeader.split(' ');
const [, token] = authHeader.split(' ');

const userId = await tokenService.getUserIdFromToken(token as string);
const userId = await tokenService.getUserIdFromToken(
token as string,
);

if (!userId) {
throw new HttpError({
message: ErrorMessage.INVALID_TOKEN,
status: HttpCode.UNAUTHORIZED,
});
}
if (!userId) {
throw new HttpError({
message: ErrorMessage.INVALID_TOKEN,
status: HttpCode.UNAUTHORIZED,
});
}

const user = await userService.findById(userId);
const user = await userService.findById(userId);

if (!user) {
throw new HttpError({
message: ErrorMessage.MISSING_USER,
status: HttpCode.BAD_REQUEST,
});
}
request.user = user.toObject();
});
if (!user) {
throw new HttpError({
message: ErrorMessage.MISSING_USER,
status: HttpCode.BAD_REQUEST,
});
}
request.user = user.toObject();
});

done();
});
done();
},
);

export { authenticateJWT };
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const ErrorMessage = {
MISSING_TOKEN: 'You are not logged in',
INVALID_TOKEN: 'Token is no longer valid. Please log in again.',
MISSING_USER: 'User with this id does not exist.',
URL_NOT_FOUND: 'Not found, route is not available or incorrect',
} as const;

export { ErrorMessage };
42 changes: 40 additions & 2 deletions backend/src/common/server-application/base-server-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { type Config } from '~/common/config/config.js';
import { type Database } from '~/common/database/database.js';
import { ServerErrorType } from '~/common/enums/enums.js';
import { type ValidationError } from '~/common/exceptions/exceptions.js';
import { HttpCode, HttpError } from '~/common/http/http.js';
import { type HttpMethod, HttpCode, HttpError } from '~/common/http/http.js';
import { type Logger } from '~/common/logger/logger.js';
import { session } from '~/common/plugins/session/session.plugin.js';
import {
Expand All @@ -26,6 +26,8 @@ import {
} from '~/common/types/types.js';

import { WHITE_ROUTES } from '../constants/constants.js';
import { ErrorMessage } from '../plugins/auth/enums/enums.js';
import { type Route } from '../plugins/auth/types/types.js';
import { authenticateJWT } from '../plugins/plugins.js';
import {
type ServerApp,
Expand All @@ -51,6 +53,8 @@ class BaseServerApp implements ServerApp {

private app: ReturnType<typeof Fastify>;

private cachedRoutes: Route[] | null = null;

public constructor({ config, logger, database, apis }: Constructor) {
this.config = config;
this.logger = logger;
Expand Down Expand Up @@ -88,7 +92,14 @@ class BaseServerApp implements ServerApp {

this.app.setNotFoundHandler(
async (_request: FastifyRequest, response: FastifyReply) => {
await response.sendFile('index.html', staticPath);
const errorMessage: string = ErrorMessage.URL_NOT_FOUND;
const responseError: ServerCommonErrorResponse = {
errorType: ServerErrorType.COMMON,
message: errorMessage,
};

this.logger.error(errorMessage);
await response.status(HttpCode.NOT_FOUND).send(responseError);
},
);
}
Expand All @@ -105,6 +116,32 @@ class BaseServerApp implements ServerApp {
this.addRoutes(routers);
}

private listAllRoutes(): Route[] {
if (this.cachedRoutes) {
return this.cachedRoutes;
}

const routes: Route[] = [];
const routesString = this.app.printRoutes();
const routesArray = routesString.split('\n');

for (const route of routesArray) {
const routeParts = route.split(' ');
if (routeParts.length >= 2) {
const method = routeParts[0]?.toUpperCase() as HttpMethod;
const path = routeParts[1];
if (!method || !path) {
continue;
}
routes.push({ method, path });
}
}

this.cachedRoutes = routes;

return routes;
}

public async initMiddlewares(): Promise<void> {
await Promise.all(
this.apis.map(async (it) => {
Expand Down Expand Up @@ -136,6 +173,7 @@ class BaseServerApp implements ServerApp {

this.app.register(authenticateJWT, {
routesWhiteList: WHITE_ROUTES,
availableRoutes: this.listAllRoutes(),
});

this.app.register(session, {
Expand Down
Loading