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";
export function ErrorForwarder(
statusCode: number,
message: string,
cause: unknown
cause: unknown,
statusCode: number = 500,
message: string = "Unexpected error"
): never {
if (cause instanceof AppError) {
throw cause;

View File

@ -11,13 +11,16 @@ import { COOKIE_KEYS } from "../../../constants/cookie.keys";
export const authVerification = async (ctx: Context) => {
try {
// Get the auth token from cookies
const cookie = getCookie(ctx);
if (!cookie.auth_token)
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);
return returnWriteResponse(ctx.set, 200, "User authenticated", authService);
} catch (error) {
// If token is invalid or expired, clear the auth cookie and return an error response
clearCookies(ctx.set, [COOKIE_KEYS.AUTH]);
return mainErrorHandler(ctx.set, error);
}

View File

@ -1,7 +1,8 @@
import { AppError } from "../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { jwtDecode } from "../../../helpers/http/jwt/decode";
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 { JWTSessionPayload } from "../auth.types";
@ -18,14 +19,10 @@ export const authVerificationService = async (cookie: string) => {
if (!sessionCheckOnRedis) {
// 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 (
!sessionCheckOnDB ||
!sessionCheckOnDB.isAuthenticated ||
new Date(sessionCheckOnDB.validUntil) < new Date()
) {
if (!sessionCheckOnDB) {
throw new AppError(401, "Session invalid or expired");
} else {
// Store the session in Redis with the remaining time until expiration
@ -38,9 +35,10 @@ export const authVerificationService = async (cookie: string) => {
return sessionCheckOnDB;
}
} else {
// If the session is found in Redis, return it
return jwtSession;
}
} 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();
return dataFromService;
} catch (error) {
ErrorForwarder(402, "Error from 1", error);
ErrorForwarder(error);
}
};

View File

@ -6,6 +6,6 @@ export const debug2Service = async () => {
const dataFromService = await debug3Service();
return dataFromService;
} 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 { ErrorForwarder } from "../../helpers/error/instances/forwarder";
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";
export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
const userSession = await prisma.userSession.findUnique({
where: {
id: identifier,
},
include: {
user: {
omit: {
password: true,
updatedAt: true,
},
include: {
roles: true,
try {
const userSession = await prisma.userSession.findUnique({
where: {
id: identifier,
},
include: {
user: {
omit: {
password: true,
updatedAt: true,
},
include: {
roles: true,
},
},
},
},
omit: {
deletedAt: true,
updatedAt: true,
},
});
omit: {
deletedAt: 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";
export const checkUserSessionInCacheService = async (
userId: 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);
return userSessionInRedis;
// Check if the user session exists in Redis
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
) => {
try {
// Store user session in cache with expiration time
await storeUserSessionToCacheRepo(userSession, timeExpires);
return;
} 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");
}
};