🚚 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");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user