fix: fix.env.example
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
export const COOKIE_KEYS = {
|
||||
AUTH: "auth_token",
|
||||
CSRF: "csrf_token",
|
||||
};
|
||||
export const COOKIE_KEYS = {
|
||||
AUTH: "auth_token",
|
||||
CSRF: "csrf_token",
|
||||
};
|
||||
|
||||
@ -1,80 +1,80 @@
|
||||
/**
|
||||
* Returns a standardized response for write operations (POST, PUT, DELETE).
|
||||
* Only includes data in the response during development.
|
||||
*
|
||||
* @param set - Function to set HTTP headers.
|
||||
* @param status - HTTP status code of the response.
|
||||
* @param message - A message describing the result.
|
||||
* @param data - Optional data for success responses or error description (only returned in development).
|
||||
*
|
||||
* @returns An object with `status`, `message`, and optionally `data` (in development only).
|
||||
*/
|
||||
export function returnWriteResponse(
|
||||
set: any,
|
||||
status: number,
|
||||
message?: string,
|
||||
data?: any
|
||||
) {
|
||||
set.status = status;
|
||||
|
||||
const response: Record<string, any> = {
|
||||
status,
|
||||
message,
|
||||
};
|
||||
if (process.env.APP_ENV === "development") response.data = data;
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a standardized response for read operations (GET).
|
||||
* Always includes data in the response regardless of the environment.
|
||||
*
|
||||
* @param set - Function to set HTTP headers.
|
||||
* @param status - HTTP status code of the response.
|
||||
* @param message - A message describing the result.
|
||||
* @param data - Data to include in the response.
|
||||
*
|
||||
* @returns An object with `status`, `message`, and `data`.
|
||||
*/
|
||||
export function returnReadResponse(
|
||||
set: any,
|
||||
status: number,
|
||||
message: string,
|
||||
data: any
|
||||
) {
|
||||
set.status = status;
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a standardized error response for handling errors in catch blocks.
|
||||
*
|
||||
* @param set - Function to set HTTP headers.
|
||||
* @param status - HTTP status code of the error response.
|
||||
* @param message - A message describing the error.
|
||||
* @param errorDetails - Optional, detailed information about the error (e.g., stack trace).
|
||||
*
|
||||
* @returns An object with `status`, `message`, and optionally `error_details` (in development only).
|
||||
*/
|
||||
export function returnErrorResponse(
|
||||
set: any,
|
||||
status: number,
|
||||
message: string,
|
||||
errorDetails?: any
|
||||
) {
|
||||
set.status = status;
|
||||
|
||||
const response: Record<string, any> = {
|
||||
status: "error",
|
||||
message,
|
||||
};
|
||||
if (process.env.APP_ENV === "development" && errorDetails)
|
||||
response.error_details = errorDetails;
|
||||
|
||||
return response;
|
||||
}
|
||||
/**
|
||||
* Returns a standardized response for write operations (POST, PUT, DELETE).
|
||||
* Only includes data in the response during development.
|
||||
*
|
||||
* @param set - Function to set HTTP headers.
|
||||
* @param status - HTTP status code of the response.
|
||||
* @param message - A message describing the result.
|
||||
* @param data - Optional data for success responses or error description (only returned in development).
|
||||
*
|
||||
* @returns An object with `status`, `message`, and optionally `data` (in development only).
|
||||
*/
|
||||
export function returnWriteResponse(
|
||||
set: any,
|
||||
status: number,
|
||||
message?: string,
|
||||
data?: any
|
||||
) {
|
||||
set.status = status;
|
||||
|
||||
const response: Record<string, any> = {
|
||||
status,
|
||||
message,
|
||||
};
|
||||
if (process.env.APP_ENV === "development") response.data = data;
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a standardized response for read operations (GET).
|
||||
* Always includes data in the response regardless of the environment.
|
||||
*
|
||||
* @param set - Function to set HTTP headers.
|
||||
* @param status - HTTP status code of the response.
|
||||
* @param message - A message describing the result.
|
||||
* @param data - Data to include in the response.
|
||||
*
|
||||
* @returns An object with `status`, `message`, and `data`.
|
||||
*/
|
||||
export function returnReadResponse(
|
||||
set: any,
|
||||
status: number,
|
||||
message: string,
|
||||
data: any
|
||||
) {
|
||||
set.status = status;
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a standardized error response for handling errors in catch blocks.
|
||||
*
|
||||
* @param set - Function to set HTTP headers.
|
||||
* @param status - HTTP status code of the error response.
|
||||
* @param message - A message describing the error.
|
||||
* @param errorDetails - Optional, detailed information about the error (e.g., stack trace).
|
||||
*
|
||||
* @returns An object with `status`, `message`, and optionally `error_details` (in development only).
|
||||
*/
|
||||
export function returnErrorResponse(
|
||||
set: any,
|
||||
status: number,
|
||||
message: string,
|
||||
errorDetails?: any
|
||||
) {
|
||||
set.status = status;
|
||||
|
||||
const response: Record<string, any> = {
|
||||
status: "error",
|
||||
message,
|
||||
};
|
||||
if (process.env.APP_ENV === "development" && errorDetails)
|
||||
response.error_details = errorDetails;
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@ -1,54 +1,54 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { returnErrorResponse } from "../../callback/httpResponse";
|
||||
import { AppError } from "../instances/app";
|
||||
import { PrismaErrorCodeList } from "../../../utils/databases/prisma/error/codeList";
|
||||
|
||||
export const mainErrorHandler = (set: any, error: unknown) => {
|
||||
if (error instanceof AppError) {
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
error.statusCode,
|
||||
error.message,
|
||||
error.details
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
const errorInfo = PrismaErrorCodeList[error.code];
|
||||
|
||||
if (errorInfo)
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
errorInfo.status,
|
||||
errorInfo.message,
|
||||
error.meta ?? {}
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientUnknownRequestError) {
|
||||
return returnErrorResponse(set, 500, "Unknown database error");
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientRustPanicError) {
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
500,
|
||||
"Database engine crashed unexpectedly"
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||
return returnErrorResponse(set, 503, `Can't reach database server.`, error);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientValidationError) {
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
400,
|
||||
"Invalid input to query",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
|
||||
return returnErrorResponse(set, 500, "Internal server error");
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { returnErrorResponse } from "../../callback/httpResponse";
|
||||
import { AppError } from "../instances/app";
|
||||
import { PrismaErrorCodeList } from "../../../utils/databases/prisma/error/codeList";
|
||||
|
||||
export const mainErrorHandler = (set: any, error: unknown) => {
|
||||
if (error instanceof AppError) {
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
error.statusCode,
|
||||
error.message,
|
||||
error.details
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
const errorInfo = PrismaErrorCodeList[error.code];
|
||||
|
||||
if (errorInfo)
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
errorInfo.status,
|
||||
errorInfo.message,
|
||||
error.meta ?? {}
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientUnknownRequestError) {
|
||||
return returnErrorResponse(set, 500, "Unknown database error");
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientRustPanicError) {
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
500,
|
||||
"Database engine crashed unexpectedly"
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||
return returnErrorResponse(set, 503, `Can't reach database server.`, error);
|
||||
}
|
||||
|
||||
if (error instanceof Prisma.PrismaClientValidationError) {
|
||||
return returnErrorResponse(
|
||||
set,
|
||||
400,
|
||||
"Invalid input to query",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
|
||||
return returnErrorResponse(set, 500, "Internal server error");
|
||||
};
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
export class AppError extends Error {
|
||||
public readonly statusCode: number;
|
||||
public readonly details?: any;
|
||||
|
||||
constructor(statusCode = 400, message: string, details?: any) {
|
||||
super(message);
|
||||
this.name = "AppError";
|
||||
this.statusCode = statusCode;
|
||||
this.details = details;
|
||||
|
||||
Object.setPrototypeOf(this, AppError.prototype);
|
||||
}
|
||||
}
|
||||
export class AppError extends Error {
|
||||
public readonly statusCode: number;
|
||||
public readonly details?: any;
|
||||
|
||||
constructor(statusCode = 400, message: string, details?: any) {
|
||||
super(message);
|
||||
this.name = "AppError";
|
||||
this.statusCode = statusCode;
|
||||
this.details = details;
|
||||
|
||||
Object.setPrototypeOf(this, AppError.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,21 +1,21 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { AppError } from "./app";
|
||||
|
||||
export function ErrorForwarder(
|
||||
cause: unknown,
|
||||
statusCode: number = 500,
|
||||
message: string = "Unexpected error"
|
||||
): never {
|
||||
if (
|
||||
cause instanceof AppError ||
|
||||
cause instanceof Prisma.PrismaClientKnownRequestError ||
|
||||
cause instanceof Prisma.PrismaClientUnknownRequestError ||
|
||||
cause instanceof Prisma.PrismaClientRustPanicError ||
|
||||
cause instanceof Prisma.PrismaClientInitializationError ||
|
||||
cause instanceof Prisma.PrismaClientValidationError
|
||||
) {
|
||||
throw cause;
|
||||
}
|
||||
|
||||
throw new AppError(statusCode, message, cause);
|
||||
}
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { AppError } from "./app";
|
||||
|
||||
export function ErrorForwarder(
|
||||
cause: unknown,
|
||||
statusCode: number = 500,
|
||||
message: string = "Unexpected error"
|
||||
): never {
|
||||
if (
|
||||
cause instanceof AppError ||
|
||||
cause instanceof Prisma.PrismaClientKnownRequestError ||
|
||||
cause instanceof Prisma.PrismaClientUnknownRequestError ||
|
||||
cause instanceof Prisma.PrismaClientRustPanicError ||
|
||||
cause instanceof Prisma.PrismaClientInitializationError ||
|
||||
cause instanceof Prisma.PrismaClientValidationError
|
||||
) {
|
||||
throw cause;
|
||||
}
|
||||
|
||||
throw new AppError(statusCode, message, cause);
|
||||
}
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
export const jwtDecode = (payload: string) => {
|
||||
// return payload;
|
||||
if (!payload) throw "JWT decode payload not found";
|
||||
const JWTKey = process.env.JWT_SECRET!;
|
||||
|
||||
try {
|
||||
const decodedPayload = jwt.verify(payload, JWTKey);
|
||||
return decodedPayload;
|
||||
} catch (error) {
|
||||
throw "JWT expired or not valid";
|
||||
}
|
||||
};
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
export const jwtDecode = (payload: string) => {
|
||||
// return payload;
|
||||
if (!payload) throw "JWT decode payload not found";
|
||||
const JWTKey = process.env.JWT_SECRET!;
|
||||
|
||||
try {
|
||||
const decodedPayload = jwt.verify(payload, JWTKey);
|
||||
return decodedPayload;
|
||||
} catch (error) {
|
||||
throw "JWT expired or not valid";
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,62 +1,62 @@
|
||||
export interface JWTAuthToken {
|
||||
id: string;
|
||||
isAuthenticated: boolean;
|
||||
userId: string;
|
||||
deviceType: string;
|
||||
deviceOs: string;
|
||||
deviceIp: string;
|
||||
isOnline: boolean;
|
||||
lastOnline: Date;
|
||||
validUntil: Date;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
user: User;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
birthDate: null;
|
||||
gender: null;
|
||||
phoneCC: null;
|
||||
phoneNumber: null;
|
||||
bioProfile: null;
|
||||
profilePicture: null;
|
||||
commentPicture: null;
|
||||
preferenceId: null;
|
||||
verifiedAt: null;
|
||||
disabledAt: null;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
primaryColor: string;
|
||||
secondaryColor: string;
|
||||
pictureImage: string;
|
||||
badgeImage: null;
|
||||
isSuperadmin: boolean;
|
||||
canEditMedia: boolean;
|
||||
canManageMedia: boolean;
|
||||
canEditEpisodes: boolean;
|
||||
canManageEpisodes: boolean;
|
||||
canEditComment: boolean;
|
||||
canManageComment: boolean;
|
||||
canEditUser: boolean;
|
||||
canManageUser: boolean;
|
||||
canEditSystem: boolean;
|
||||
canManageSystem: boolean;
|
||||
createdBy: string;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
export interface JWTAuthToken {
|
||||
id: string;
|
||||
isAuthenticated: boolean;
|
||||
userId: string;
|
||||
deviceType: string;
|
||||
deviceOs: string;
|
||||
deviceIp: string;
|
||||
isOnline: boolean;
|
||||
lastOnline: Date;
|
||||
validUntil: Date;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
user: User;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
birthDate: null;
|
||||
gender: null;
|
||||
phoneCC: null;
|
||||
phoneNumber: null;
|
||||
bioProfile: null;
|
||||
profilePicture: null;
|
||||
commentPicture: null;
|
||||
preferenceId: null;
|
||||
verifiedAt: null;
|
||||
disabledAt: null;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
primaryColor: string;
|
||||
secondaryColor: string;
|
||||
pictureImage: string;
|
||||
badgeImage: null;
|
||||
isSuperadmin: boolean;
|
||||
canEditMedia: boolean;
|
||||
canManageMedia: boolean;
|
||||
canEditEpisodes: boolean;
|
||||
canManageEpisodes: boolean;
|
||||
canEditComment: boolean;
|
||||
canManageComment: boolean;
|
||||
canEditUser: boolean;
|
||||
canManageUser: boolean;
|
||||
canEditSystem: boolean;
|
||||
canManageSystem: boolean;
|
||||
createdBy: string;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
export const jwtEncode = (payload: any) => {
|
||||
const tokenLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||
const jwtSecret = process.env.JWT_SECRET!;
|
||||
const jwtToken = jwt.sign(payload, jwtSecret, {
|
||||
expiresIn: tokenLifetime,
|
||||
});
|
||||
|
||||
return jwtToken;
|
||||
};
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
export const jwtEncode = (payload: any) => {
|
||||
const tokenLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||
const jwtSecret = process.env.JWT_SECRET!;
|
||||
const jwtToken = jwt.sign(payload, jwtSecret, {
|
||||
expiresIn: tokenLifetime,
|
||||
});
|
||||
|
||||
return jwtToken;
|
||||
};
|
||||
|
||||
@ -1,33 +1,33 @@
|
||||
import { serialize } from "cookie";
|
||||
|
||||
export const clearCookies = (
|
||||
set: any,
|
||||
cookieKeys: string[],
|
||||
options?: Partial<{
|
||||
httpOnly: boolean;
|
||||
secure: boolean;
|
||||
sameSite: "strict" | "lax" | "none";
|
||||
path: string;
|
||||
}>
|
||||
) => {
|
||||
// Define the default configurations for clearing cookies
|
||||
const defaultOptions = {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "strict" as const,
|
||||
path: "/",
|
||||
...options,
|
||||
};
|
||||
|
||||
// Create an array of cleared cookies with the specified names
|
||||
const clearedCookies = cookieKeys.map((name) => {
|
||||
return serialize(name, "", {
|
||||
...defaultOptions,
|
||||
expires: new Date(0),
|
||||
});
|
||||
});
|
||||
|
||||
// Set the cleared cookies in the response headers
|
||||
set.headers["set-cookie"] = clearedCookies;
|
||||
return clearedCookies;
|
||||
};
|
||||
import { serialize } from "cookie";
|
||||
|
||||
export const clearCookies = (
|
||||
set: any,
|
||||
cookieKeys: string[],
|
||||
options?: Partial<{
|
||||
httpOnly: boolean;
|
||||
secure: boolean;
|
||||
sameSite: "strict" | "lax" | "none";
|
||||
path: string;
|
||||
}>
|
||||
) => {
|
||||
// Define the default configurations for clearing cookies
|
||||
const defaultOptions = {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "strict" as const,
|
||||
path: "/",
|
||||
...options,
|
||||
};
|
||||
|
||||
// Create an array of cleared cookies with the specified names
|
||||
const clearedCookies = cookieKeys.map((name) => {
|
||||
return serialize(name, "", {
|
||||
...defaultOptions,
|
||||
expires: new Date(0),
|
||||
});
|
||||
});
|
||||
|
||||
// Set the cleared cookies in the response headers
|
||||
set.headers["set-cookie"] = clearedCookies;
|
||||
return clearedCookies;
|
||||
};
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
import { parse } from "cookie";
|
||||
import { Context } from "elysia";
|
||||
import { AppError } from "../../../error/instances/app";
|
||||
|
||||
export const getCookie = (ctx: Context) => {
|
||||
try {
|
||||
const cookiePayload = ctx.request.headers.get("Cookie");
|
||||
const cookies = parse(cookiePayload!);
|
||||
return cookies;
|
||||
} catch (error) {
|
||||
throw new AppError(401, "Cookie not found");
|
||||
}
|
||||
};
|
||||
import { parse } from "cookie";
|
||||
import { Context } from "elysia";
|
||||
import { AppError } from "../../../error/instances/app";
|
||||
|
||||
export const getCookie = (ctx: Context) => {
|
||||
try {
|
||||
const cookiePayload = ctx.request.headers.get("Cookie");
|
||||
const cookies = parse(cookiePayload!);
|
||||
return cookies;
|
||||
} catch (error) {
|
||||
throw new AppError(401, "Cookie not found");
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,34 +1,34 @@
|
||||
import { serialize } from "cookie";
|
||||
|
||||
export const setCookie = async (
|
||||
set: any,
|
||||
name: string,
|
||||
payload: string,
|
||||
options?: Partial<{
|
||||
httpOnly: boolean;
|
||||
secure: boolean;
|
||||
sameSite: "strict" | "lax" | "none";
|
||||
maxAge: number;
|
||||
path: string;
|
||||
}>
|
||||
) => {
|
||||
// Define the default configurations for the cookie
|
||||
const cookieLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||
const defaultOptions = {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "strict" as const,
|
||||
maxAge: cookieLifetime,
|
||||
path: "/",
|
||||
};
|
||||
|
||||
// Merge the default options with the provided options
|
||||
const finalOptions = { ...defaultOptions, ...options };
|
||||
|
||||
// Create the serialized cookie string
|
||||
const serializedCookie = serialize(name, payload, finalOptions);
|
||||
|
||||
// Set the cookie in the response headers
|
||||
set.headers["set-cookie"] = serializedCookie;
|
||||
return serializedCookie;
|
||||
};
|
||||
import { serialize } from "cookie";
|
||||
|
||||
export const setCookie = async (
|
||||
set: any,
|
||||
name: string,
|
||||
payload: string,
|
||||
options?: Partial<{
|
||||
httpOnly: boolean;
|
||||
secure: boolean;
|
||||
sameSite: "strict" | "lax" | "none";
|
||||
maxAge: number;
|
||||
path: string;
|
||||
}>
|
||||
) => {
|
||||
// Define the default configurations for the cookie
|
||||
const cookieLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||
const defaultOptions = {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "strict" as const,
|
||||
maxAge: cookieLifetime,
|
||||
path: "/",
|
||||
};
|
||||
|
||||
// Merge the default options with the provided options
|
||||
const finalOptions = { ...defaultOptions, ...options };
|
||||
|
||||
// Create the serialized cookie string
|
||||
const serializedCookie = serialize(name, payload, finalOptions);
|
||||
|
||||
// Set the cookie in the response headers
|
||||
set.headers["set-cookie"] = serializedCookie;
|
||||
return serializedCookie;
|
||||
};
|
||||
|
||||
@ -1,26 +1,26 @@
|
||||
import { Context } from "elysia";
|
||||
import { UAParser } from "ua-parser-js";
|
||||
import { UserHeaderInformation } from "./types";
|
||||
|
||||
export const getUserHeaderInformation = (
|
||||
ctx: Context
|
||||
): UserHeaderInformation => {
|
||||
const headers = ctx.request.headers;
|
||||
const userAgentHeader = headers.get("user-agent") || "desktop";
|
||||
const userAgent = new UAParser(userAgentHeader);
|
||||
|
||||
const userIP =
|
||||
headers.get("cf-connecting-ip") ||
|
||||
headers.get("x-real-ip") ||
|
||||
headers.get("x-forwarded-for")?.split(",")[0] ||
|
||||
"Unknown IP";
|
||||
|
||||
const userHeaderInformation = {
|
||||
ip: userIP,
|
||||
deviceType: userAgent.getDevice().type || "desktop",
|
||||
deviceOS: userAgent.getOS().name + " " + userAgent.getOS().version,
|
||||
browser: userAgent.getBrowser().name + " " + userAgent.getBrowser().version,
|
||||
};
|
||||
|
||||
return userHeaderInformation;
|
||||
};
|
||||
import { Context } from "elysia";
|
||||
import { UAParser } from "ua-parser-js";
|
||||
import { UserHeaderInformation } from "./types";
|
||||
|
||||
export const getUserHeaderInformation = (
|
||||
ctx: Context
|
||||
): UserHeaderInformation => {
|
||||
const headers = ctx.request.headers;
|
||||
const userAgentHeader = headers.get("user-agent") || "desktop";
|
||||
const userAgent = new UAParser(userAgentHeader);
|
||||
|
||||
const userIP =
|
||||
headers.get("cf-connecting-ip") ||
|
||||
headers.get("x-real-ip") ||
|
||||
headers.get("x-forwarded-for")?.split(",")[0] ||
|
||||
"Unknown IP";
|
||||
|
||||
const userHeaderInformation = {
|
||||
ip: userIP,
|
||||
deviceType: userAgent.getDevice().type || "desktop",
|
||||
deviceOS: userAgent.getOS().name + " " + userAgent.getOS().version,
|
||||
browser: userAgent.getBrowser().name + " " + userAgent.getBrowser().version,
|
||||
};
|
||||
|
||||
return userHeaderInformation;
|
||||
};
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
export interface UserHeaderInformation {
|
||||
ip: string;
|
||||
deviceType: string;
|
||||
deviceOS: string;
|
||||
browser: string;
|
||||
}
|
||||
export interface UserHeaderInformation {
|
||||
ip: string;
|
||||
deviceType: string;
|
||||
deviceOS: string;
|
||||
browser: string;
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import bcrypt from "bcrypt";
|
||||
|
||||
export const hashPassword = async (password: string): Promise<string> => {
|
||||
const saltRounds = Number(process.env.SALT_ROUNDS);
|
||||
return await bcrypt.hash(password, saltRounds);
|
||||
};
|
||||
import bcrypt from "bcrypt";
|
||||
|
||||
export const hashPassword = async (password: string): Promise<string> => {
|
||||
const saltRounds = Number(process.env.SALT_ROUNDS);
|
||||
return await bcrypt.hash(password, saltRounds);
|
||||
};
|
||||
|
||||
16
src/index.ts
16
src/index.ts
@ -1,8 +1,8 @@
|
||||
import { Elysia } from "elysia";
|
||||
import { routes } from "./routes";
|
||||
|
||||
const app = new Elysia().use(routes).listen(process.env.PORT || 3000);
|
||||
|
||||
console.log(
|
||||
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
|
||||
);
|
||||
import { Elysia } from "elysia";
|
||||
import { routes } from "./routes";
|
||||
|
||||
const app = new Elysia().use(routes).listen(process.env.PORT || 3000);
|
||||
|
||||
console.log(
|
||||
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
|
||||
);
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../helpers/http/userHeader/cookies/getCookies";
|
||||
import { mainErrorHandler } from "../helpers/error/handler";
|
||||
import { returnErrorResponse } from "../helpers/callback/httpResponse";
|
||||
|
||||
export const authMiddleware = (ctx: Context) => {
|
||||
try {
|
||||
const cookie = getCookie(ctx);
|
||||
if (!cookie.auth_token)
|
||||
return returnErrorResponse(ctx.set, 401, "User Unauthorized");
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../helpers/http/userHeader/cookies/getCookies";
|
||||
import { mainErrorHandler } from "../helpers/error/handler";
|
||||
import { returnErrorResponse } from "../helpers/callback/httpResponse";
|
||||
|
||||
export const authMiddleware = (ctx: Context) => {
|
||||
try {
|
||||
const cookie = getCookie(ctx);
|
||||
if (!cookie.auth_token)
|
||||
return returnErrorResponse(ctx.set, 401, "User Unauthorized");
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { returnErrorResponse } from "../../helpers/callback/httpResponse";
|
||||
import { mainErrorHandler } from "../../helpers/error/handler";
|
||||
|
||||
export const authMiddleware = (ctx: Context) => {
|
||||
try {
|
||||
const cookie = getCookie(ctx);
|
||||
if (!cookie.auth_token)
|
||||
return returnErrorResponse(ctx.set, 401, "User Unauthorized");
|
||||
|
||||
// pass
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { returnErrorResponse } from "../../helpers/callback/httpResponse";
|
||||
import { mainErrorHandler } from "../../helpers/error/handler";
|
||||
|
||||
export const authMiddleware = (ctx: Context) => {
|
||||
try {
|
||||
const cookie = getCookie(ctx);
|
||||
if (!cookie.auth_token)
|
||||
return returnErrorResponse(ctx.set, 401, "User Unauthorized");
|
||||
|
||||
// pass
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { returnErrorResponse } from "../../helpers/callback/httpResponse";
|
||||
|
||||
export const unautenticatedMiddleware = (ctx: Context) => {
|
||||
try {
|
||||
const cookies = getCookie(ctx);
|
||||
if (cookies.auth_token)
|
||||
return returnErrorResponse(ctx.set, 403, "User already aunthenticated");
|
||||
|
||||
// pass
|
||||
} catch (error) {
|
||||
// pass
|
||||
}
|
||||
};
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { returnErrorResponse } from "../../helpers/callback/httpResponse";
|
||||
|
||||
export const unautenticatedMiddleware = (ctx: Context) => {
|
||||
try {
|
||||
const cookies = getCookie(ctx);
|
||||
if (cookies.auth_token)
|
||||
return returnErrorResponse(ctx.set, 403, "User already aunthenticated");
|
||||
|
||||
// pass
|
||||
} catch (error) {
|
||||
// pass
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,65 +1,65 @@
|
||||
export interface LoginWithPasswordRequest {
|
||||
identifier: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface JWTSessionPayload {
|
||||
id: string;
|
||||
isAuthenticated: boolean;
|
||||
userId: string;
|
||||
deviceType: string;
|
||||
deviceOs: string;
|
||||
deviceIp: string;
|
||||
isOnline: boolean;
|
||||
lastOnline: Date;
|
||||
validUntil: Date;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
user: User;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
birthDate: null;
|
||||
gender: null;
|
||||
phoneCC: null;
|
||||
phoneNumber: null;
|
||||
bioProfile: null;
|
||||
profilePicture: null;
|
||||
commentPicture: null;
|
||||
preferenceId: null;
|
||||
verifiedAt: null;
|
||||
disabledAt: null;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
roles: Role[];
|
||||
}
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
primaryColor: string;
|
||||
secondaryColor: string;
|
||||
pictureImage: string;
|
||||
badgeImage: null;
|
||||
isSuperadmin: boolean;
|
||||
canEditMedia: boolean;
|
||||
canManageMedia: boolean;
|
||||
canEditEpisodes: boolean;
|
||||
canManageEpisodes: boolean;
|
||||
canEditComment: boolean;
|
||||
canManageComment: boolean;
|
||||
canEditUser: boolean;
|
||||
canManageUser: boolean;
|
||||
canEditSystem: boolean;
|
||||
canManageSystem: boolean;
|
||||
createdBy: string;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
export interface LoginWithPasswordRequest {
|
||||
identifier: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface JWTSessionPayload {
|
||||
id: string;
|
||||
isAuthenticated: boolean;
|
||||
userId: string;
|
||||
deviceType: string;
|
||||
deviceOs: string;
|
||||
deviceIp: string;
|
||||
isOnline: boolean;
|
||||
lastOnline: Date;
|
||||
validUntil: Date;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
user: User;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
birthDate: null;
|
||||
gender: null;
|
||||
phoneCC: null;
|
||||
phoneNumber: null;
|
||||
bioProfile: null;
|
||||
profilePicture: null;
|
||||
commentPicture: null;
|
||||
preferenceId: null;
|
||||
verifiedAt: null;
|
||||
disabledAt: null;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
roles: Role[];
|
||||
}
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
primaryColor: string;
|
||||
secondaryColor: string;
|
||||
pictureImage: string;
|
||||
badgeImage: null;
|
||||
isSuperadmin: boolean;
|
||||
canEditMedia: boolean;
|
||||
canManageMedia: boolean;
|
||||
canEditEpisodes: boolean;
|
||||
canManageEpisodes: boolean;
|
||||
canEditComment: boolean;
|
||||
canManageComment: boolean;
|
||||
canEditUser: boolean;
|
||||
canManageUser: boolean;
|
||||
canEditSystem: boolean;
|
||||
canManageSystem: boolean;
|
||||
createdBy: string;
|
||||
deletedAt: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
@ -1,27 +1,27 @@
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { authVerificationService } from "../services/authVerification.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies";
|
||||
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);
|
||||
}
|
||||
};
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { authVerificationService } from "../services/authVerification.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies";
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,41 +1,41 @@
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { loginWithPasswordService } from "../services/loginWithPassword.service";
|
||||
import { LoginWithPasswordRequest } from "../auth.types";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
||||
import { setCookie } from "../../../helpers/http/userHeader/cookies/setCookies";
|
||||
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
||||
import { loginWithPasswordSchema } from "../schemas/loginWithPassword";
|
||||
|
||||
export const loginWithPassword = async (
|
||||
ctx: Context & { body: LoginWithPasswordRequest }
|
||||
) => {
|
||||
// Validate the request body against the schema
|
||||
const { error } = loginWithPasswordSchema.validate(ctx.body);
|
||||
if (error || !ctx.body)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
// Extract user header information
|
||||
const userHeaderInfo = getUserHeaderInformation(ctx);
|
||||
|
||||
try {
|
||||
// Call the service to handle login with password
|
||||
const jwtToken = await loginWithPasswordService(ctx.body, userHeaderInfo);
|
||||
|
||||
// Set the authentication cookie with the JWT token
|
||||
setCookie(ctx.set, COOKIE_KEYS.AUTH, jwtToken);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
200,
|
||||
"Authentication Success",
|
||||
jwtToken
|
||||
);
|
||||
} catch (error) {
|
||||
// Handle any errors that occur during the login process
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { loginWithPasswordService } from "../services/loginWithPassword.service";
|
||||
import { LoginWithPasswordRequest } from "../auth.types";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
||||
import { setCookie } from "../../../helpers/http/userHeader/cookies/setCookies";
|
||||
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
||||
import { loginWithPasswordSchema } from "../schemas/loginWithPassword";
|
||||
|
||||
export const loginWithPassword = async (
|
||||
ctx: Context & { body: LoginWithPasswordRequest }
|
||||
) => {
|
||||
// Validate the request body against the schema
|
||||
const { error } = loginWithPasswordSchema.validate(ctx.body);
|
||||
if (error || !ctx.body)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
// Extract user header information
|
||||
const userHeaderInfo = getUserHeaderInformation(ctx);
|
||||
|
||||
try {
|
||||
// Call the service to handle login with password
|
||||
const jwtToken = await loginWithPasswordService(ctx.body, userHeaderInfo);
|
||||
|
||||
// Set the authentication cookie with the JWT token
|
||||
setCookie(ctx.set, COOKIE_KEYS.AUTH, jwtToken);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
200,
|
||||
"Authentication Success",
|
||||
jwtToken
|
||||
);
|
||||
} catch (error) {
|
||||
// Handle any errors that occur during the login process
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import Elysia from "elysia";
|
||||
import { loginWithPassword } from "./controller/loginWithPassword.controller";
|
||||
import { authMiddleware } from "../../middleware/auth.middleware";
|
||||
import { authVerification } from "./controller/authVerification.controller";
|
||||
|
||||
export const authModule = new Elysia({ prefix: "/auth" })
|
||||
.post("/legacy", loginWithPassword)
|
||||
.post("/verification", authVerification, {
|
||||
beforeHandle: authMiddleware,
|
||||
});
|
||||
import Elysia from "elysia";
|
||||
import { loginWithPassword } from "./controller/loginWithPassword.controller";
|
||||
import { authMiddleware } from "../../middleware/auth.middleware";
|
||||
import { authVerification } from "./controller/authVerification.controller";
|
||||
|
||||
export const authModule = new Elysia({ prefix: "/auth" })
|
||||
.post("/legacy", loginWithPassword)
|
||||
.post("/verification", authVerification, {
|
||||
beforeHandle: authMiddleware,
|
||||
});
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import Joi from "joi";
|
||||
|
||||
export const loginWithPasswordSchema = Joi.object({
|
||||
identifier: Joi.string().required(),
|
||||
password: Joi.string().required(),
|
||||
});
|
||||
import Joi from "joi";
|
||||
|
||||
export const loginWithPasswordSchema = Joi.object({
|
||||
identifier: Joi.string().required(),
|
||||
password: Joi.string().required(),
|
||||
});
|
||||
|
||||
@ -1,44 +1,44 @@
|
||||
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 { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service";
|
||||
import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service";
|
||||
import { JWTSessionPayload } from "../auth.types";
|
||||
|
||||
export const authVerificationService = async (cookie: string) => {
|
||||
try {
|
||||
// Decode the JWT token to get the session payload
|
||||
const jwtSession = jwtDecode(cookie) as JWTSessionPayload;
|
||||
|
||||
// Check if the session exists in Redis
|
||||
const sessionCheckOnRedis = await checkUserSessionInCacheService(
|
||||
jwtSession.userId,
|
||||
jwtSession.id
|
||||
);
|
||||
|
||||
if (!sessionCheckOnRedis) {
|
||||
// If not found in Redis, check the database
|
||||
const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id);
|
||||
|
||||
// If the session found in the database, store it in Redis. if not, throw an error
|
||||
if (!sessionCheckOnDB) {
|
||||
throw new AppError(401, "Session invalid or expired");
|
||||
} else {
|
||||
// Store the session in Redis with the remaining time until expiration
|
||||
const timeExpires = Math.floor(
|
||||
(new Date(sessionCheckOnDB.validUntil).getTime() -
|
||||
new Date().getTime()) /
|
||||
1000
|
||||
);
|
||||
await storeUserSessionToCacheService(sessionCheckOnDB, timeExpires);
|
||||
return sessionCheckOnDB;
|
||||
}
|
||||
} else {
|
||||
// If the session is found in Redis, return it
|
||||
return jwtSession;
|
||||
}
|
||||
} catch (error) {
|
||||
ErrorForwarder(error, 401, "Token is invalid");
|
||||
}
|
||||
};
|
||||
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 { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service";
|
||||
import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service";
|
||||
import { JWTSessionPayload } from "../auth.types";
|
||||
|
||||
export const authVerificationService = async (cookie: string) => {
|
||||
try {
|
||||
// Decode the JWT token to get the session payload
|
||||
const jwtSession = jwtDecode(cookie) as JWTSessionPayload;
|
||||
|
||||
// Check if the session exists in Redis
|
||||
const sessionCheckOnRedis = await checkUserSessionInCacheService(
|
||||
jwtSession.userId,
|
||||
jwtSession.id
|
||||
);
|
||||
|
||||
if (!sessionCheckOnRedis) {
|
||||
// If not found in Redis, check the database
|
||||
const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id);
|
||||
|
||||
// If the session found in the database, store it in Redis. if not, throw an error
|
||||
if (!sessionCheckOnDB) {
|
||||
throw new AppError(401, "Session invalid or expired");
|
||||
} else {
|
||||
// Store the session in Redis with the remaining time until expiration
|
||||
const timeExpires = Math.floor(
|
||||
(new Date(sessionCheckOnDB.validUntil).getTime() -
|
||||
new Date().getTime()) /
|
||||
1000
|
||||
);
|
||||
await storeUserSessionToCacheService(sessionCheckOnDB, timeExpires);
|
||||
return sessionCheckOnDB;
|
||||
}
|
||||
} else {
|
||||
// If the session is found in Redis, return it
|
||||
return jwtSession;
|
||||
}
|
||||
} catch (error) {
|
||||
ErrorForwarder(error, 401, "Token is invalid");
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,37 +1,37 @@
|
||||
import bcrypt from "bcrypt";
|
||||
import { findUserByEmailOrUsernameService } from "../../user/services/findUserByEmailOrUsername.service";
|
||||
import { LoginWithPasswordRequest } from "../auth.types";
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
||||
import { jwtEncode } from "../../../helpers/http/jwt/encode";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
export const loginWithPasswordService = async (
|
||||
request: LoginWithPasswordRequest,
|
||||
userHeaderInfo: UserHeaderInformation
|
||||
) => {
|
||||
try {
|
||||
// search for user data using an identifier (username or email)
|
||||
const userData = await findUserByEmailOrUsernameService(request.identifier);
|
||||
|
||||
// if user data is not found, throw an error
|
||||
if (!userData) throw new AppError(404, "User not found");
|
||||
|
||||
// validate the password in the request with the existing one
|
||||
if (!(await bcrypt.compare(request.password, userData.password)))
|
||||
throw new AppError(401, "Password incorrect");
|
||||
|
||||
// create new user session
|
||||
const userSession = await createUserSessionService({
|
||||
userId: userData.id,
|
||||
userHeaderInformation: userHeaderInfo,
|
||||
});
|
||||
|
||||
// create JWT token that contain user session
|
||||
const jwtToken = jwtEncode(userSession);
|
||||
return jwtToken;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
import bcrypt from "bcrypt";
|
||||
import { findUserByEmailOrUsernameService } from "../../user/services/findUserByEmailOrUsername.service";
|
||||
import { LoginWithPasswordRequest } from "../auth.types";
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
||||
import { jwtEncode } from "../../../helpers/http/jwt/encode";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
export const loginWithPasswordService = async (
|
||||
request: LoginWithPasswordRequest,
|
||||
userHeaderInfo: UserHeaderInformation
|
||||
) => {
|
||||
try {
|
||||
// search for user data using an identifier (username or email)
|
||||
const userData = await findUserByEmailOrUsernameService(request.identifier);
|
||||
|
||||
// if user data is not found, throw an error
|
||||
if (!userData) throw new AppError(404, "User not found");
|
||||
|
||||
// validate the password in the request with the existing one
|
||||
if (!(await bcrypt.compare(request.password, userData.password)))
|
||||
throw new AppError(401, "Password incorrect");
|
||||
|
||||
// create new user session
|
||||
const userSession = await createUserSessionService({
|
||||
userId: userData.id,
|
||||
userHeaderInformation: userHeaderInfo,
|
||||
});
|
||||
|
||||
// create JWT token that contain user session
|
||||
const jwtToken = jwtEncode(userSession);
|
||||
return jwtToken;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import { Context } from "elysia";
|
||||
import { mainErrorHandler } from "../../helpers/error/handler";
|
||||
import { debugService } from "./debug.service";
|
||||
import { returnWriteResponse } from "../../helpers/callback/httpResponse";
|
||||
|
||||
export const debugController = async (ctx: Context) => {
|
||||
try {
|
||||
const dataFromService = await debugService();
|
||||
return returnWriteResponse(ctx.set, 200, "Message Sent", dataFromService);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
// buat debug untuk date to number (second)
|
||||
import { Context } from "elysia";
|
||||
import { mainErrorHandler } from "../../helpers/error/handler";
|
||||
import { debugService } from "./debug.service";
|
||||
import { returnWriteResponse } from "../../helpers/callback/httpResponse";
|
||||
|
||||
export const debugController = async (ctx: Context) => {
|
||||
try {
|
||||
const dataFromService = await debugService();
|
||||
return returnWriteResponse(ctx.set, 200, "Message Sent", dataFromService);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
// buat debug untuk date to number (second)
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
|
||||
import { debug2Service } from "./debug2.service";
|
||||
|
||||
export const debugService = async () => {
|
||||
try {
|
||||
const dataFromService = await debug2Service();
|
||||
return dataFromService;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
|
||||
import { debug2Service } from "./debug2.service";
|
||||
|
||||
export const debugService = async () => {
|
||||
try {
|
||||
const dataFromService = await debug2Service();
|
||||
return dataFromService;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
|
||||
import { debug3Service } from "./debug3.service";
|
||||
|
||||
export const debug2Service = async () => {
|
||||
try {
|
||||
const dataFromService = await debug3Service();
|
||||
return dataFromService;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error, 502);
|
||||
}
|
||||
};
|
||||
import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
|
||||
import { debug3Service } from "./debug3.service";
|
||||
|
||||
export const debug2Service = async () => {
|
||||
try {
|
||||
const dataFromService = await debug3Service();
|
||||
return dataFromService;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error, 502);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,9 +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");
|
||||
const data = "RAWR";
|
||||
// return data;
|
||||
ErrorForwarder(data);
|
||||
};
|
||||
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");
|
||||
const data = "RAWR";
|
||||
// return data;
|
||||
ErrorForwarder(data);
|
||||
};
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import Elysia from "elysia";
|
||||
import { debugController } from "./debug.controller";
|
||||
|
||||
export const debugModule = new Elysia({ prefix: "/debug" }).get(
|
||||
"/",
|
||||
debugController
|
||||
);
|
||||
import Elysia from "elysia";
|
||||
import { debugController } from "./debug.controller";
|
||||
|
||||
export const debugModule = new Elysia({ prefix: "/debug" }).get(
|
||||
"/",
|
||||
debugController
|
||||
);
|
||||
|
||||
@ -1,50 +1,50 @@
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Context } from "elysia";
|
||||
import { createUserService } from "../services/createUser.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { createUserSchema } from "../schemas/createUser.schema";
|
||||
|
||||
/**
|
||||
* @function createUser
|
||||
* @description Creates a new user in the database.
|
||||
*
|
||||
* @param {Context & { body: Prisma.UserCreateInput }} ctx - The context object containing the request body.
|
||||
* @param {Prisma.UserCreateInput} ctx.body - The user data to be created.
|
||||
*
|
||||
* @returns {Promise<Object>} A response object indicating success or failure.
|
||||
* @throws {Object} An error response object if validation fails or an error occurs during user creation.
|
||||
*
|
||||
* @example
|
||||
* Request route: POST /users
|
||||
* Request body:
|
||||
* {
|
||||
* "username": "john_doe",
|
||||
* "email": "john@example.com",
|
||||
* "password": "password123"
|
||||
* }
|
||||
*/
|
||||
export const createUser = async (
|
||||
ctx: Context & { body: Prisma.UserCreateInput }
|
||||
) => {
|
||||
// Validate the user input using a validation schema
|
||||
const { error } = createUserSchema.validate(ctx.body);
|
||||
if (error)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
// Create the user in the database using the service
|
||||
try {
|
||||
const newUser = await createUserService(ctx.body);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User created successfully",
|
||||
newUser
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Context } from "elysia";
|
||||
import { createUserService } from "../services/createUser.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { createUserSchema } from "../schemas/createUser.schema";
|
||||
|
||||
/**
|
||||
* @function createUser
|
||||
* @description Creates a new user in the database.
|
||||
*
|
||||
* @param {Context & { body: Prisma.UserCreateInput }} ctx - The context object containing the request body.
|
||||
* @param {Prisma.UserCreateInput} ctx.body - The user data to be created.
|
||||
*
|
||||
* @returns {Promise<Object>} A response object indicating success or failure.
|
||||
* @throws {Object} An error response object if validation fails or an error occurs during user creation.
|
||||
*
|
||||
* @example
|
||||
* Request route: POST /users
|
||||
* Request body:
|
||||
* {
|
||||
* "username": "john_doe",
|
||||
* "email": "john@example.com",
|
||||
* "password": "password123"
|
||||
* }
|
||||
*/
|
||||
export const createUser = async (
|
||||
ctx: Context & { body: Prisma.UserCreateInput }
|
||||
) => {
|
||||
// Validate the user input using a validation schema
|
||||
const { error } = createUserSchema.validate(ctx.body);
|
||||
if (error)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
// Create the user in the database using the service
|
||||
try {
|
||||
const newUser = await createUserService(ctx.body);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User created successfully",
|
||||
newUser
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,21 +1,21 @@
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnReadResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { getAllUsersService } from "../services/getAllUser.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
|
||||
export const getAllUser = async (ctx: Context) => {
|
||||
try {
|
||||
const allUser = await getAllUsersService();
|
||||
return returnReadResponse(
|
||||
ctx.set,
|
||||
200,
|
||||
"All user ranks successfully",
|
||||
allUser
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnReadResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { getAllUsersService } from "../services/getAllUser.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
|
||||
export const getAllUser = async (ctx: Context) => {
|
||||
try {
|
||||
const allUser = await getAllUsersService();
|
||||
return returnReadResponse(
|
||||
ctx.set,
|
||||
200,
|
||||
"All user ranks successfully",
|
||||
allUser
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import Elysia from "elysia";
|
||||
import { getAllUser } from "./controller/getAllUser.controller";
|
||||
import { createUser } from "./controller/createUser.controller";
|
||||
|
||||
export const userModule = new Elysia({ prefix: "/users" })
|
||||
.get("/", getAllUser)
|
||||
.post("/", createUser);
|
||||
import Elysia from "elysia";
|
||||
import { getAllUser } from "./controller/getAllUser.controller";
|
||||
import { createUser } from "./controller/createUser.controller";
|
||||
|
||||
export const userModule = new Elysia({ prefix: "/users" })
|
||||
.get("/", getAllUser)
|
||||
.post("/", createUser);
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userModel } from "../user.model";
|
||||
|
||||
export const createUserRepo = async (data: Prisma.UserCreateInput) => {
|
||||
try {
|
||||
const userData = await userModel.create({
|
||||
data,
|
||||
omit: {
|
||||
password: true,
|
||||
},
|
||||
});
|
||||
|
||||
return userData;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userModel } from "../user.model";
|
||||
|
||||
export const createUserRepo = async (data: Prisma.UserCreateInput) => {
|
||||
try {
|
||||
const userData = await userModel.create({
|
||||
data,
|
||||
omit: {
|
||||
password: true,
|
||||
},
|
||||
});
|
||||
|
||||
return userData;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,39 +1,39 @@
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { userModel } from "../user.model";
|
||||
|
||||
export const findUserByEmailOrUsernameRepo = async (identifier: string) => {
|
||||
try {
|
||||
const userData =
|
||||
(await userModel.findUnique({
|
||||
where: { email: identifier },
|
||||
include: {
|
||||
roles: {
|
||||
omit: {
|
||||
createdBy: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
deletedAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})) ||
|
||||
(await userModel.findUnique({
|
||||
where: { username: identifier },
|
||||
include: {
|
||||
roles: {
|
||||
omit: {
|
||||
createdBy: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
deletedAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
if (!userData) return false;
|
||||
return userData;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { userModel } from "../user.model";
|
||||
|
||||
export const findUserByEmailOrUsernameRepo = async (identifier: string) => {
|
||||
try {
|
||||
const userData =
|
||||
(await userModel.findUnique({
|
||||
where: { email: identifier },
|
||||
include: {
|
||||
roles: {
|
||||
omit: {
|
||||
createdBy: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
deletedAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})) ||
|
||||
(await userModel.findUnique({
|
||||
where: { username: identifier },
|
||||
include: {
|
||||
roles: {
|
||||
omit: {
|
||||
createdBy: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
deletedAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
if (!userData) return false;
|
||||
return userData;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import { userModel } from "../user.model";
|
||||
|
||||
export const getAllUserRepo = async () => {
|
||||
try {
|
||||
const data = await userModel.findMany({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { userModel } from "../user.model";
|
||||
|
||||
export const getAllUserRepo = async () => {
|
||||
try {
|
||||
const data = await userModel.findMany({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import Joi from "joi";
|
||||
|
||||
export const createUserSchema = Joi.object({
|
||||
name: Joi.string().min(4).max(255).required(),
|
||||
username: Joi.string().min(4).max(255).required(),
|
||||
email: Joi.string().email().required(),
|
||||
password: Joi.string().min(8).max(255).required(),
|
||||
birthdate: Joi.date(),
|
||||
gender: Joi.string().valid("male", "female"),
|
||||
phoneCC: Joi.string().min(2).max(2),
|
||||
phoneNumber: Joi.string().min(7).max(15),
|
||||
bioProfile: Joi.string().max(300),
|
||||
profilePicture: Joi.string().uri(),
|
||||
commentPicture: Joi.string().uri(),
|
||||
});
|
||||
import Joi from "joi";
|
||||
|
||||
export const createUserSchema = Joi.object({
|
||||
name: Joi.string().min(4).max(255).required(),
|
||||
username: Joi.string().min(4).max(255).required(),
|
||||
email: Joi.string().email().required(),
|
||||
password: Joi.string().min(8).max(255).required(),
|
||||
birthdate: Joi.date(),
|
||||
gender: Joi.string().valid("male", "female"),
|
||||
phoneCC: Joi.string().min(2).max(2),
|
||||
phoneNumber: Joi.string().min(7).max(15),
|
||||
bioProfile: Joi.string().max(300),
|
||||
profilePicture: Joi.string().uri(),
|
||||
commentPicture: Joi.string().uri(),
|
||||
});
|
||||
|
||||
@ -1,18 +1,18 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { hashPassword } from "../../../helpers/security/password/hash";
|
||||
import { createUserRepo } from "../repositories/createUser.repository";
|
||||
|
||||
export const createUserService = async (userData: Prisma.UserCreateInput) => {
|
||||
const { password, ...rest } = userData; // Destructure the password and the rest of the user data
|
||||
const hashedPassword = await hashPassword(password); // Hash the password before saving to the database
|
||||
|
||||
try {
|
||||
const newUser = await createUserRepo({
|
||||
...rest,
|
||||
password: hashedPassword,
|
||||
});
|
||||
return newUser;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { hashPassword } from "../../../helpers/security/password/hash";
|
||||
import { createUserRepo } from "../repositories/createUser.repository";
|
||||
|
||||
export const createUserService = async (userData: Prisma.UserCreateInput) => {
|
||||
const { password, ...rest } = userData; // Destructure the password and the rest of the user data
|
||||
const hashedPassword = await hashPassword(password); // Hash the password before saving to the database
|
||||
|
||||
try {
|
||||
const newUser = await createUserRepo({
|
||||
...rest,
|
||||
password: hashedPassword,
|
||||
});
|
||||
return newUser;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { findUserByEmailOrUsernameRepo } from "../repositories/findUserByEmailOrUsername.repository";
|
||||
|
||||
export const findUserByEmailOrUsernameService = async (identifier: string) => {
|
||||
try {
|
||||
const userData = await findUserByEmailOrUsernameRepo(identifier);
|
||||
return userData;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { findUserByEmailOrUsernameRepo } from "../repositories/findUserByEmailOrUsername.repository";
|
||||
|
||||
export const findUserByEmailOrUsernameService = async (identifier: string) => {
|
||||
try {
|
||||
const userData = await findUserByEmailOrUsernameRepo(identifier);
|
||||
return userData;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import { getAllUserRepo } from "../repositories/getAllUser.repository";
|
||||
|
||||
export const getAllUsersService = async () => {
|
||||
try {
|
||||
const allUser = await getAllUserRepo();
|
||||
return allUser;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { getAllUserRepo } from "../repositories/getAllUser.repository";
|
||||
|
||||
export const getAllUsersService = async () => {
|
||||
try {
|
||||
const allUser = await getAllUserRepo();
|
||||
return allUser;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userModel = prisma.user;
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userModel = prisma.user;
|
||||
|
||||
@ -1,67 +1,67 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Context } from "elysia";
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { createUserRoleService } from "../services/createUserRole.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { createUserRoleSchema } from "../schemas/createUserRole.schema";
|
||||
|
||||
/**
|
||||
* @function createUserRole
|
||||
* @description Creates a new user role in the database.
|
||||
*
|
||||
* @param {Context & { body: UserRole }} ctx - The context object containing the request body.
|
||||
* @param {UserRole} ctx.body - The user role data to be created.
|
||||
*
|
||||
* @returns {Promise<Object>} A response object indicating success or failure.
|
||||
* @throws {Object} An error response object if validation fails or an error occurs during role creation.
|
||||
*
|
||||
* @example
|
||||
* Request route: POST /roles
|
||||
* Request body:
|
||||
* {
|
||||
* "userID": "e31668e6-c261-4a7e-9469-ffad734cf2dd",
|
||||
* "name": "Admin",
|
||||
* "primaryColor": "#D9D9D9",
|
||||
* "secondaryColor": "#FFFFFF",
|
||||
* "pictureImage": "https://example.com/picture.jpg",
|
||||
* "badgeImage": "https://example.com/badge.jpg",
|
||||
* "isSuperadmin": false,
|
||||
* "canEditMedia": false,
|
||||
* "canManageMedia": false,
|
||||
* "canEditEpisodes": false,
|
||||
* "canManageEpisodes": false,
|
||||
* "canEditComment": false,
|
||||
* "canManageComment": false,
|
||||
* "canEditUser": false,
|
||||
* "canManageUser": false,
|
||||
* "canEditSystem": false,
|
||||
* "canManageSystem": false
|
||||
* }
|
||||
*/
|
||||
export const createUserRole = async (
|
||||
ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput }
|
||||
) => {
|
||||
const { error } = createUserRoleSchema.validate(ctx.body);
|
||||
if (error)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
const formData: Prisma.UserRoleUncheckedCreateInput = {
|
||||
...ctx.body,
|
||||
createdBy: "daw",
|
||||
};
|
||||
|
||||
try {
|
||||
const newUserRole = await createUserRoleService(formData);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User role created successfully",
|
||||
newUserRole
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Context } from "elysia";
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { createUserRoleService } from "../services/createUserRole.service";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { createUserRoleSchema } from "../schemas/createUserRole.schema";
|
||||
|
||||
/**
|
||||
* @function createUserRole
|
||||
* @description Creates a new user role in the database.
|
||||
*
|
||||
* @param {Context & { body: UserRole }} ctx - The context object containing the request body.
|
||||
* @param {UserRole} ctx.body - The user role data to be created.
|
||||
*
|
||||
* @returns {Promise<Object>} A response object indicating success or failure.
|
||||
* @throws {Object} An error response object if validation fails or an error occurs during role creation.
|
||||
*
|
||||
* @example
|
||||
* Request route: POST /roles
|
||||
* Request body:
|
||||
* {
|
||||
* "userID": "e31668e6-c261-4a7e-9469-ffad734cf2dd",
|
||||
* "name": "Admin",
|
||||
* "primaryColor": "#D9D9D9",
|
||||
* "secondaryColor": "#FFFFFF",
|
||||
* "pictureImage": "https://example.com/picture.jpg",
|
||||
* "badgeImage": "https://example.com/badge.jpg",
|
||||
* "isSuperadmin": false,
|
||||
* "canEditMedia": false,
|
||||
* "canManageMedia": false,
|
||||
* "canEditEpisodes": false,
|
||||
* "canManageEpisodes": false,
|
||||
* "canEditComment": false,
|
||||
* "canManageComment": false,
|
||||
* "canEditUser": false,
|
||||
* "canManageUser": false,
|
||||
* "canEditSystem": false,
|
||||
* "canManageSystem": false
|
||||
* }
|
||||
*/
|
||||
export const createUserRole = async (
|
||||
ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput }
|
||||
) => {
|
||||
const { error } = createUserRoleSchema.validate(ctx.body);
|
||||
if (error)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
const formData: Prisma.UserRoleUncheckedCreateInput = {
|
||||
...ctx.body,
|
||||
createdBy: "daw",
|
||||
};
|
||||
|
||||
try {
|
||||
const newUserRole = await createUserRoleService(formData);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User role created successfully",
|
||||
newUserRole
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
import Elysia from "elysia";
|
||||
import { createUserRole } from "./controller/createUserRole.controller";
|
||||
import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware";
|
||||
|
||||
export const userRoleModule = new Elysia({ prefix: "/roles" })
|
||||
.get("/", () => "Hello User Role Module", {
|
||||
beforeHandle: unautenticatedMiddleware,
|
||||
})
|
||||
.post("/", createUserRole);
|
||||
import Elysia from "elysia";
|
||||
import { createUserRole } from "./controller/createUserRole.controller";
|
||||
import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware";
|
||||
|
||||
export const userRoleModule = new Elysia({ prefix: "/roles" })
|
||||
.get("/", () => "Hello User Role Module", {
|
||||
beforeHandle: unautenticatedMiddleware,
|
||||
})
|
||||
.post("/", createUserRole);
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userRoleModel } from "../userRole.model";
|
||||
|
||||
export const createUserRoleRepo = async (
|
||||
data: Prisma.UserRoleUncheckedCreateInput
|
||||
) => {
|
||||
try {
|
||||
const newUserRole = await userRoleModel.create({
|
||||
data,
|
||||
});
|
||||
return newUserRole;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userRoleModel } from "../userRole.model";
|
||||
|
||||
export const createUserRoleRepo = async (
|
||||
data: Prisma.UserRoleUncheckedCreateInput
|
||||
) => {
|
||||
try {
|
||||
const newUserRole = await userRoleModel.create({
|
||||
data,
|
||||
});
|
||||
return newUserRole;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,28 +1,28 @@
|
||||
import Joi from "joi";
|
||||
|
||||
export const createUserRoleSchema = Joi.object({
|
||||
name: Joi.string().min(4).max(255).required(),
|
||||
primaryColor: Joi.string()
|
||||
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
||||
.optional(),
|
||||
secondaryColor: Joi.string()
|
||||
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
||||
.optional(),
|
||||
pictureImage: Joi.string()
|
||||
.uri({ scheme: ["http", "https"] })
|
||||
.optional(),
|
||||
badgeImage: Joi.string()
|
||||
.uri({ scheme: ["http", "https"] })
|
||||
.optional(),
|
||||
isSuperadmin: Joi.boolean().required(),
|
||||
canEditMedia: Joi.boolean().required(),
|
||||
canManageMedia: Joi.boolean().required(),
|
||||
canEditEpisodes: Joi.boolean().required(),
|
||||
canManageEpisodes: Joi.boolean().required(),
|
||||
canEditComment: Joi.boolean().required(),
|
||||
canManageComment: Joi.boolean().required(),
|
||||
canEditUser: Joi.boolean().required(),
|
||||
canManageUser: Joi.boolean().required(),
|
||||
canEditSystem: Joi.boolean().required(),
|
||||
canManageSystem: Joi.boolean().required(),
|
||||
});
|
||||
import Joi from "joi";
|
||||
|
||||
export const createUserRoleSchema = Joi.object({
|
||||
name: Joi.string().min(4).max(255).required(),
|
||||
primaryColor: Joi.string()
|
||||
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
||||
.optional(),
|
||||
secondaryColor: Joi.string()
|
||||
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
||||
.optional(),
|
||||
pictureImage: Joi.string()
|
||||
.uri({ scheme: ["http", "https"] })
|
||||
.optional(),
|
||||
badgeImage: Joi.string()
|
||||
.uri({ scheme: ["http", "https"] })
|
||||
.optional(),
|
||||
isSuperadmin: Joi.boolean().required(),
|
||||
canEditMedia: Joi.boolean().required(),
|
||||
canManageMedia: Joi.boolean().required(),
|
||||
canEditEpisodes: Joi.boolean().required(),
|
||||
canManageEpisodes: Joi.boolean().required(),
|
||||
canEditComment: Joi.boolean().required(),
|
||||
canManageComment: Joi.boolean().required(),
|
||||
canEditUser: Joi.boolean().required(),
|
||||
canManageUser: Joi.boolean().required(),
|
||||
canEditSystem: Joi.boolean().required(),
|
||||
canManageSystem: Joi.boolean().required(),
|
||||
});
|
||||
|
||||
@ -1,28 +1,28 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { createUserRoleRepo } from "../repositories/createUserRole.repository";
|
||||
|
||||
export const createUserRoleService = async (
|
||||
userRoleData: Prisma.UserRoleUncheckedCreateInput
|
||||
) => {
|
||||
try {
|
||||
const dataPayload = {
|
||||
...userRoleData,
|
||||
isSuperadmin: Boolean(userRoleData.isSuperadmin),
|
||||
canEditMedia: Boolean(userRoleData.canEditMedia),
|
||||
canManageMedia: Boolean(userRoleData.canManageMedia),
|
||||
canEditEpisodes: Boolean(userRoleData.canEditEpisodes),
|
||||
canManageEpisodes: Boolean(userRoleData.canManageEpisodes),
|
||||
canEditComment: Boolean(userRoleData.canEditComment),
|
||||
canManageComment: Boolean(userRoleData.canManageComment),
|
||||
canEditUser: Boolean(userRoleData.canEditUser),
|
||||
canManageUser: Boolean(userRoleData.canManageUser),
|
||||
canEditSystem: Boolean(userRoleData.canEditSystem),
|
||||
canManageSystem: Boolean(userRoleData.canManageSystem),
|
||||
deletedAt: null,
|
||||
};
|
||||
const newUserRole = await createUserRoleRepo(dataPayload);
|
||||
return newUserRole;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { createUserRoleRepo } from "../repositories/createUserRole.repository";
|
||||
|
||||
export const createUserRoleService = async (
|
||||
userRoleData: Prisma.UserRoleUncheckedCreateInput
|
||||
) => {
|
||||
try {
|
||||
const dataPayload = {
|
||||
...userRoleData,
|
||||
isSuperadmin: Boolean(userRoleData.isSuperadmin),
|
||||
canEditMedia: Boolean(userRoleData.canEditMedia),
|
||||
canManageMedia: Boolean(userRoleData.canManageMedia),
|
||||
canEditEpisodes: Boolean(userRoleData.canEditEpisodes),
|
||||
canManageEpisodes: Boolean(userRoleData.canManageEpisodes),
|
||||
canEditComment: Boolean(userRoleData.canEditComment),
|
||||
canManageComment: Boolean(userRoleData.canManageComment),
|
||||
canEditUser: Boolean(userRoleData.canEditUser),
|
||||
canManageUser: Boolean(userRoleData.canManageUser),
|
||||
canEditSystem: Boolean(userRoleData.canEditSystem),
|
||||
canManageSystem: Boolean(userRoleData.canManageSystem),
|
||||
deletedAt: null,
|
||||
};
|
||||
const newUserRole = await createUserRoleRepo(dataPayload);
|
||||
return newUserRole;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userRoleModel = prisma.userRole;
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userRoleModel = prisma.userRole;
|
||||
|
||||
@ -1,35 +1,35 @@
|
||||
import { Context } from "elysia";
|
||||
import { createUserSessionService } from "../services/createUserSession.service";
|
||||
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
|
||||
export const createUserSessionRole = async (
|
||||
ctx: Context & { body: { userId?: string } }
|
||||
) => {
|
||||
// Validate request body
|
||||
if (!ctx.body?.userId) {
|
||||
return returnErrorResponse(ctx.set, 400, "User ID is required");
|
||||
}
|
||||
|
||||
// Get user device and browser information
|
||||
const userHeaderData = getUserHeaderInformation(ctx);
|
||||
|
||||
try {
|
||||
const newUserSession = await createUserSessionService({
|
||||
userId: ctx.body.userId,
|
||||
userHeaderInformation: userHeaderData,
|
||||
});
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User session created",
|
||||
newUserSession
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
import { Context } from "elysia";
|
||||
import { createUserSessionService } from "../services/createUserSession.service";
|
||||
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
|
||||
export const createUserSessionRole = async (
|
||||
ctx: Context & { body: { userId?: string } }
|
||||
) => {
|
||||
// Validate request body
|
||||
if (!ctx.body?.userId) {
|
||||
return returnErrorResponse(ctx.set, 400, "User ID is required");
|
||||
}
|
||||
|
||||
// Get user device and browser information
|
||||
const userHeaderData = getUserHeaderInformation(ctx);
|
||||
|
||||
try {
|
||||
const newUserSession = await createUserSessionService({
|
||||
userId: ctx.body.userId,
|
||||
userHeaderInformation: userHeaderData,
|
||||
});
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User session created",
|
||||
newUserSession
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import Elysia from "elysia";
|
||||
import { createUserSessionRole } from "./controllers/createUserSession.controller";
|
||||
|
||||
export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post(
|
||||
"/",
|
||||
createUserSessionRole
|
||||
);
|
||||
import Elysia from "elysia";
|
||||
import { createUserSessionRole } from "./controllers/createUserSession.controller";
|
||||
|
||||
export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post(
|
||||
"/",
|
||||
createUserSessionRole
|
||||
);
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { redis } from "../../../utils/databases/redis/connection";
|
||||
|
||||
export const checkUserSessionInCacheRepo = async (redisKeyName: string) => {
|
||||
try {
|
||||
const userSessionInRedis = await redis.exists(redisKeyName);
|
||||
if (!userSessionInRedis) return false;
|
||||
|
||||
return userSessionInRedis;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Server cache error", error);
|
||||
}
|
||||
};
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { redis } from "../../../utils/databases/redis/connection";
|
||||
|
||||
export const checkUserSessionInCacheRepo = async (redisKeyName: string) => {
|
||||
try {
|
||||
const userSessionInRedis = await redis.exists(redisKeyName);
|
||||
if (!userSessionInRedis) return false;
|
||||
|
||||
return userSessionInRedis;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Server cache error", error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,33 +1,33 @@
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { prisma } from "../../../utils/databases/prisma/connection";
|
||||
|
||||
export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userSession) return false;
|
||||
|
||||
return userSession;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Database Error", error);
|
||||
}
|
||||
};
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { prisma } from "../../../utils/databases/prisma/connection";
|
||||
|
||||
export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userSession) return false;
|
||||
|
||||
return userSession;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Database Error", error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,32 +1,32 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userSessionModel } from "../userSession.model";
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
|
||||
export const createUserSessionRepo = async (
|
||||
data: Prisma.UserSessionUncheckedCreateInput
|
||||
) => {
|
||||
try {
|
||||
const newUserSession = await userSessionModel.create({
|
||||
data: data,
|
||||
include: {
|
||||
user: {
|
||||
omit: {
|
||||
password: true,
|
||||
},
|
||||
include: {
|
||||
roles: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
omit: {
|
||||
lastOnline: true,
|
||||
deletedAt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
return newUserSession;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userSessionModel } from "../userSession.model";
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
|
||||
export const createUserSessionRepo = async (
|
||||
data: Prisma.UserSessionUncheckedCreateInput
|
||||
) => {
|
||||
try {
|
||||
const newUserSession = await userSessionModel.create({
|
||||
data: data,
|
||||
include: {
|
||||
user: {
|
||||
omit: {
|
||||
password: true,
|
||||
},
|
||||
include: {
|
||||
roles: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
omit: {
|
||||
lastOnline: true,
|
||||
deletedAt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
return newUserSession;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,19 +1,19 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { redis } from "../../../utils/databases/redis/connection";
|
||||
|
||||
export const storeUserSessionToCacheRepo = async (
|
||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||
timeExpires: number
|
||||
) => {
|
||||
try {
|
||||
await redis.set(
|
||||
`${process.env.app_name}:users:${userSession.userId}:sessions:${userSession.id}`,
|
||||
String(userSession.validUntil),
|
||||
"EX",
|
||||
timeExpires
|
||||
);
|
||||
} catch (error) {
|
||||
throw new AppError(401, "Failed to store user session to cache");
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { redis } from "../../../utils/databases/redis/connection";
|
||||
|
||||
export const storeUserSessionToCacheRepo = async (
|
||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||
timeExpires: number
|
||||
) => {
|
||||
try {
|
||||
await redis.set(
|
||||
`${process.env.app_name}:users:${userSession.userId}:sessions:${userSession.id}`,
|
||||
String(userSession.validUntil),
|
||||
"EX",
|
||||
timeExpires
|
||||
);
|
||||
} catch (error) {
|
||||
throw new AppError(401, "Failed to store user session to cache");
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,19 +1,19 @@
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository";
|
||||
|
||||
export const checkUserSessionInCacheService = async (
|
||||
userId: string,
|
||||
sessionId: string
|
||||
) => {
|
||||
try {
|
||||
// Construct the Redis key name using the userId and sessionId
|
||||
const redisKeyName = `${process.env.app_name}:users:${userId}:sessions:${sessionId}`;
|
||||
|
||||
// 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");
|
||||
}
|
||||
};
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository";
|
||||
|
||||
export const checkUserSessionInCacheService = async (
|
||||
userId: string,
|
||||
sessionId: string
|
||||
) => {
|
||||
try {
|
||||
// Construct the Redis key name using the userId and sessionId
|
||||
const redisKeyName = `${process.env.app_name}:users:${userId}:sessions:${sessionId}`;
|
||||
|
||||
// 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");
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,27 +1,27 @@
|
||||
import { createUserSessionServiceParams } from "../userSession.types";
|
||||
import { createUserSessionRepo } from "../repositories/insertUserSessionToDB.repository";
|
||||
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
export const createUserSessionService = async (
|
||||
data: createUserSessionServiceParams
|
||||
) => {
|
||||
const sessionLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||
try {
|
||||
const newUserSession = await createUserSessionRepo({
|
||||
userId: data.userId,
|
||||
isAuthenticated: true,
|
||||
deviceType: data.userHeaderInformation.deviceType,
|
||||
deviceOs: data.userHeaderInformation.deviceOS,
|
||||
deviceIp: data.userHeaderInformation.ip,
|
||||
validUntil: new Date(new Date().getTime() + sessionLifetime * 1000),
|
||||
});
|
||||
|
||||
const timeExpires = Number(process.env.SESSION_EXPIRE!);
|
||||
await storeUserSessionToCacheRepo(newUserSession, timeExpires);
|
||||
|
||||
return newUserSession;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
import { createUserSessionServiceParams } from "../userSession.types";
|
||||
import { createUserSessionRepo } from "../repositories/insertUserSessionToDB.repository";
|
||||
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
export const createUserSessionService = async (
|
||||
data: createUserSessionServiceParams
|
||||
) => {
|
||||
const sessionLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||
try {
|
||||
const newUserSession = await createUserSessionRepo({
|
||||
userId: data.userId,
|
||||
isAuthenticated: true,
|
||||
deviceType: data.userHeaderInformation.deviceType,
|
||||
deviceOs: data.userHeaderInformation.deviceOS,
|
||||
deviceIp: data.userHeaderInformation.ip,
|
||||
validUntil: new Date(new Date().getTime() + sessionLifetime * 1000),
|
||||
});
|
||||
|
||||
const timeExpires = Number(process.env.SESSION_EXPIRE!);
|
||||
await storeUserSessionToCacheRepo(newUserSession, timeExpires);
|
||||
|
||||
return newUserSession;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,23 +1,23 @@
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
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
|
||||
ErrorForwarder(error, 401, "Unable to get user session");
|
||||
}
|
||||
};
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
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
|
||||
ErrorForwarder(error, 401, "Unable to get user session");
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
export const storeUserSessionToCacheService = async (
|
||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||
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
|
||||
ErrorForwarder(error, 401, "Failed to store user session to cache");
|
||||
}
|
||||
};
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
export const storeUserSessionToCacheService = async (
|
||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||
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
|
||||
ErrorForwarder(error, 401, "Failed to store user session to cache");
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userSessionModel = prisma.userSession;
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userSessionModel = prisma.userSession;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||
|
||||
export interface createUserSessionServiceParams {
|
||||
userId: string;
|
||||
userHeaderInformation: UserHeaderInformation;
|
||||
}
|
||||
import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||
|
||||
export interface createUserSessionServiceParams {
|
||||
userId: string;
|
||||
userHeaderInformation: UserHeaderInformation;
|
||||
}
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
export const prisma = new PrismaClient();
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
export const prisma = new PrismaClient();
|
||||
|
||||
@ -1,225 +1,225 @@
|
||||
/**
|
||||
* Map of known Prisma error codes to HTTP status codes and messages.
|
||||
* Extend this map to handle additional error codes if needed.
|
||||
*/
|
||||
export const PrismaErrorCodeList: Record<
|
||||
string,
|
||||
{ status: number; message: string }
|
||||
> = {
|
||||
P1000: {
|
||||
status: 500,
|
||||
message: `Authentication failed against the database server.`,
|
||||
},
|
||||
P1001: {
|
||||
status: 503,
|
||||
message: `Can't reach database server at ${process.env.APP_NAME}.`,
|
||||
},
|
||||
P1002: {
|
||||
status: 503,
|
||||
message: `The database server was reached but timed out.`,
|
||||
},
|
||||
P1003: {
|
||||
status: 500,
|
||||
message: `Database does not exist.`,
|
||||
},
|
||||
P1008: {
|
||||
status: 504,
|
||||
message: `Operations timed out.`,
|
||||
},
|
||||
P1009: {
|
||||
status: 500,
|
||||
message: `Database requires SSL connection.`,
|
||||
},
|
||||
P1010: {
|
||||
status: 403,
|
||||
message: `User was denied access to the database.`,
|
||||
},
|
||||
P1011: {
|
||||
status: 500,
|
||||
message: `Error opening a TLS connection.`,
|
||||
},
|
||||
P1012: {
|
||||
status: 500,
|
||||
message: `Schema validation error.`,
|
||||
},
|
||||
P1013: {
|
||||
status: 500,
|
||||
message: `Invalid Prisma schema.`,
|
||||
},
|
||||
P1014: {
|
||||
status: 500,
|
||||
message: `The underlying engine for the datasource could not be found.`,
|
||||
},
|
||||
P1015: {
|
||||
status: 500,
|
||||
message: `Your Prisma schema is using features that are not supported for the database.`,
|
||||
},
|
||||
P1016: {
|
||||
status: 500,
|
||||
message: `Your Prisma schema is using features that are not supported for the database version.`,
|
||||
},
|
||||
P1017: {
|
||||
status: 500,
|
||||
message: `The Prisma engine has crashed.`,
|
||||
},
|
||||
P1018: {
|
||||
status: 500,
|
||||
message: `The current Prisma engine version is not compatible with the database.`,
|
||||
},
|
||||
P1019: {
|
||||
status: 500,
|
||||
message: `The Prisma engine could not be started.`,
|
||||
},
|
||||
P1020: {
|
||||
status: 500,
|
||||
message: `The Prisma engine exited with an error.`,
|
||||
},
|
||||
P1021: {
|
||||
status: 500,
|
||||
message: `The Prisma engine could not be started due to missing dependencies.`,
|
||||
},
|
||||
P1022: {
|
||||
status: 500,
|
||||
message: `The Prisma engine could not be started due to an unknown error.`,
|
||||
},
|
||||
P2000: {
|
||||
status: 400,
|
||||
message: `The provided value for the column is too long for the column's type.`,
|
||||
},
|
||||
P2001: {
|
||||
status: 404,
|
||||
message: `The record searched for in the where condition does not exist.`,
|
||||
},
|
||||
P2002: {
|
||||
status: 400,
|
||||
message: `Unique constraint failed on the fields.`,
|
||||
},
|
||||
P2003: {
|
||||
status: 400,
|
||||
message: `Foreign key constraint failed on the field.`,
|
||||
},
|
||||
P2004: {
|
||||
status: 400,
|
||||
message: `A constraint failed on the database.`,
|
||||
},
|
||||
P2005: {
|
||||
status: 400,
|
||||
message: `The value stored in the database for the field is invalid for the field's type.`,
|
||||
},
|
||||
P2006: {
|
||||
status: 400,
|
||||
message: `The provided value for the field is not valid.`,
|
||||
},
|
||||
P2007: {
|
||||
status: 400,
|
||||
message: `Data validation error.`,
|
||||
},
|
||||
P2008: {
|
||||
status: 500,
|
||||
message: `Failed to parse the query.`,
|
||||
},
|
||||
P2009: {
|
||||
status: 400,
|
||||
message: `Failed to validate the query.`,
|
||||
},
|
||||
P2010: {
|
||||
status: 400,
|
||||
message: `Raw query failed.`,
|
||||
},
|
||||
P2011: {
|
||||
status: 400,
|
||||
message: `Null constraint violation on the field.`,
|
||||
},
|
||||
P2012: {
|
||||
status: 400,
|
||||
message: `Missing a required value.`,
|
||||
},
|
||||
P2013: {
|
||||
status: 400,
|
||||
message: `Missing the required argument.`,
|
||||
},
|
||||
P2014: {
|
||||
status: 400,
|
||||
message: `The change you are trying to make would violate the required relation.`,
|
||||
},
|
||||
P2015: {
|
||||
status: 404,
|
||||
message: `A related record could not be found.`,
|
||||
},
|
||||
P2016: {
|
||||
status: 400,
|
||||
message: `Query interpretation error.`,
|
||||
},
|
||||
P2017: {
|
||||
status: 400,
|
||||
message: `The records for the relation between the parent and child models were not connected.`,
|
||||
},
|
||||
P2018: {
|
||||
status: 400,
|
||||
message: `The required connected records were not found.`,
|
||||
},
|
||||
P2019: {
|
||||
status: 400,
|
||||
message: `Input error.`,
|
||||
},
|
||||
P2020: {
|
||||
status: 400,
|
||||
message: `Value out of range for the type.`,
|
||||
},
|
||||
P2021: {
|
||||
status: 400,
|
||||
message: `The table does not exist in the current database.`,
|
||||
},
|
||||
P2022: {
|
||||
status: 400,
|
||||
message: `The column does not exist in the current database.`,
|
||||
},
|
||||
P2023: {
|
||||
status: 400,
|
||||
message: `Inconsistent column data.`,
|
||||
},
|
||||
P2024: {
|
||||
status: 400,
|
||||
message: `Timed out fetching a new connection from the connection pool.`,
|
||||
},
|
||||
P2025: {
|
||||
status: 404,
|
||||
message: `An operation failed because it depends on one or more records that were required but not found.`,
|
||||
},
|
||||
P2026: {
|
||||
status: 400,
|
||||
message: `The current database provider doesn't support a feature that the query uses.`,
|
||||
},
|
||||
P2027: {
|
||||
status: 400,
|
||||
message: `Multiple errors occurred on the database during query execution.`,
|
||||
},
|
||||
P2028: {
|
||||
status: 400,
|
||||
message: `Transaction API error.`,
|
||||
},
|
||||
P2029: {
|
||||
status: 400,
|
||||
message: `Query parameter limit exceeded.`,
|
||||
},
|
||||
P2030: {
|
||||
status: 400,
|
||||
message: `Cannot find a fulltext index to use for the search.`,
|
||||
},
|
||||
P2031: {
|
||||
status: 400,
|
||||
message: `Prisma needs to perform a transaction, but the database does not support transactions.`,
|
||||
},
|
||||
P2033: {
|
||||
status: 400,
|
||||
message: `A number used in the query does not fit into a 64-bit signed integer.`,
|
||||
},
|
||||
P2034: {
|
||||
status: 503,
|
||||
message: `Too many connections are open to the database.`,
|
||||
},
|
||||
P2035: {
|
||||
status: 400,
|
||||
message: `A constraint failed on the database.`,
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Map of known Prisma error codes to HTTP status codes and messages.
|
||||
* Extend this map to handle additional error codes if needed.
|
||||
*/
|
||||
export const PrismaErrorCodeList: Record<
|
||||
string,
|
||||
{ status: number; message: string }
|
||||
> = {
|
||||
P1000: {
|
||||
status: 500,
|
||||
message: `Authentication failed against the database server.`,
|
||||
},
|
||||
P1001: {
|
||||
status: 503,
|
||||
message: `Can't reach database server at ${process.env.APP_NAME}.`,
|
||||
},
|
||||
P1002: {
|
||||
status: 503,
|
||||
message: `The database server was reached but timed out.`,
|
||||
},
|
||||
P1003: {
|
||||
status: 500,
|
||||
message: `Database does not exist.`,
|
||||
},
|
||||
P1008: {
|
||||
status: 504,
|
||||
message: `Operations timed out.`,
|
||||
},
|
||||
P1009: {
|
||||
status: 500,
|
||||
message: `Database requires SSL connection.`,
|
||||
},
|
||||
P1010: {
|
||||
status: 403,
|
||||
message: `User was denied access to the database.`,
|
||||
},
|
||||
P1011: {
|
||||
status: 500,
|
||||
message: `Error opening a TLS connection.`,
|
||||
},
|
||||
P1012: {
|
||||
status: 500,
|
||||
message: `Schema validation error.`,
|
||||
},
|
||||
P1013: {
|
||||
status: 500,
|
||||
message: `Invalid Prisma schema.`,
|
||||
},
|
||||
P1014: {
|
||||
status: 500,
|
||||
message: `The underlying engine for the datasource could not be found.`,
|
||||
},
|
||||
P1015: {
|
||||
status: 500,
|
||||
message: `Your Prisma schema is using features that are not supported for the database.`,
|
||||
},
|
||||
P1016: {
|
||||
status: 500,
|
||||
message: `Your Prisma schema is using features that are not supported for the database version.`,
|
||||
},
|
||||
P1017: {
|
||||
status: 500,
|
||||
message: `The Prisma engine has crashed.`,
|
||||
},
|
||||
P1018: {
|
||||
status: 500,
|
||||
message: `The current Prisma engine version is not compatible with the database.`,
|
||||
},
|
||||
P1019: {
|
||||
status: 500,
|
||||
message: `The Prisma engine could not be started.`,
|
||||
},
|
||||
P1020: {
|
||||
status: 500,
|
||||
message: `The Prisma engine exited with an error.`,
|
||||
},
|
||||
P1021: {
|
||||
status: 500,
|
||||
message: `The Prisma engine could not be started due to missing dependencies.`,
|
||||
},
|
||||
P1022: {
|
||||
status: 500,
|
||||
message: `The Prisma engine could not be started due to an unknown error.`,
|
||||
},
|
||||
P2000: {
|
||||
status: 400,
|
||||
message: `The provided value for the column is too long for the column's type.`,
|
||||
},
|
||||
P2001: {
|
||||
status: 404,
|
||||
message: `The record searched for in the where condition does not exist.`,
|
||||
},
|
||||
P2002: {
|
||||
status: 400,
|
||||
message: `Unique constraint failed on the fields.`,
|
||||
},
|
||||
P2003: {
|
||||
status: 400,
|
||||
message: `Foreign key constraint failed on the field.`,
|
||||
},
|
||||
P2004: {
|
||||
status: 400,
|
||||
message: `A constraint failed on the database.`,
|
||||
},
|
||||
P2005: {
|
||||
status: 400,
|
||||
message: `The value stored in the database for the field is invalid for the field's type.`,
|
||||
},
|
||||
P2006: {
|
||||
status: 400,
|
||||
message: `The provided value for the field is not valid.`,
|
||||
},
|
||||
P2007: {
|
||||
status: 400,
|
||||
message: `Data validation error.`,
|
||||
},
|
||||
P2008: {
|
||||
status: 500,
|
||||
message: `Failed to parse the query.`,
|
||||
},
|
||||
P2009: {
|
||||
status: 400,
|
||||
message: `Failed to validate the query.`,
|
||||
},
|
||||
P2010: {
|
||||
status: 400,
|
||||
message: `Raw query failed.`,
|
||||
},
|
||||
P2011: {
|
||||
status: 400,
|
||||
message: `Null constraint violation on the field.`,
|
||||
},
|
||||
P2012: {
|
||||
status: 400,
|
||||
message: `Missing a required value.`,
|
||||
},
|
||||
P2013: {
|
||||
status: 400,
|
||||
message: `Missing the required argument.`,
|
||||
},
|
||||
P2014: {
|
||||
status: 400,
|
||||
message: `The change you are trying to make would violate the required relation.`,
|
||||
},
|
||||
P2015: {
|
||||
status: 404,
|
||||
message: `A related record could not be found.`,
|
||||
},
|
||||
P2016: {
|
||||
status: 400,
|
||||
message: `Query interpretation error.`,
|
||||
},
|
||||
P2017: {
|
||||
status: 400,
|
||||
message: `The records for the relation between the parent and child models were not connected.`,
|
||||
},
|
||||
P2018: {
|
||||
status: 400,
|
||||
message: `The required connected records were not found.`,
|
||||
},
|
||||
P2019: {
|
||||
status: 400,
|
||||
message: `Input error.`,
|
||||
},
|
||||
P2020: {
|
||||
status: 400,
|
||||
message: `Value out of range for the type.`,
|
||||
},
|
||||
P2021: {
|
||||
status: 400,
|
||||
message: `The table does not exist in the current database.`,
|
||||
},
|
||||
P2022: {
|
||||
status: 400,
|
||||
message: `The column does not exist in the current database.`,
|
||||
},
|
||||
P2023: {
|
||||
status: 400,
|
||||
message: `Inconsistent column data.`,
|
||||
},
|
||||
P2024: {
|
||||
status: 400,
|
||||
message: `Timed out fetching a new connection from the connection pool.`,
|
||||
},
|
||||
P2025: {
|
||||
status: 404,
|
||||
message: `An operation failed because it depends on one or more records that were required but not found.`,
|
||||
},
|
||||
P2026: {
|
||||
status: 400,
|
||||
message: `The current database provider doesn't support a feature that the query uses.`,
|
||||
},
|
||||
P2027: {
|
||||
status: 400,
|
||||
message: `Multiple errors occurred on the database during query execution.`,
|
||||
},
|
||||
P2028: {
|
||||
status: 400,
|
||||
message: `Transaction API error.`,
|
||||
},
|
||||
P2029: {
|
||||
status: 400,
|
||||
message: `Query parameter limit exceeded.`,
|
||||
},
|
||||
P2030: {
|
||||
status: 400,
|
||||
message: `Cannot find a fulltext index to use for the search.`,
|
||||
},
|
||||
P2031: {
|
||||
status: 400,
|
||||
message: `Prisma needs to perform a transaction, but the database does not support transactions.`,
|
||||
},
|
||||
P2033: {
|
||||
status: 400,
|
||||
message: `A number used in the query does not fit into a 64-bit signed integer.`,
|
||||
},
|
||||
P2034: {
|
||||
status: 503,
|
||||
message: `Too many connections are open to the database.`,
|
||||
},
|
||||
P2035: {
|
||||
status: 400,
|
||||
message: `A constraint failed on the database.`,
|
||||
},
|
||||
};
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
/**
|
||||
* @typedef {Object} ErrorResponse
|
||||
* @property {number} status - The HTTP status code corresponding to the error.
|
||||
* @property {string} message - A human-readable error message.
|
||||
* @property {any} [details] - Additional details about the error, if available.
|
||||
*/
|
||||
export interface PrismaErrorTypes {
|
||||
status: number;
|
||||
message: string;
|
||||
details?: any;
|
||||
}
|
||||
/**
|
||||
* @typedef {Object} ErrorResponse
|
||||
* @property {number} status - The HTTP status code corresponding to the error.
|
||||
* @property {string} message - A human-readable error message.
|
||||
* @property {any} [details] - Additional details about the error, if available.
|
||||
*/
|
||||
export interface PrismaErrorTypes {
|
||||
status: number;
|
||||
message: string;
|
||||
details?: any;
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import Redis from "ioredis";
|
||||
|
||||
export const redis = new Redis({
|
||||
host: process.env.REDIS_HOST,
|
||||
port: Number(process.env.REDIS_PORT),
|
||||
password: process.env.REDIS_PASSWORD,
|
||||
});
|
||||
import Redis from "ioredis";
|
||||
|
||||
export const redis = new Redis({
|
||||
host: process.env.REDIS_HOST,
|
||||
port: Number(process.env.REDIS_PORT),
|
||||
password: process.env.REDIS_PASSWORD,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user