🚚 create backup folder
create backup folder for archive the old modules
This commit is contained in:
@ -1,65 +0,0 @@
|
||||
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 +0,0 @@
|
||||
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,74 +0,0 @@
|
||||
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";
|
||||
|
||||
/**
|
||||
* @function loginWithPassword
|
||||
* @description Authenticates user using username/email and password.
|
||||
* On successful login, sets JWT token in cookies and returns token in response (development only).
|
||||
* In production environment, only sets cookie without returning token in response body.
|
||||
*
|
||||
* @param {Context & { body: LoginWithPasswordRequest }} ctx - The context object containing request information.
|
||||
* @param {Object} ctx.body - The login credentials.
|
||||
*
|
||||
* @returns {Promise<Object>} A response object indicating authentication success or failure.
|
||||
* @throws {Object} An error response if validation fails or authentication error occurs.
|
||||
*
|
||||
* @example
|
||||
* Request route: POST /auth/legacy
|
||||
* Request body:
|
||||
* {
|
||||
* "identifier": "user@example.com" or "username123",
|
||||
* "password": "securePassword123"
|
||||
* }
|
||||
*
|
||||
* Success Response:
|
||||
* Status: 200 OK
|
||||
* Development:
|
||||
* {
|
||||
* "message": "Authentication Success",
|
||||
* "token": "<JWT_TOKEN>" // Only in development environment
|
||||
* }
|
||||
*
|
||||
* Failure Responses:
|
||||
* - 400 Bad Request: Invalid user input or missing fields
|
||||
* - 401 Unauthorized: Invalid credentials
|
||||
* - 500 Internal Server Error: Server error during authentication
|
||||
*/
|
||||
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,65 +0,0 @@
|
||||
import { Context } from "elysia";
|
||||
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { logoutService } from "../services/logout.service";
|
||||
|
||||
/**
|
||||
* @function logoutController
|
||||
* @description Handles user logout by clearing authentication token from cookies.
|
||||
* Requires valid active session (auth token in cookies).
|
||||
* In development environment, returns additional session clearing details.
|
||||
*
|
||||
* @param {Context} ctx - The context object containing request information.
|
||||
*
|
||||
* @returns {Promise<Object>} A response object indicating logout success or failure.
|
||||
* @throws {Object} An error response if no active session found or server error occurs.
|
||||
*
|
||||
* @example
|
||||
* Request route: POST /logout
|
||||
* Request headers:
|
||||
* {
|
||||
* "Cookie": "auth_token=<JWT_TOKEN>"
|
||||
* }
|
||||
*
|
||||
* Success Response:
|
||||
* Status: 200 OK
|
||||
* {
|
||||
* "message": "Successfully logged out",
|
||||
* "data": { ...clearSessionDetails } // Only in development environment
|
||||
* }
|
||||
*
|
||||
* Failure Responses:
|
||||
* - 401 Unauthorized: No active session found (not logged in)
|
||||
* - 500 Internal Server Error: Server error during logout process
|
||||
*/
|
||||
export const logoutController = async (ctx: Context) => {
|
||||
try {
|
||||
// Get the user cookie from the request, if not found, return an error
|
||||
const userCookie = getCookie(ctx);
|
||||
if (!userCookie || !userCookie.auth_token) {
|
||||
return returnErrorResponse(ctx.set, 401, "You're not logged in yet");
|
||||
}
|
||||
|
||||
// Call the logout service to clear the user session
|
||||
const clearSession = logoutService(userCookie.auth_token);
|
||||
|
||||
// Clear the auth cookie from the user session
|
||||
clearCookies(ctx.set, [COOKIE_KEYS.AUTH]);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
200,
|
||||
"Successfully logged out",
|
||||
clearSession
|
||||
);
|
||||
|
||||
// If there's an error during the logout process, handle it
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
@ -1,12 +0,0 @@
|
||||
import Elysia from "elysia";
|
||||
import { loginWithPassword } from "./controller/loginWithPassword.controller";
|
||||
import { authMiddleware } from "../../middleware/auth.middleware";
|
||||
import { authVerification } from "./controller/authVerification.controller";
|
||||
import { logoutController } from "./controller/logout.controller";
|
||||
|
||||
export const authModule = new Elysia({ prefix: "/auth" })
|
||||
.post("/legacy", loginWithPassword)
|
||||
.post("/verification", authVerification, {
|
||||
beforeHandle: authMiddleware,
|
||||
})
|
||||
.post("/logout", logoutController);
|
||||
@ -1,6 +0,0 @@
|
||||
import Joi from "joi";
|
||||
|
||||
export const loginWithPasswordSchema = Joi.object({
|
||||
identifier: Joi.string().required(),
|
||||
password: Joi.string().required(),
|
||||
});
|
||||
@ -1,44 +0,0 @@
|
||||
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,18 +0,0 @@
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
||||
|
||||
export const loginFromSystemService = async (
|
||||
userId: string,
|
||||
userHeaderInfo: UserHeaderInformation
|
||||
) => {
|
||||
try {
|
||||
const userSession = await createUserSessionService({
|
||||
userId,
|
||||
userHeaderInformation: userHeaderInfo,
|
||||
});
|
||||
return userSession;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
@ -1,40 +0,0 @@
|
||||
import bcrypt from "bcrypt";
|
||||
import { findUserByEmailOrUsernameService } from "../../user/services/getUserData.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,
|
||||
{ verbose: true }
|
||||
);
|
||||
|
||||
// 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,19 +0,0 @@
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { jwtDecode } from "../../../helpers/http/jwt/decode";
|
||||
import { deleteUserSessionInCacheAndDBService } from "../../userSession/services/deleteUserSessionInCacheAndDB.service";
|
||||
|
||||
export const logoutService = async (userCookie: string) => {
|
||||
try {
|
||||
// Decode the JWT token to get the user session
|
||||
const jwtToken = jwtDecode(userCookie);
|
||||
|
||||
// Delete the user session from cache and database
|
||||
const deleteUserSessionInCacheAndDB =
|
||||
deleteUserSessionInCacheAndDBService(jwtToken);
|
||||
return deleteUserSessionInCacheAndDB;
|
||||
|
||||
// If the session was not found in the cache or database, throw an error
|
||||
} catch (error) {
|
||||
ErrorForwarder(error, 500, "Logout service had encountered error");
|
||||
}
|
||||
};
|
||||
@ -1,81 +0,0 @@
|
||||
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";
|
||||
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
||||
import { jwtDecode } from "../../../helpers/http/jwt/decode";
|
||||
|
||||
/**
|
||||
* @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 createUserRoleController = async (
|
||||
ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput }
|
||||
) => {
|
||||
// Validation input form with schema
|
||||
const { error } = createUserRoleSchema.validate(ctx.body);
|
||||
if (error)
|
||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||
|
||||
// Delete this, use middleware instead!!!
|
||||
const cookie = getCookie(ctx);
|
||||
if (!cookie.auth_token)
|
||||
return returnErrorResponse(
|
||||
ctx.set,
|
||||
403,
|
||||
"Forbidden, You don't have access to this resouce"
|
||||
);
|
||||
|
||||
const jwtSession = jwtDecode(cookie.auth_token);
|
||||
|
||||
const formData: Prisma.UserRoleUncheckedCreateInput = {
|
||||
...ctx.body,
|
||||
createdBy: jwtSession.userId,
|
||||
};
|
||||
|
||||
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 +0,0 @@
|
||||
import Elysia from "elysia";
|
||||
import { createUserRoleController } 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("/", createUserRoleController);
|
||||
@ -1,11 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userRoleModel } from "../userRole.model";
|
||||
|
||||
export const createUserRoleRepo = async (
|
||||
data: Prisma.UserRoleUncheckedCreateInput
|
||||
) => {
|
||||
const newUserRole = await userRoleModel.create({
|
||||
data,
|
||||
});
|
||||
return newUserRole;
|
||||
};
|
||||
@ -1,6 +0,0 @@
|
||||
import z from "zod";
|
||||
|
||||
export const userRoleAssignmentSchema = z.object({
|
||||
userId: z.string(),
|
||||
roleId: z.string(),
|
||||
});
|
||||
@ -1,28 +0,0 @@
|
||||
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,29 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { createUserRoleRepo } from "../repositories/createUserRole.repository";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
|
||||
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) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
@ -1,3 +0,0 @@
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userRoleModel = prisma.userRole;
|
||||
@ -1,31 +0,0 @@
|
||||
import {
|
||||
returnErrorResponse,
|
||||
returnWriteResponse,
|
||||
} from "../../../helpers/callback/httpResponse";
|
||||
import { Context } from "elysia";
|
||||
import { assignRoleToUserSchema } from "../schemas/assignRoleToUser.schema";
|
||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||
import { assignRoleToUserService } from "../services/assignRoleToUser.service";
|
||||
|
||||
export const assignRoleToUserController = async (ctx: Context) => {
|
||||
const validation = assignRoleToUserSchema.safeParse(ctx.body);
|
||||
if (!validation.success)
|
||||
return returnErrorResponse(
|
||||
ctx.set,
|
||||
400,
|
||||
"Invalid Request",
|
||||
validation.error
|
||||
);
|
||||
|
||||
try {
|
||||
const assignRoleToUser = await assignRoleToUserService(validation.data);
|
||||
return returnWriteResponse(
|
||||
ctx.set,
|
||||
201,
|
||||
"User Role Assigned Successfully",
|
||||
assignRoleToUser
|
||||
);
|
||||
} catch (error) {
|
||||
return mainErrorHandler(ctx.set, error);
|
||||
}
|
||||
};
|
||||
@ -1,6 +0,0 @@
|
||||
import Elysia from "elysia";
|
||||
import { assignRoleToUserController } from "./controller/assignRoleToUser.controller";
|
||||
|
||||
export const userRoleAssignmentModule = new Elysia({
|
||||
prefix: "/role-assignments",
|
||||
}).post("/assign", assignRoleToUserController);
|
||||
@ -1,16 +0,0 @@
|
||||
import { userRoleAssignmentModel } from "../userRoleAssignment.model";
|
||||
import { InputUserRoleAssignment } from "../userRoleAssignment.types";
|
||||
|
||||
export const assignRoleToUserRepository = async ({
|
||||
userId,
|
||||
roleId,
|
||||
}: InputUserRoleAssignment) => {
|
||||
const assignRoleToUser = await userRoleAssignmentModel.create({
|
||||
data: {
|
||||
userId,
|
||||
roleId,
|
||||
},
|
||||
});
|
||||
|
||||
return assignRoleToUser;
|
||||
};
|
||||
@ -1,6 +0,0 @@
|
||||
import z from "zod";
|
||||
|
||||
export const assignRoleToUserSchema = z.object({
|
||||
userId: z.string(),
|
||||
roleId: z.string(),
|
||||
});
|
||||
@ -1,14 +0,0 @@
|
||||
import { assignRoleToUserRepository } from "../repositories/assignRoleToUser.repository";
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { InputUserRoleAssignment } from "../userRoleAssignment.types";
|
||||
|
||||
export const assignRoleToUserService = async (
|
||||
payload: InputUserRoleAssignment
|
||||
) => {
|
||||
try {
|
||||
const assignRoleToUser = await assignRoleToUserRepository(payload);
|
||||
return assignRoleToUser;
|
||||
} catch (error) {
|
||||
ErrorForwarder(error);
|
||||
}
|
||||
};
|
||||
@ -1,3 +0,0 @@
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userRoleAssignmentModel = prisma.userRoleAssignment;
|
||||
@ -1,4 +0,0 @@
|
||||
export interface InputUserRoleAssignment {
|
||||
userId: string;
|
||||
roleId: string;
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
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 +0,0 @@
|
||||
import Elysia from "elysia";
|
||||
import { createUserSessionRole } from "./controllers/createUserSession.controller";
|
||||
|
||||
export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post(
|
||||
"/",
|
||||
createUserSessionRole
|
||||
);
|
||||
@ -1,13 +0,0 @@
|
||||
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,16 +0,0 @@
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { redis } from "../../../utils/databases/redis/connection";
|
||||
|
||||
export const deleteUserSessionFromCacheRepo = async (
|
||||
userId: string,
|
||||
sessionId: string
|
||||
) => {
|
||||
try {
|
||||
const deleteUserSessionFromCache = redis.del(
|
||||
`${process.env.APP_NAME}:users:${userId}:sessions:${sessionId}`
|
||||
);
|
||||
return deleteUserSessionFromCache;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Error while remove data from cache", error);
|
||||
}
|
||||
};
|
||||
@ -1,19 +0,0 @@
|
||||
import { AppError } from "../../../helpers/error/instances/app";
|
||||
import { prisma } from "../../../utils/databases/prisma/connection";
|
||||
|
||||
export const deleteUserSessionFromDBRepo = async (sessionId: string) => {
|
||||
try {
|
||||
const deleteUserSessionFromCacheDB = await prisma.userSession.update({
|
||||
where: {
|
||||
id: sessionId,
|
||||
},
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return deleteUserSessionFromCacheDB;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Error while remove delete from database", error);
|
||||
}
|
||||
};
|
||||
@ -1,32 +0,0 @@
|
||||
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: {
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userSession) return false;
|
||||
|
||||
return userSession;
|
||||
} catch (error) {
|
||||
throw new AppError(500, "Database Error", error);
|
||||
}
|
||||
};
|
||||
@ -1,27 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { userSessionModel } from "../userSession.model";
|
||||
|
||||
export const createUserSessionRepo = async (
|
||||
data: Prisma.UserSessionUncheckedCreateInput
|
||||
) => {
|
||||
const newUserSession = await userSessionModel.create({
|
||||
data: data,
|
||||
include: {
|
||||
user: {
|
||||
omit: {
|
||||
password: true,
|
||||
},
|
||||
include: {
|
||||
roles: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
omit: {
|
||||
lastOnline: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return newUserSession;
|
||||
};
|
||||
@ -1,14 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { redis } from "../../../utils/databases/redis/connection";
|
||||
|
||||
export const storeUserSessionToCacheRepo = async (
|
||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||
timeExpires: number
|
||||
) => {
|
||||
await redis.set(
|
||||
`${process.env.APP_NAME}:users:${userSession.userId}:sessions:${userSession.id}`,
|
||||
String(userSession.validUntil),
|
||||
"EX",
|
||||
timeExpires
|
||||
);
|
||||
};
|
||||
@ -1,19 +0,0 @@
|
||||
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 +0,0 @@
|
||||
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,30 +0,0 @@
|
||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||
import { JWTAuthToken } from "../../../helpers/http/jwt/decode/types";
|
||||
import { deleteUserSessionFromCacheRepo } from "../repositories/deleteUserSessionFromCache.repository";
|
||||
import { deleteUserSessionFromDBRepo } from "../repositories/deleteUserSessionFromDB.repository";
|
||||
|
||||
export const deleteUserSessionInCacheAndDBService = async (
|
||||
jwtToken: JWTAuthToken
|
||||
) => {
|
||||
try {
|
||||
// Construct the userId and sessionId from the JWT token
|
||||
const userId = jwtToken.userId;
|
||||
const sessionId = jwtToken.id;
|
||||
|
||||
// Delete the user session from cache and database
|
||||
await deleteUserSessionFromCacheRepo(userId, sessionId);
|
||||
const deleteUserSessionFromDB = await deleteUserSessionFromDBRepo(
|
||||
sessionId
|
||||
);
|
||||
|
||||
return deleteUserSessionFromDB;
|
||||
|
||||
// If the session was not found in the cache or database, throw an error
|
||||
} catch (error) {
|
||||
ErrorForwarder(
|
||||
error,
|
||||
500,
|
||||
"Delete user session service had encountered error"
|
||||
);
|
||||
}
|
||||
};
|
||||
@ -1,24 +0,0 @@
|
||||
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 ||
|
||||
userSession.deletedAt ||
|
||||
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 +0,0 @@
|
||||
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 +0,0 @@
|
||||
import { prisma } from "../../utils/databases/prisma/connection";
|
||||
|
||||
export const userSessionModel = prisma.userSession;
|
||||
@ -1,6 +0,0 @@
|
||||
import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||
|
||||
export interface createUserSessionServiceParams {
|
||||
userId: string;
|
||||
userHeaderInformation: UserHeaderInformation;
|
||||
}
|
||||
Reference in New Issue
Block a user