🚚 create backup folder
create backup folder for archive the old modules
This commit is contained in:
@ -1,65 +1,65 @@
|
|||||||
export interface LoginWithPasswordRequest {
|
export interface LoginWithPasswordRequest {
|
||||||
identifier: string;
|
identifier: string;
|
||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface JWTSessionPayload {
|
export interface JWTSessionPayload {
|
||||||
id: string;
|
id: string;
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
userId: string;
|
userId: string;
|
||||||
deviceType: string;
|
deviceType: string;
|
||||||
deviceOs: string;
|
deviceOs: string;
|
||||||
deviceIp: string;
|
deviceIp: string;
|
||||||
isOnline: boolean;
|
isOnline: boolean;
|
||||||
lastOnline: Date;
|
lastOnline: Date;
|
||||||
validUntil: Date;
|
validUntil: Date;
|
||||||
deletedAt: null;
|
deletedAt: null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
user: User;
|
user: User;
|
||||||
iat: number;
|
iat: number;
|
||||||
exp: number;
|
exp: number;
|
||||||
}
|
}
|
||||||
interface User {
|
interface User {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
username: string;
|
username: string;
|
||||||
email: string;
|
email: string;
|
||||||
birthDate: null;
|
birthDate: null;
|
||||||
gender: null;
|
gender: null;
|
||||||
phoneCC: null;
|
phoneCC: null;
|
||||||
phoneNumber: null;
|
phoneNumber: null;
|
||||||
bioProfile: null;
|
bioProfile: null;
|
||||||
profilePicture: null;
|
profilePicture: null;
|
||||||
commentPicture: null;
|
commentPicture: null;
|
||||||
preferenceId: null;
|
preferenceId: null;
|
||||||
verifiedAt: null;
|
verifiedAt: null;
|
||||||
disabledAt: null;
|
disabledAt: null;
|
||||||
deletedAt: null;
|
deletedAt: null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
roles: Role[];
|
roles: Role[];
|
||||||
}
|
}
|
||||||
interface Role {
|
interface Role {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
primaryColor: string;
|
primaryColor: string;
|
||||||
secondaryColor: string;
|
secondaryColor: string;
|
||||||
pictureImage: string;
|
pictureImage: string;
|
||||||
badgeImage: null;
|
badgeImage: null;
|
||||||
isSuperadmin: boolean;
|
isSuperadmin: boolean;
|
||||||
canEditMedia: boolean;
|
canEditMedia: boolean;
|
||||||
canManageMedia: boolean;
|
canManageMedia: boolean;
|
||||||
canEditEpisodes: boolean;
|
canEditEpisodes: boolean;
|
||||||
canManageEpisodes: boolean;
|
canManageEpisodes: boolean;
|
||||||
canEditComment: boolean;
|
canEditComment: boolean;
|
||||||
canManageComment: boolean;
|
canManageComment: boolean;
|
||||||
canEditUser: boolean;
|
canEditUser: boolean;
|
||||||
canManageUser: boolean;
|
canManageUser: boolean;
|
||||||
canEditSystem: boolean;
|
canEditSystem: boolean;
|
||||||
canManageSystem: boolean;
|
canManageSystem: boolean;
|
||||||
createdBy: string;
|
createdBy: string;
|
||||||
deletedAt: null;
|
deletedAt: null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
@ -1,27 +1,27 @@
|
|||||||
import {
|
import {
|
||||||
returnErrorResponse,
|
returnErrorResponse,
|
||||||
returnWriteResponse,
|
returnWriteResponse,
|
||||||
} from "../../../helpers/callback/httpResponse";
|
} from "../../../helpers/callback/httpResponse";
|
||||||
import { Context } from "elysia";
|
import { Context } from "elysia";
|
||||||
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
||||||
import { authVerificationService } from "../services/authVerification.service";
|
import { authVerificationService } from "../services/authVerification.service";
|
||||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||||
import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies";
|
import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies";
|
||||||
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
||||||
|
|
||||||
export const authVerification = async (ctx: Context) => {
|
export const authVerification = async (ctx: Context) => {
|
||||||
try {
|
try {
|
||||||
// Get the auth token from cookies
|
// Get the auth token from cookies
|
||||||
const cookie = getCookie(ctx);
|
const cookie = getCookie(ctx);
|
||||||
if (!cookie.auth_token)
|
if (!cookie.auth_token)
|
||||||
return returnErrorResponse(ctx.set, 401, "Auth token not found");
|
return returnErrorResponse(ctx.set, 401, "Auth token not found");
|
||||||
|
|
||||||
// Verify the auth token and get the user session
|
// Verify the auth token and get the user session
|
||||||
const authService = await authVerificationService(cookie.auth_token);
|
const authService = await authVerificationService(cookie.auth_token);
|
||||||
return returnWriteResponse(ctx.set, 200, "User authenticated", authService);
|
return returnWriteResponse(ctx.set, 200, "User authenticated", authService);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If token is invalid or expired, clear the auth cookie and return an error response
|
// If token is invalid or expired, clear the auth cookie and return an error response
|
||||||
clearCookies(ctx.set, [COOKIE_KEYS.AUTH]);
|
clearCookies(ctx.set, [COOKIE_KEYS.AUTH]);
|
||||||
return mainErrorHandler(ctx.set, error);
|
return mainErrorHandler(ctx.set, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,74 +1,74 @@
|
|||||||
import {
|
import {
|
||||||
returnErrorResponse,
|
returnErrorResponse,
|
||||||
returnWriteResponse,
|
returnWriteResponse,
|
||||||
} from "../../../helpers/callback/httpResponse";
|
} from "../../../helpers/callback/httpResponse";
|
||||||
import { Context } from "elysia";
|
import { Context } from "elysia";
|
||||||
import { loginWithPasswordService } from "../services/loginWithPassword.service";
|
import { loginWithPasswordService } from "../services/loginWithPassword.service";
|
||||||
import { LoginWithPasswordRequest } from "../auth.types";
|
import { LoginWithPasswordRequest } from "../auth.types";
|
||||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||||
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
||||||
import { setCookie } from "../../../helpers/http/userHeader/cookies/setCookies";
|
import { setCookie } from "../../../helpers/http/userHeader/cookies/setCookies";
|
||||||
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
import { COOKIE_KEYS } from "../../../constants/cookie.keys";
|
||||||
import { loginWithPasswordSchema } from "../schemas/loginWithPassword";
|
import { loginWithPasswordSchema } from "../schemas/loginWithPassword";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @function loginWithPassword
|
* @function loginWithPassword
|
||||||
* @description Authenticates user using username/email and password.
|
* @description Authenticates user using username/email and password.
|
||||||
* On successful login, sets JWT token in cookies and returns token in response (development only).
|
* 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.
|
* In production environment, only sets cookie without returning token in response body.
|
||||||
*
|
*
|
||||||
* @param {Context & { body: LoginWithPasswordRequest }} ctx - The context object containing request information.
|
* @param {Context & { body: LoginWithPasswordRequest }} ctx - The context object containing request information.
|
||||||
* @param {Object} ctx.body - The login credentials.
|
* @param {Object} ctx.body - The login credentials.
|
||||||
*
|
*
|
||||||
* @returns {Promise<Object>} A response object indicating authentication success or failure.
|
* @returns {Promise<Object>} A response object indicating authentication success or failure.
|
||||||
* @throws {Object} An error response if validation fails or authentication error occurs.
|
* @throws {Object} An error response if validation fails or authentication error occurs.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* Request route: POST /auth/legacy
|
* Request route: POST /auth/legacy
|
||||||
* Request body:
|
* Request body:
|
||||||
* {
|
* {
|
||||||
* "identifier": "user@example.com" or "username123",
|
* "identifier": "user@example.com" or "username123",
|
||||||
* "password": "securePassword123"
|
* "password": "securePassword123"
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* Success Response:
|
* Success Response:
|
||||||
* Status: 200 OK
|
* Status: 200 OK
|
||||||
* Development:
|
* Development:
|
||||||
* {
|
* {
|
||||||
* "message": "Authentication Success",
|
* "message": "Authentication Success",
|
||||||
* "token": "<JWT_TOKEN>" // Only in development environment
|
* "token": "<JWT_TOKEN>" // Only in development environment
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* Failure Responses:
|
* Failure Responses:
|
||||||
* - 400 Bad Request: Invalid user input or missing fields
|
* - 400 Bad Request: Invalid user input or missing fields
|
||||||
* - 401 Unauthorized: Invalid credentials
|
* - 401 Unauthorized: Invalid credentials
|
||||||
* - 500 Internal Server Error: Server error during authentication
|
* - 500 Internal Server Error: Server error during authentication
|
||||||
*/
|
*/
|
||||||
export const loginWithPassword = async (
|
export const loginWithPassword = async (
|
||||||
ctx: Context & { body: LoginWithPasswordRequest }
|
ctx: Context & { body: LoginWithPasswordRequest }
|
||||||
) => {
|
) => {
|
||||||
// Validate the request body against the schema
|
// Validate the request body against the schema
|
||||||
const { error } = loginWithPasswordSchema.validate(ctx.body);
|
const { error } = loginWithPasswordSchema.validate(ctx.body);
|
||||||
if (error || !ctx.body)
|
if (error || !ctx.body)
|
||||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||||
|
|
||||||
// Extract user header information
|
// Extract user header information
|
||||||
const userHeaderInfo = getUserHeaderInformation(ctx);
|
const userHeaderInfo = getUserHeaderInformation(ctx);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Call the service to handle login with password
|
// Call the service to handle login with password
|
||||||
const jwtToken = await loginWithPasswordService(ctx.body, userHeaderInfo);
|
const jwtToken = await loginWithPasswordService(ctx.body, userHeaderInfo);
|
||||||
|
|
||||||
// Set the authentication cookie with the JWT token
|
// Set the authentication cookie with the JWT token
|
||||||
setCookie(ctx.set, COOKIE_KEYS.AUTH, jwtToken);
|
setCookie(ctx.set, COOKIE_KEYS.AUTH, jwtToken);
|
||||||
return returnWriteResponse(
|
return returnWriteResponse(
|
||||||
ctx.set,
|
ctx.set,
|
||||||
200,
|
200,
|
||||||
"Authentication Success",
|
"Authentication Success",
|
||||||
jwtToken
|
jwtToken
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle any errors that occur during the login process
|
// Handle any errors that occur during the login process
|
||||||
return mainErrorHandler(ctx.set, error);
|
return mainErrorHandler(ctx.set, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,12 +1,12 @@
|
|||||||
import Elysia from "elysia";
|
import Elysia from "elysia";
|
||||||
import { loginWithPassword } from "./controller/loginWithPassword.controller";
|
import { loginWithPassword } from "./controller/loginWithPassword.controller";
|
||||||
import { authMiddleware } from "../../middleware/auth.middleware";
|
import { authMiddleware } from "../../middleware/auth.middleware";
|
||||||
import { authVerification } from "./controller/authVerification.controller";
|
import { authVerification } from "./controller/authVerification.controller";
|
||||||
import { logoutController } from "./controller/logout.controller";
|
import { logoutController } from "./controller/logout.controller";
|
||||||
|
|
||||||
export const authModule = new Elysia({ prefix: "/auth" })
|
export const authModule = new Elysia({ prefix: "/auth" })
|
||||||
.post("/legacy", loginWithPassword)
|
.post("/legacy", loginWithPassword)
|
||||||
.post("/verification", authVerification, {
|
.post("/verification", authVerification, {
|
||||||
beforeHandle: authMiddleware,
|
beforeHandle: authMiddleware,
|
||||||
})
|
})
|
||||||
.post("/logout", logoutController);
|
.post("/logout", logoutController);
|
||||||
@ -1,6 +1,6 @@
|
|||||||
import Joi from "joi";
|
import Joi from "joi";
|
||||||
|
|
||||||
export const loginWithPasswordSchema = Joi.object({
|
export const loginWithPasswordSchema = Joi.object({
|
||||||
identifier: Joi.string().required(),
|
identifier: Joi.string().required(),
|
||||||
password: Joi.string().required(),
|
password: Joi.string().required(),
|
||||||
});
|
});
|
||||||
@ -1,44 +1,44 @@
|
|||||||
import { AppError } from "../../../helpers/error/instances/app";
|
import { AppError } from "../../../helpers/error/instances/app";
|
||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
import { jwtDecode } from "../../../helpers/http/jwt/decode";
|
import { jwtDecode } from "../../../helpers/http/jwt/decode";
|
||||||
import { checkUserSessionInCacheService } from "../../userSession/services/checkUserSessionInCache.service";
|
import { checkUserSessionInCacheService } from "../../userSession/services/checkUserSessionInCache.service";
|
||||||
import { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service";
|
import { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service";
|
||||||
import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service";
|
import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service";
|
||||||
import { JWTSessionPayload } from "../auth.types";
|
import { JWTSessionPayload } from "../auth.types";
|
||||||
|
|
||||||
export const authVerificationService = async (cookie: string) => {
|
export const authVerificationService = async (cookie: string) => {
|
||||||
try {
|
try {
|
||||||
// Decode the JWT token to get the session payload
|
// Decode the JWT token to get the session payload
|
||||||
const jwtSession = jwtDecode(cookie) as JWTSessionPayload;
|
const jwtSession = jwtDecode(cookie) as JWTSessionPayload;
|
||||||
|
|
||||||
// Check if the session exists in Redis
|
// Check if the session exists in Redis
|
||||||
const sessionCheckOnRedis = await checkUserSessionInCacheService(
|
const sessionCheckOnRedis = await checkUserSessionInCacheService(
|
||||||
jwtSession.userId,
|
jwtSession.userId,
|
||||||
jwtSession.id
|
jwtSession.id
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!sessionCheckOnRedis) {
|
if (!sessionCheckOnRedis) {
|
||||||
// If not found in Redis, check the database
|
// If not found in Redis, check the database
|
||||||
const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id);
|
const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id);
|
||||||
|
|
||||||
// If the session found in the database, store it in Redis. if not, throw an error
|
// If the session found in the database, store it in Redis. if not, throw an error
|
||||||
if (!sessionCheckOnDB) {
|
if (!sessionCheckOnDB) {
|
||||||
throw new AppError(401, "Session invalid or expired");
|
throw new AppError(401, "Session invalid or expired");
|
||||||
} else {
|
} else {
|
||||||
// Store the session in Redis with the remaining time until expiration
|
// Store the session in Redis with the remaining time until expiration
|
||||||
const timeExpires = Math.floor(
|
const timeExpires = Math.floor(
|
||||||
(new Date(sessionCheckOnDB.validUntil).getTime() -
|
(new Date(sessionCheckOnDB.validUntil).getTime() -
|
||||||
new Date().getTime()) /
|
new Date().getTime()) /
|
||||||
1000
|
1000
|
||||||
);
|
);
|
||||||
await storeUserSessionToCacheService(sessionCheckOnDB, timeExpires);
|
await storeUserSessionToCacheService(sessionCheckOnDB, timeExpires);
|
||||||
return sessionCheckOnDB;
|
return sessionCheckOnDB;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// If the session is found in Redis, return it
|
// If the session is found in Redis, return it
|
||||||
return jwtSession;
|
return jwtSession;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ErrorForwarder(error, 401, "Token is invalid");
|
ErrorForwarder(error, 401, "Token is invalid");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,18 +1,18 @@
|
|||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||||
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
||||||
|
|
||||||
export const loginFromSystemService = async (
|
export const loginFromSystemService = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
userHeaderInfo: UserHeaderInformation
|
userHeaderInfo: UserHeaderInformation
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const userSession = await createUserSessionService({
|
const userSession = await createUserSessionService({
|
||||||
userId,
|
userId,
|
||||||
userHeaderInformation: userHeaderInfo,
|
userHeaderInformation: userHeaderInfo,
|
||||||
});
|
});
|
||||||
return userSession;
|
return userSession;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ErrorForwarder(error);
|
ErrorForwarder(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,40 +1,40 @@
|
|||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
import { findUserByEmailOrUsernameService } from "../../user/services/getUserData.service";
|
import { findUserByEmailOrUsernameService } from "../../user/services/getUserData.service";
|
||||||
import { LoginWithPasswordRequest } from "../auth.types";
|
import { LoginWithPasswordRequest } from "../auth.types";
|
||||||
import { AppError } from "../../../helpers/error/instances/app";
|
import { AppError } from "../../../helpers/error/instances/app";
|
||||||
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||||
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
import { createUserSessionService } from "../../userSession/services/createUserSession.service";
|
||||||
import { jwtEncode } from "../../../helpers/http/jwt/encode";
|
import { jwtEncode } from "../../../helpers/http/jwt/encode";
|
||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
|
|
||||||
export const loginWithPasswordService = async (
|
export const loginWithPasswordService = async (
|
||||||
request: LoginWithPasswordRequest,
|
request: LoginWithPasswordRequest,
|
||||||
userHeaderInfo: UserHeaderInformation
|
userHeaderInfo: UserHeaderInformation
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
// search for user data using an identifier (username or email)
|
// search for user data using an identifier (username or email)
|
||||||
const userData = await findUserByEmailOrUsernameService(
|
const userData = await findUserByEmailOrUsernameService(
|
||||||
request.identifier,
|
request.identifier,
|
||||||
{ verbose: true }
|
{ verbose: true }
|
||||||
);
|
);
|
||||||
|
|
||||||
// if user data is not found, throw an error
|
// if user data is not found, throw an error
|
||||||
if (!userData) throw new AppError(404, "User not found");
|
if (!userData) throw new AppError(404, "User not found");
|
||||||
|
|
||||||
// validate the password in the request with the existing one
|
// validate the password in the request with the existing one
|
||||||
if (!(await bcrypt.compare(request.password, userData.password)))
|
if (!(await bcrypt.compare(request.password, userData.password)))
|
||||||
throw new AppError(401, "Password incorrect");
|
throw new AppError(401, "Password incorrect");
|
||||||
|
|
||||||
// create new user session
|
// create new user session
|
||||||
const userSession = await createUserSessionService({
|
const userSession = await createUserSessionService({
|
||||||
userId: userData.id,
|
userId: userData.id,
|
||||||
userHeaderInformation: userHeaderInfo,
|
userHeaderInformation: userHeaderInfo,
|
||||||
});
|
});
|
||||||
|
|
||||||
// create JWT token that contain user session
|
// create JWT token that contain user session
|
||||||
const jwtToken = jwtEncode(userSession);
|
const jwtToken = jwtEncode(userSession);
|
||||||
return jwtToken;
|
return jwtToken;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ErrorForwarder(error);
|
ErrorForwarder(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,81 +1,81 @@
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { Context } from "elysia";
|
import { Context } from "elysia";
|
||||||
import {
|
import {
|
||||||
returnErrorResponse,
|
returnErrorResponse,
|
||||||
returnWriteResponse,
|
returnWriteResponse,
|
||||||
} from "../../../helpers/callback/httpResponse";
|
} from "../../../helpers/callback/httpResponse";
|
||||||
import { createUserRoleService } from "../services/createUserRole.service";
|
import { createUserRoleService } from "../services/createUserRole.service";
|
||||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||||
import { createUserRoleSchema } from "../schemas/createUserRole.schema";
|
import { createUserRoleSchema } from "../schemas/createUserRole.schema";
|
||||||
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
|
||||||
import { jwtDecode } from "../../../helpers/http/jwt/decode";
|
import { jwtDecode } from "../../../helpers/http/jwt/decode";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @function createUserRole
|
* @function createUserRole
|
||||||
* @description Creates a new user role in the database.
|
* @description Creates a new user role in the database.
|
||||||
*
|
*
|
||||||
* @param {Context & { body: UserRole }} ctx - The context object containing the request body.
|
* @param {Context & { body: UserRole }} ctx - The context object containing the request body.
|
||||||
* @param {UserRole} ctx.body - The user role data to be created.
|
* @param {UserRole} ctx.body - The user role data to be created.
|
||||||
*
|
*
|
||||||
* @returns {Promise<Object>} A response object indicating success or failure.
|
* @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.
|
* @throws {Object} An error response object if validation fails or an error occurs during role creation.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* Request route: POST /roles
|
* Request route: POST /roles
|
||||||
* Request body:
|
* Request body:
|
||||||
* {
|
* {
|
||||||
* "userID": "e31668e6-c261-4a7e-9469-ffad734cf2dd",
|
* "userID": "e31668e6-c261-4a7e-9469-ffad734cf2dd",
|
||||||
* "name": "Admin",
|
* "name": "Admin",
|
||||||
* "primaryColor": "#D9D9D9",
|
* "primaryColor": "#D9D9D9",
|
||||||
* "secondaryColor": "#FFFFFF",
|
* "secondaryColor": "#FFFFFF",
|
||||||
* "pictureImage": "https://example.com/picture.jpg",
|
* "pictureImage": "https://example.com/picture.jpg",
|
||||||
* "badgeImage": "https://example.com/badge.jpg",
|
* "badgeImage": "https://example.com/badge.jpg",
|
||||||
* "isSuperadmin": false,
|
* "isSuperadmin": false,
|
||||||
* "canEditMedia": false,
|
* "canEditMedia": false,
|
||||||
* "canManageMedia": false,
|
* "canManageMedia": false,
|
||||||
* "canEditEpisodes": false,
|
* "canEditEpisodes": false,
|
||||||
* "canManageEpisodes": false,
|
* "canManageEpisodes": false,
|
||||||
* "canEditComment": false,
|
* "canEditComment": false,
|
||||||
* "canManageComment": false,
|
* "canManageComment": false,
|
||||||
* "canEditUser": false,
|
* "canEditUser": false,
|
||||||
* "canManageUser": false,
|
* "canManageUser": false,
|
||||||
* "canEditSystem": false,
|
* "canEditSystem": false,
|
||||||
* "canManageSystem": false
|
* "canManageSystem": false
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
export const createUserRoleController = async (
|
export const createUserRoleController = async (
|
||||||
ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput }
|
ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput }
|
||||||
) => {
|
) => {
|
||||||
// Validation input form with schema
|
// Validation input form with schema
|
||||||
const { error } = createUserRoleSchema.validate(ctx.body);
|
const { error } = createUserRoleSchema.validate(ctx.body);
|
||||||
if (error)
|
if (error)
|
||||||
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
|
||||||
|
|
||||||
// Delete this, use middleware instead!!!
|
// Delete this, use middleware instead!!!
|
||||||
const cookie = getCookie(ctx);
|
const cookie = getCookie(ctx);
|
||||||
if (!cookie.auth_token)
|
if (!cookie.auth_token)
|
||||||
return returnErrorResponse(
|
return returnErrorResponse(
|
||||||
ctx.set,
|
ctx.set,
|
||||||
403,
|
403,
|
||||||
"Forbidden, You don't have access to this resouce"
|
"Forbidden, You don't have access to this resouce"
|
||||||
);
|
);
|
||||||
|
|
||||||
const jwtSession = jwtDecode(cookie.auth_token);
|
const jwtSession = jwtDecode(cookie.auth_token);
|
||||||
|
|
||||||
const formData: Prisma.UserRoleUncheckedCreateInput = {
|
const formData: Prisma.UserRoleUncheckedCreateInput = {
|
||||||
...ctx.body,
|
...ctx.body,
|
||||||
createdBy: jwtSession.userId,
|
createdBy: jwtSession.userId,
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const newUserRole = await createUserRoleService(formData);
|
const newUserRole = await createUserRoleService(formData);
|
||||||
return returnWriteResponse(
|
return returnWriteResponse(
|
||||||
ctx.set,
|
ctx.set,
|
||||||
201,
|
201,
|
||||||
"User role created successfully",
|
"User role created successfully",
|
||||||
newUserRole
|
newUserRole
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mainErrorHandler(ctx.set, error);
|
return mainErrorHandler(ctx.set, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,9 +1,9 @@
|
|||||||
import Elysia from "elysia";
|
import Elysia from "elysia";
|
||||||
import { createUserRoleController } from "./controller/createUserRole.controller";
|
import { createUserRoleController } from "./controller/createUserRole.controller";
|
||||||
import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware";
|
import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware";
|
||||||
|
|
||||||
export const userRoleModule = new Elysia({ prefix: "/roles" })
|
export const userRoleModule = new Elysia({ prefix: "/roles" })
|
||||||
.get("/", () => "Hello User Role Module", {
|
.get("/", () => "Hello User Role Module", {
|
||||||
beforeHandle: unautenticatedMiddleware,
|
beforeHandle: unautenticatedMiddleware,
|
||||||
})
|
})
|
||||||
.post("/", createUserRoleController);
|
.post("/", createUserRoleController);
|
||||||
@ -1,11 +1,11 @@
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { userRoleModel } from "../userRole.model";
|
import { userRoleModel } from "../userRole.model";
|
||||||
|
|
||||||
export const createUserRoleRepo = async (
|
export const createUserRoleRepo = async (
|
||||||
data: Prisma.UserRoleUncheckedCreateInput
|
data: Prisma.UserRoleUncheckedCreateInput
|
||||||
) => {
|
) => {
|
||||||
const newUserRole = await userRoleModel.create({
|
const newUserRole = await userRoleModel.create({
|
||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
return newUserRole;
|
return newUserRole;
|
||||||
};
|
};
|
||||||
@ -1,28 +1,28 @@
|
|||||||
import Joi from "joi";
|
import Joi from "joi";
|
||||||
|
|
||||||
export const createUserRoleSchema = Joi.object({
|
export const createUserRoleSchema = Joi.object({
|
||||||
name: Joi.string().min(4).max(255).required(),
|
name: Joi.string().min(4).max(255).required(),
|
||||||
primaryColor: Joi.string()
|
primaryColor: Joi.string()
|
||||||
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
||||||
.optional(),
|
.optional(),
|
||||||
secondaryColor: Joi.string()
|
secondaryColor: Joi.string()
|
||||||
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
|
||||||
.optional(),
|
.optional(),
|
||||||
pictureImage: Joi.string()
|
pictureImage: Joi.string()
|
||||||
.uri({ scheme: ["http", "https"] })
|
.uri({ scheme: ["http", "https"] })
|
||||||
.optional(),
|
.optional(),
|
||||||
badgeImage: Joi.string()
|
badgeImage: Joi.string()
|
||||||
.uri({ scheme: ["http", "https"] })
|
.uri({ scheme: ["http", "https"] })
|
||||||
.optional(),
|
.optional(),
|
||||||
isSuperadmin: Joi.boolean().required(),
|
isSuperadmin: Joi.boolean().required(),
|
||||||
canEditMedia: Joi.boolean().required(),
|
canEditMedia: Joi.boolean().required(),
|
||||||
canManageMedia: Joi.boolean().required(),
|
canManageMedia: Joi.boolean().required(),
|
||||||
canEditEpisodes: Joi.boolean().required(),
|
canEditEpisodes: Joi.boolean().required(),
|
||||||
canManageEpisodes: Joi.boolean().required(),
|
canManageEpisodes: Joi.boolean().required(),
|
||||||
canEditComment: Joi.boolean().required(),
|
canEditComment: Joi.boolean().required(),
|
||||||
canManageComment: Joi.boolean().required(),
|
canManageComment: Joi.boolean().required(),
|
||||||
canEditUser: Joi.boolean().required(),
|
canEditUser: Joi.boolean().required(),
|
||||||
canManageUser: Joi.boolean().required(),
|
canManageUser: Joi.boolean().required(),
|
||||||
canEditSystem: Joi.boolean().required(),
|
canEditSystem: Joi.boolean().required(),
|
||||||
canManageSystem: Joi.boolean().required(),
|
canManageSystem: Joi.boolean().required(),
|
||||||
});
|
});
|
||||||
@ -1,29 +1,29 @@
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { createUserRoleRepo } from "../repositories/createUserRole.repository";
|
import { createUserRoleRepo } from "../repositories/createUserRole.repository";
|
||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
|
|
||||||
export const createUserRoleService = async (
|
export const createUserRoleService = async (
|
||||||
userRoleData: Prisma.UserRoleUncheckedCreateInput
|
userRoleData: Prisma.UserRoleUncheckedCreateInput
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const dataPayload = {
|
const dataPayload = {
|
||||||
...userRoleData,
|
...userRoleData,
|
||||||
isSuperadmin: Boolean(userRoleData.isSuperadmin),
|
isSuperadmin: Boolean(userRoleData.isSuperadmin),
|
||||||
canEditMedia: Boolean(userRoleData.canEditMedia),
|
canEditMedia: Boolean(userRoleData.canEditMedia),
|
||||||
canManageMedia: Boolean(userRoleData.canManageMedia),
|
canManageMedia: Boolean(userRoleData.canManageMedia),
|
||||||
canEditEpisodes: Boolean(userRoleData.canEditEpisodes),
|
canEditEpisodes: Boolean(userRoleData.canEditEpisodes),
|
||||||
canManageEpisodes: Boolean(userRoleData.canManageEpisodes),
|
canManageEpisodes: Boolean(userRoleData.canManageEpisodes),
|
||||||
canEditComment: Boolean(userRoleData.canEditComment),
|
canEditComment: Boolean(userRoleData.canEditComment),
|
||||||
canManageComment: Boolean(userRoleData.canManageComment),
|
canManageComment: Boolean(userRoleData.canManageComment),
|
||||||
canEditUser: Boolean(userRoleData.canEditUser),
|
canEditUser: Boolean(userRoleData.canEditUser),
|
||||||
canManageUser: Boolean(userRoleData.canManageUser),
|
canManageUser: Boolean(userRoleData.canManageUser),
|
||||||
canEditSystem: Boolean(userRoleData.canEditSystem),
|
canEditSystem: Boolean(userRoleData.canEditSystem),
|
||||||
canManageSystem: Boolean(userRoleData.canManageSystem),
|
canManageSystem: Boolean(userRoleData.canManageSystem),
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
};
|
};
|
||||||
const newUserRole = await createUserRoleRepo(dataPayload);
|
const newUserRole = await createUserRoleRepo(dataPayload);
|
||||||
return newUserRole;
|
return newUserRole;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ErrorForwarder(error);
|
ErrorForwarder(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,3 +1,3 @@
|
|||||||
import { prisma } from "../../utils/databases/prisma/connection";
|
import { prisma } from "../../utils/databases/prisma/connection";
|
||||||
|
|
||||||
export const userRoleModel = prisma.userRole;
|
export const userRoleModel = prisma.userRole;
|
||||||
@ -1,35 +1,35 @@
|
|||||||
import { Context } from "elysia";
|
import { Context } from "elysia";
|
||||||
import { createUserSessionService } from "../services/createUserSession.service";
|
import { createUserSessionService } from "../services/createUserSession.service";
|
||||||
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
|
||||||
import { mainErrorHandler } from "../../../helpers/error/handler";
|
import { mainErrorHandler } from "../../../helpers/error/handler";
|
||||||
import {
|
import {
|
||||||
returnErrorResponse,
|
returnErrorResponse,
|
||||||
returnWriteResponse,
|
returnWriteResponse,
|
||||||
} from "../../../helpers/callback/httpResponse";
|
} from "../../../helpers/callback/httpResponse";
|
||||||
|
|
||||||
export const createUserSessionRole = async (
|
export const createUserSessionRole = async (
|
||||||
ctx: Context & { body: { userId?: string } }
|
ctx: Context & { body: { userId?: string } }
|
||||||
) => {
|
) => {
|
||||||
// Validate request body
|
// Validate request body
|
||||||
if (!ctx.body?.userId) {
|
if (!ctx.body?.userId) {
|
||||||
return returnErrorResponse(ctx.set, 400, "User ID is required");
|
return returnErrorResponse(ctx.set, 400, "User ID is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get user device and browser information
|
// Get user device and browser information
|
||||||
const userHeaderData = getUserHeaderInformation(ctx);
|
const userHeaderData = getUserHeaderInformation(ctx);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const newUserSession = await createUserSessionService({
|
const newUserSession = await createUserSessionService({
|
||||||
userId: ctx.body.userId,
|
userId: ctx.body.userId,
|
||||||
userHeaderInformation: userHeaderData,
|
userHeaderInformation: userHeaderData,
|
||||||
});
|
});
|
||||||
return returnWriteResponse(
|
return returnWriteResponse(
|
||||||
ctx.set,
|
ctx.set,
|
||||||
201,
|
201,
|
||||||
"User session created",
|
"User session created",
|
||||||
newUserSession
|
newUserSession
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return mainErrorHandler(ctx.set, error);
|
return mainErrorHandler(ctx.set, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,7 +1,7 @@
|
|||||||
import Elysia from "elysia";
|
import Elysia from "elysia";
|
||||||
import { createUserSessionRole } from "./controllers/createUserSession.controller";
|
import { createUserSessionRole } from "./controllers/createUserSession.controller";
|
||||||
|
|
||||||
export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post(
|
export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post(
|
||||||
"/",
|
"/",
|
||||||
createUserSessionRole
|
createUserSessionRole
|
||||||
);
|
);
|
||||||
@ -1,13 +1,13 @@
|
|||||||
import { AppError } from "../../../helpers/error/instances/app";
|
import { AppError } from "../../../helpers/error/instances/app";
|
||||||
import { redis } from "../../../utils/databases/redis/connection";
|
import { redis } from "../../../utils/databases/redis/connection";
|
||||||
|
|
||||||
export const checkUserSessionInCacheRepo = async (redisKeyName: string) => {
|
export const checkUserSessionInCacheRepo = async (redisKeyName: string) => {
|
||||||
try {
|
try {
|
||||||
const userSessionInRedis = await redis.exists(redisKeyName);
|
const userSessionInRedis = await redis.exists(redisKeyName);
|
||||||
if (!userSessionInRedis) return false;
|
if (!userSessionInRedis) return false;
|
||||||
|
|
||||||
return userSessionInRedis;
|
return userSessionInRedis;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new AppError(500, "Server cache error", error);
|
throw new AppError(500, "Server cache error", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,32 +1,32 @@
|
|||||||
import { AppError } from "../../../helpers/error/instances/app";
|
import { AppError } from "../../../helpers/error/instances/app";
|
||||||
import { prisma } from "../../../utils/databases/prisma/connection";
|
import { prisma } from "../../../utils/databases/prisma/connection";
|
||||||
|
|
||||||
export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
|
export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
|
||||||
try {
|
try {
|
||||||
const userSession = await prisma.userSession.findUnique({
|
const userSession = await prisma.userSession.findUnique({
|
||||||
where: {
|
where: {
|
||||||
id: identifier,
|
id: identifier,
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
user: {
|
user: {
|
||||||
omit: {
|
omit: {
|
||||||
password: true,
|
password: true,
|
||||||
updatedAt: true,
|
updatedAt: true,
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
roles: true,
|
roles: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
omit: {
|
omit: {
|
||||||
updatedAt: true,
|
updatedAt: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!userSession) return false;
|
if (!userSession) return false;
|
||||||
|
|
||||||
return userSession;
|
return userSession;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new AppError(500, "Database Error", error);
|
throw new AppError(500, "Database Error", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,27 +1,27 @@
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { userSessionModel } from "../userSession.model";
|
import { userSessionModel } from "../userSession.model";
|
||||||
|
|
||||||
export const createUserSessionRepo = async (
|
export const createUserSessionRepo = async (
|
||||||
data: Prisma.UserSessionUncheckedCreateInput
|
data: Prisma.UserSessionUncheckedCreateInput
|
||||||
) => {
|
) => {
|
||||||
const newUserSession = await userSessionModel.create({
|
const newUserSession = await userSessionModel.create({
|
||||||
data: data,
|
data: data,
|
||||||
include: {
|
include: {
|
||||||
user: {
|
user: {
|
||||||
omit: {
|
omit: {
|
||||||
password: true,
|
password: true,
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
roles: true,
|
roles: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
omit: {
|
omit: {
|
||||||
lastOnline: true,
|
lastOnline: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
updatedAt: true,
|
updatedAt: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return newUserSession;
|
return newUserSession;
|
||||||
};
|
};
|
||||||
@ -1,14 +1,14 @@
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { redis } from "../../../utils/databases/redis/connection";
|
import { redis } from "../../../utils/databases/redis/connection";
|
||||||
|
|
||||||
export const storeUserSessionToCacheRepo = async (
|
export const storeUserSessionToCacheRepo = async (
|
||||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||||
timeExpires: number
|
timeExpires: number
|
||||||
) => {
|
) => {
|
||||||
await redis.set(
|
await redis.set(
|
||||||
`${process.env.APP_NAME}:users:${userSession.userId}:sessions:${userSession.id}`,
|
`${process.env.APP_NAME}:users:${userSession.userId}:sessions:${userSession.id}`,
|
||||||
String(userSession.validUntil),
|
String(userSession.validUntil),
|
||||||
"EX",
|
"EX",
|
||||||
timeExpires
|
timeExpires
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@ -1,19 +1,19 @@
|
|||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository";
|
import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository";
|
||||||
|
|
||||||
export const checkUserSessionInCacheService = async (
|
export const checkUserSessionInCacheService = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
sessionId: string
|
sessionId: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
// Construct the Redis key name using the userId and sessionId
|
// Construct the Redis key name using the userId and sessionId
|
||||||
const redisKeyName = `${process.env.APP_NAME}:users:${userId}:sessions:${sessionId}`;
|
const redisKeyName = `${process.env.APP_NAME}:users:${userId}:sessions:${sessionId}`;
|
||||||
|
|
||||||
// Check if the user session exists in Redis
|
// Check if the user session exists in Redis
|
||||||
const userSessionInRedis = await checkUserSessionInCacheRepo(redisKeyName);
|
const userSessionInRedis = await checkUserSessionInCacheRepo(redisKeyName);
|
||||||
return userSessionInRedis;
|
return userSessionInRedis;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Forward the error with a 400 status code and a message
|
// Forward the error with a 400 status code and a message
|
||||||
ErrorForwarder(error, 400, "Bad Request");
|
ErrorForwarder(error, 400, "Bad Request");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,27 +1,27 @@
|
|||||||
import { createUserSessionServiceParams } from "../userSession.types";
|
import { createUserSessionServiceParams } from "../userSession.types";
|
||||||
import { createUserSessionRepo } from "../repositories/insertUserSessionToDB.repository";
|
import { createUserSessionRepo } from "../repositories/insertUserSessionToDB.repository";
|
||||||
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
|
|
||||||
export const createUserSessionService = async (
|
export const createUserSessionService = async (
|
||||||
data: createUserSessionServiceParams
|
data: createUserSessionServiceParams
|
||||||
) => {
|
) => {
|
||||||
const sessionLifetime = Number(process.env.SESSION_EXPIRE!);
|
const sessionLifetime = Number(process.env.SESSION_EXPIRE!);
|
||||||
try {
|
try {
|
||||||
const newUserSession = await createUserSessionRepo({
|
const newUserSession = await createUserSessionRepo({
|
||||||
userId: data.userId,
|
userId: data.userId,
|
||||||
isAuthenticated: true,
|
isAuthenticated: true,
|
||||||
deviceType: data.userHeaderInformation.deviceType,
|
deviceType: data.userHeaderInformation.deviceType,
|
||||||
deviceOs: data.userHeaderInformation.deviceOS,
|
deviceOs: data.userHeaderInformation.deviceOS,
|
||||||
deviceIp: data.userHeaderInformation.ip,
|
deviceIp: data.userHeaderInformation.ip,
|
||||||
validUntil: new Date(new Date().getTime() + sessionLifetime * 1000),
|
validUntil: new Date(new Date().getTime() + sessionLifetime * 1000),
|
||||||
});
|
});
|
||||||
|
|
||||||
const timeExpires = Number(process.env.SESSION_EXPIRE!);
|
const timeExpires = Number(process.env.SESSION_EXPIRE!);
|
||||||
await storeUserSessionToCacheRepo(newUserSession, timeExpires);
|
await storeUserSessionToCacheRepo(newUserSession, timeExpires);
|
||||||
|
|
||||||
return newUserSession;
|
return newUserSession;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ErrorForwarder(error);
|
ErrorForwarder(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,24 +1,24 @@
|
|||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
import { findUniqueUserSessionInDBRepo } from "../repositories/findUniqueUserSessionInDB.repository";
|
import { findUniqueUserSessionInDBRepo } from "../repositories/findUniqueUserSessionInDB.repository";
|
||||||
|
|
||||||
export const getUserSessionFromDBService = async (identifier: string) => {
|
export const getUserSessionFromDBService = async (identifier: string) => {
|
||||||
try {
|
try {
|
||||||
// Check is session exists in DB
|
// Check is session exists in DB
|
||||||
const userSession = await findUniqueUserSessionInDBRepo(identifier);
|
const userSession = await findUniqueUserSessionInDBRepo(identifier);
|
||||||
|
|
||||||
// If session not found, return false
|
// If session not found, return false
|
||||||
if (
|
if (
|
||||||
!userSession ||
|
!userSession ||
|
||||||
!userSession.isAuthenticated ||
|
!userSession.isAuthenticated ||
|
||||||
userSession.deletedAt ||
|
userSession.deletedAt ||
|
||||||
new Date(userSession.validUntil) < new Date()
|
new Date(userSession.validUntil) < new Date()
|
||||||
)
|
)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// If session found, return it
|
// If session found, return it
|
||||||
return userSession;
|
return userSession;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If any DB error occurs, throw an AppError
|
// If any DB error occurs, throw an AppError
|
||||||
ErrorForwarder(error, 401, "Unable to get user session");
|
ErrorForwarder(error, 401, "Unable to get user session");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,17 +1,17 @@
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
|
||||||
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
|
||||||
|
|
||||||
export const storeUserSessionToCacheService = async (
|
export const storeUserSessionToCacheService = async (
|
||||||
userSession: Prisma.UserSessionUncheckedCreateInput,
|
userSession: Prisma.UserSessionUncheckedCreateInput,
|
||||||
timeExpires: number
|
timeExpires: number
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
// Store user session in cache with expiration time
|
// Store user session in cache with expiration time
|
||||||
await storeUserSessionToCacheRepo(userSession, timeExpires);
|
await storeUserSessionToCacheRepo(userSession, timeExpires);
|
||||||
return;
|
return;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If any error occurs while storing session in cache, throw an AppError
|
// If any error occurs while storing session in cache, throw an AppError
|
||||||
ErrorForwarder(error, 401, "Failed to store user session to cache");
|
ErrorForwarder(error, 401, "Failed to store user session to cache");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -1,3 +1,3 @@
|
|||||||
import { prisma } from "../../utils/databases/prisma/connection";
|
import { prisma } from "../../utils/databases/prisma/connection";
|
||||||
|
|
||||||
export const userSessionModel = prisma.userSession;
|
export const userSessionModel = prisma.userSession;
|
||||||
@ -1,6 +1,6 @@
|
|||||||
import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types";
|
import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types";
|
||||||
|
|
||||||
export interface createUserSessionServiceParams {
|
export interface createUserSessionServiceParams {
|
||||||
userId: string;
|
userId: string;
|
||||||
userHeaderInformation: UserHeaderInformation;
|
userHeaderInformation: UserHeaderInformation;
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user