add default value in forwarder error

This commit is contained in:
rafiarrafif
2025-05-27 05:10:27 +07:00
parent a7c984b316
commit 85bc85618b
11 changed files with 81 additions and 48 deletions

View File

@ -1,9 +1,9 @@
import { AppError } from "./app"; import { AppError } from "./app";
export function ErrorForwarder( export function ErrorForwarder(
statusCode: number, cause: unknown,
message: string, statusCode: number = 500,
cause: unknown message: string = "Unexpected error"
): never { ): never {
if (cause instanceof AppError) { if (cause instanceof AppError) {
throw cause; throw cause;

View File

@ -11,13 +11,16 @@ import { COOKIE_KEYS } from "../../../constants/cookie.keys";
export const authVerification = async (ctx: Context) => { export const authVerification = async (ctx: Context) => {
try { try {
// Get the auth token from cookies
const cookie = getCookie(ctx); const cookie = getCookie(ctx);
if (!cookie.auth_token) if (!cookie.auth_token)
return returnErrorResponse(ctx.set, 401, "Auth token not found"); return returnErrorResponse(ctx.set, 401, "Auth token not found");
// Verify the auth token and get the user session
const authService = await authVerificationService(cookie.auth_token); const authService = await authVerificationService(cookie.auth_token);
return returnWriteResponse(ctx.set, 200, "User authenticated", authService); return returnWriteResponse(ctx.set, 200, "User authenticated", authService);
} catch (error) { } catch (error) {
// If token is invalid or expired, clear the auth cookie and return an error response
clearCookies(ctx.set, [COOKIE_KEYS.AUTH]); clearCookies(ctx.set, [COOKIE_KEYS.AUTH]);
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }

View File

@ -1,7 +1,8 @@
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { jwtDecode } from "../../../helpers/http/jwt/decode"; import { jwtDecode } from "../../../helpers/http/jwt/decode";
import { checkUserSessionInCacheService } from "../../userSession/services/checkUserSessionInCache.service"; import { checkUserSessionInCacheService } from "../../userSession/services/checkUserSessionInCache.service";
import { getUserSessionService } from "../../userSession/services/getUserSession.service"; import { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service";
import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service"; import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service";
import { JWTSessionPayload } from "../auth.types"; import { JWTSessionPayload } from "../auth.types";
@ -18,14 +19,10 @@ export const authVerificationService = async (cookie: string) => {
if (!sessionCheckOnRedis) { if (!sessionCheckOnRedis) {
// If not found in Redis, check the database // If not found in Redis, check the database
const sessionCheckOnDB = await getUserSessionService(jwtSession.id); const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id);
// If the session found in the database, store it in Redis. if not, throw an error // If the session found in the database, store it in Redis. if not, throw an error
if ( if (!sessionCheckOnDB) {
!sessionCheckOnDB ||
!sessionCheckOnDB.isAuthenticated ||
new Date(sessionCheckOnDB.validUntil) < new Date()
) {
throw new AppError(401, "Session invalid or expired"); throw new AppError(401, "Session invalid or expired");
} else { } else {
// Store the session in Redis with the remaining time until expiration // Store the session in Redis with the remaining time until expiration
@ -38,9 +35,10 @@ export const authVerificationService = async (cookie: string) => {
return sessionCheckOnDB; return sessionCheckOnDB;
} }
} else { } else {
// If the session is found in Redis, return it
return jwtSession; return jwtSession;
} }
} catch (error) { } catch (error) {
throw new AppError(401, "Token is invalid", error); ErrorForwarder(error, 401, "Token is invalid");
} }
}; };

View File

@ -6,6 +6,6 @@ export const debugService = async () => {
const dataFromService = await debug2Service(); const dataFromService = await debug2Service();
return dataFromService; return dataFromService;
} catch (error) { } catch (error) {
ErrorForwarder(402, "Error from 1", error); ErrorForwarder(error);
} }
}; };

View File

@ -6,6 +6,6 @@ export const debug2Service = async () => {
const dataFromService = await debug3Service(); const dataFromService = await debug3Service();
return dataFromService; return dataFromService;
} catch (error) { } catch (error) {
ErrorForwarder(402, "Error from 2", error); ErrorForwarder(error, 502);
} }
}; };

View File

@ -1,5 +1,9 @@
import { AppError } from "../../helpers/error/instances/app"; import { AppError } from "../../helpers/error/instances/app";
import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
export const debug3Service = async () => { export const debug3Service = async () => {
throw new AppError(402, "Error from 3"); // throw new AppError(402, "Error from 3");
const data = "RAWR";
// return data;
ErrorForwarder(data);
}; };

View File

@ -1,26 +1,33 @@
import { AppError } from "../../../helpers/error/instances/app";
import { prisma } from "../../../utils/databases/prisma/connection"; import { prisma } from "../../../utils/databases/prisma/connection";
export const findUniqueUserSessionInDBRepo = async (identifier: string) => { export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
const userSession = await prisma.userSession.findUnique({ try {
where: { const userSession = await prisma.userSession.findUnique({
id: identifier, where: {
}, id: identifier,
include: { },
user: { include: {
omit: { user: {
password: true, omit: {
updatedAt: true, password: true,
}, updatedAt: true,
include: { },
roles: true, include: {
roles: true,
},
}, },
}, },
}, omit: {
omit: { deletedAt: true,
deletedAt: true, updatedAt: true,
updatedAt: true, },
}, });
});
return userSession; if (!userSession) return false;
return userSession;
} catch (error) {
throw new AppError(500, "Database Error", error);
}
}; };

View File

@ -1,12 +1,19 @@
import { AppError } from "../../../helpers/error/instances/app"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository"; import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository";
export const checkUserSessionInCacheService = async ( export const checkUserSessionInCacheService = async (
userId: string, userId: string,
sessionId: string sessionId: string
) => { ) => {
const redisKeyName = `${process.env.app_name}:users:${userId}:sessions:${sessionId}`; try {
// Construct the Redis key name using the userId and sessionId
const redisKeyName = `${process.env.app_name}:users:${userId}:sessions:${sessionId}`;
const userSessionInRedis = await checkUserSessionInCacheRepo(redisKeyName); // Check if the user session exists in Redis
return userSessionInRedis; const userSessionInRedis = await checkUserSessionInCacheRepo(redisKeyName);
return userSessionInRedis;
} catch (error) {
// Forward the error with a 400 status code and a message
ErrorForwarder(error, 400, "Bad Request");
}
}; };

View File

@ -1,11 +0,0 @@
import { AppError } from "../../../helpers/error/instances/app";
import { findUniqueUserSessionInDBRepo } from "../repositories/findUniqueUserSessionInDB.repository";
export const getUserSessionService = async (identifier: string) => {
try {
const userSession = await findUniqueUserSessionInDBRepo(identifier);
return userSession;
} catch (error) {
throw new AppError(401, "Unable to get user session", error);
}
};

View File

@ -0,0 +1,23 @@
import { AppError } from "../../../helpers/error/instances/app";
import { findUniqueUserSessionInDBRepo } from "../repositories/findUniqueUserSessionInDB.repository";
export const getUserSessionFromDBService = async (identifier: string) => {
try {
// Check is session exists in DB
const userSession = await findUniqueUserSessionInDBRepo(identifier);
// If session not found, return false
if (
!userSession ||
!userSession.isAuthenticated ||
new Date(userSession.validUntil) < new Date()
)
return false;
// If session found, return it
return userSession;
} catch (error) {
// If any DB error occurs, throw an AppError
throw new AppError(401, "Unable to get user session", error);
}
};

View File

@ -7,9 +7,11 @@ export const storeUserSessionToCacheService = async (
timeExpires: number timeExpires: number
) => { ) => {
try { try {
// Store user session in cache with expiration time
await storeUserSessionToCacheRepo(userSession, timeExpires); await storeUserSessionToCacheRepo(userSession, timeExpires);
return; return;
} catch (error) { } catch (error) {
// If any error occurs while storing session in cache, throw an AppError
throw new AppError(401, "Failed to store user session to cache"); throw new AppError(401, "Failed to store user session to cache");
} }
}; };