RBAC socket updated
This commit is contained in:
@@ -1,155 +1,155 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import {
|
import {
|
||||||
forgetPassword,
|
forgetPassword,
|
||||||
signinService,
|
signinService,
|
||||||
signupService,
|
signupService,
|
||||||
} from "../../shared/services/AuthService";
|
} from "../../shared/services/AuthService";
|
||||||
|
|
||||||
export const signupController = async (
|
export const signupController = async (
|
||||||
req: Request,
|
req: Request,
|
||||||
res: Response
|
res: Response
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const { userName, email, password, confirmPassword } = req.body;
|
const { userName, email, password, confirmPassword } = req.body;
|
||||||
if (!userName || !email || !password || !confirmPassword) {
|
if (!userName || !email || !password || !confirmPassword) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: "All fields are required",
|
message: "All fields are required",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const data = {
|
const data = {
|
||||||
userName,
|
userName,
|
||||||
email,
|
email,
|
||||||
password,
|
password,
|
||||||
confirmPassword,
|
confirmPassword,
|
||||||
};
|
};
|
||||||
const result = await signupService(data);
|
const result = await signupService(data);
|
||||||
|
|
||||||
switch (result.status) {
|
switch (result.status) {
|
||||||
case "User Already exists":
|
case "User Already exists":
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
message: "User Already exists",
|
message: "User Already exists",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "Passwords do not match":
|
case "Passwords do not match":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Passwords do not match",
|
message: "Passwords do not match",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "Signup unsuccessfull":
|
case "Signup unsuccessfull":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Signup unsuccessfull",
|
message: "Signup unsuccessfull",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "Success":
|
case "Success":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Signup Successfull",
|
message: "Signup Successfull",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Internal server error",
|
message: "Internal server error",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Unknown error",
|
message: "Unknown error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
export const signinController = async (
|
export const signinController = async (
|
||||||
req: Request,
|
req: Request,
|
||||||
res: Response
|
res: Response
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const { email, password } = req.body;
|
const { email, password } = req.body;
|
||||||
if (!email || !password) {
|
if (!email || !password) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: "All fields are required",
|
message: "All fields are required",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const data = {
|
const data = {
|
||||||
email,
|
email,
|
||||||
password,
|
password,
|
||||||
};
|
};
|
||||||
const result = await signinService(data);
|
const result = await signinService(data);
|
||||||
|
|
||||||
switch (result.status) {
|
switch (result.status) {
|
||||||
case "User not found!!! Kindly Signup":
|
case "User not found!!! Kindly Signup":
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
message: "User not found!!! Kindly Signup",
|
message: "User not found!!! Kindly Signup",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "Password is invalid...Check the credentials":
|
case "Password is invalid...Check the credentials":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Password is invalid...Check the credentials",
|
message: "Password is invalid...Check the credentials",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "Success":
|
case "Success":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Signup Successfull",
|
message: "Signup Successfull",
|
||||||
data: result.data,
|
data: result.data,
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Internal server error",
|
message: "Internal server error",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Unknown error",
|
message: "Unknown error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
export const forgetPasswordController = async (
|
export const forgetPasswordController = async (
|
||||||
req: Request,
|
req: Request,
|
||||||
res: Response
|
res: Response
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const { email } = req.body;
|
const { email } = req.body;
|
||||||
if (!email) {
|
if (!email) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: "All fields are required",
|
message: "All fields are required",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const data = {
|
const data = {
|
||||||
email,
|
email,
|
||||||
};
|
};
|
||||||
const result = await forgetPassword(data);
|
const result = await forgetPassword(data);
|
||||||
|
|
||||||
switch (result.status) {
|
switch (result.status) {
|
||||||
case "User not found!!! Kindly Signup":
|
case "User not found!!! Kindly Signup":
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
message: "User not found!!! Kindly Signup",
|
message: "User not found!!! Kindly Signup",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "Password is invalid...Check the credentials":
|
case "Password is invalid...Check the credentials":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Password is invalid...Check the credentials",
|
message: "Password is invalid...Check the credentials",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "Success":
|
case "Success":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
message: "Signup Successfull",
|
message: "Signup Successfull",
|
||||||
// data: result.data,
|
// data: result.data,
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Internal server error",
|
message: "Internal server error",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Unknown error",
|
message: "Unknown error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,45 +1,45 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { AuthenticatedRequest } from "../../shared/utils/token";
|
import { AuthenticatedRequest } from "../../shared/utils/token";
|
||||||
import { recentlyViewedServices } from "../../shared/services/homePageService";
|
import { recentlyViewedServices } from "../../shared/services/homePageService";
|
||||||
|
|
||||||
export const homePageRecentlyViewedController = async (
|
export const homePageRecentlyViewedController = async (
|
||||||
req: AuthenticatedRequest,
|
req: AuthenticatedRequest,
|
||||||
res: Response
|
res: Response
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const { organization, userId } = req.user || {};
|
const { organization, userId } = req.user || {};
|
||||||
if (!organization || !userId) {
|
if (!organization || !userId) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: "All fields are required",
|
message: "All fields are required",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const data = {
|
const data = {
|
||||||
organization,
|
organization,
|
||||||
userId,
|
userId,
|
||||||
};
|
};
|
||||||
const result = await recentlyViewedServices(data);
|
const result = await recentlyViewedServices(data);
|
||||||
|
|
||||||
switch (result.status) {
|
switch (result.status) {
|
||||||
case "User not found":
|
case "User not found":
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
message: "User not found",
|
message: "User not found",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case "Success":
|
case "Success":
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
datas: result.data,
|
datas: result.data,
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Internal server error",
|
message: "Internal server error",
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: "Unknown error",
|
message: "Unknown error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { forgetPasswordController, signinController, signupController } from "../controller/authController";
|
import { forgetPasswordController, signinController, signupController } from "../controller/authController";
|
||||||
|
|
||||||
const authRoutes = express.Router();
|
const authRoutes = express.Router();
|
||||||
|
|
||||||
authRoutes.post("/signup", signupController);
|
authRoutes.post("/signup", signupController);
|
||||||
authRoutes.post("/signIn", signinController);
|
authRoutes.post("/signIn", signinController);
|
||||||
authRoutes.post("/forget", forgetPasswordController);
|
authRoutes.post("/forget", forgetPasswordController);
|
||||||
export default authRoutes;
|
export default authRoutes;
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { homePageRecentlyViewedController } from "../controller/homePageController";
|
import { homePageRecentlyViewedController } from "../controller/homePageController";
|
||||||
import { tokenValidator } from "../../shared/utils/token";
|
import { tokenValidator } from "../../shared/utils/token";
|
||||||
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
|
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
|
||||||
const homeRoutes = express.Router();
|
const homeRoutes = express.Router();
|
||||||
|
|
||||||
homeRoutes.get("/home",tokenValidator,authorizedRoles("Admin","Editor","Viewer"), homePageRecentlyViewedController);
|
homeRoutes.get("/home",tokenValidator,authorizedRoles("Admin","Editor","Viewer"), homePageRecentlyViewedController);
|
||||||
export default homeRoutes;
|
export default homeRoutes;
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
import Redis from "ioredis";
|
import Redis from "ioredis";
|
||||||
import * as dotenv from "dotenv";
|
import * as dotenv from "dotenv";
|
||||||
dotenv.config({});
|
dotenv.config({});
|
||||||
const redis = new Redis({
|
const redis = new Redis({
|
||||||
host:
|
host:
|
||||||
process.env.REDIS_ENV === "true"
|
process.env.REDIS_ENV === "true"
|
||||||
? process.env.REDIS_DOCKER
|
? process.env.REDIS_DOCKER
|
||||||
: process.env.REDIS_LOCAL,
|
: process.env.REDIS_LOCAL,
|
||||||
port: parseInt(process.env.REDIS_PORT || "6379"),
|
port: parseInt(process.env.REDIS_PORT || "6379"),
|
||||||
password: "",
|
password: "",
|
||||||
db: 0,
|
db: 0,
|
||||||
});
|
});
|
||||||
redis.on("connect", () => {
|
redis.on("connect", () => {
|
||||||
console.log(`Connected to Redis to ${redis.options.port}`);
|
console.log(`Connected to Redis to ${redis.options.port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
redis.on("error", (err: unknown) => {
|
redis.on("error", (err: unknown) => {
|
||||||
console.error("Redis connection error:", err);
|
console.error("Redis connection error:", err);
|
||||||
});
|
});
|
||||||
|
|
||||||
export default redis;
|
export default redis;
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Response, NextFunction } from "express";
|
import { Response, NextFunction } from "express";
|
||||||
import { AuthenticatedRequest } from "../../shared/utils/token";
|
import { AuthenticatedRequest } from "../../shared/utils/token";
|
||||||
type Role = "Admin" | "Viewer" | "Editor";
|
type Role = "Admin" | "Viewer" | "Editor";
|
||||||
const authorizedRoles = (...allowedRoles: Role[]) => {
|
const authorizedRoles = (...allowedRoles: Role[]) => {
|
||||||
return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||||
if (!req.user || !allowedRoles.includes(req.user.role as Role)) {
|
if (!req.user || !allowedRoles.includes(req.user.role as Role)) {
|
||||||
res.status(403).json({ message: "Access Denied" });
|
res.status(403).json({ message: "Access Denied" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
export default authorizedRoles;
|
export default authorizedRoles;
|
||||||
|
|||||||
@@ -1,61 +1,61 @@
|
|||||||
import mongoose, { Document, Schema } from "mongoose";
|
import mongoose, { Document, Schema } from "mongoose";
|
||||||
import MainModel from "../connection/connection";
|
import MainModel from "../connection/connection";
|
||||||
import { IProject } from "./projectmodel";
|
import { IProject } from "./projectmodel";
|
||||||
import { User } from "./userModel";
|
import { User } from "./userModel";
|
||||||
|
|
||||||
export interface ISharedUser {
|
export interface ISharedUser {
|
||||||
userId: User["_id"];
|
userId: User["_id"];
|
||||||
accessLevel: "Viewer" | "Editor" | "Admin";
|
accessLevel: "Viewer" | "Editor" | "Admin";
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IShare extends Document {
|
export interface IShare extends Document {
|
||||||
projectId: IProject["_id"];
|
projectId: IProject["_id"];
|
||||||
sharedBy: mongoose.Types.ObjectId;
|
sharedBy: mongoose.Types.ObjectId;
|
||||||
sharedWith: ISharedUser[];
|
sharedWith: ISharedUser[];
|
||||||
description?: string;
|
description?: string;
|
||||||
isArchived: boolean;
|
isArchived: boolean;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
const shareSchema = new Schema<IShare>(
|
const shareSchema = new Schema<IShare>(
|
||||||
{
|
{
|
||||||
projectId: {
|
projectId: {
|
||||||
type: mongoose.Schema.Types.ObjectId,
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: "Project",
|
ref: "Project",
|
||||||
},
|
},
|
||||||
sharedBy: {
|
sharedBy: {
|
||||||
type: mongoose.Schema.Types.ObjectId,
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: "User",
|
ref: "User",
|
||||||
},
|
},
|
||||||
sharedWith: [
|
sharedWith: [
|
||||||
{
|
{
|
||||||
userId: {
|
userId: {
|
||||||
type: mongoose.Schema.Types.ObjectId,
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: "User",
|
ref: "User",
|
||||||
},
|
},
|
||||||
accessLevel: {
|
accessLevel: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: ["Viewer", "Editor", "Admin"],
|
enum: ["Viewer", "Editor", "Admin"],
|
||||||
default: "Viewer",
|
default: "Viewer",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
description: {
|
description: {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
isArchived: {
|
isArchived: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const shareModel = (db: any) => {
|
const shareModel = (db: any) => {
|
||||||
return MainModel(db, "Share", shareSchema, "Share");
|
return MainModel(db, "Share", shareSchema, "Share");
|
||||||
};
|
};
|
||||||
|
|
||||||
export default shareModel;
|
export default shareModel;
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
import { Schema, Document } from "mongoose";
|
import { Schema, Document } from "mongoose";
|
||||||
import MainModel from "../connection/connection";
|
import MainModel from "../connection/connection";
|
||||||
import { User } from "./userModel";
|
import { User } from "./userModel";
|
||||||
export interface IUserToken extends Document {
|
export interface IUserToken extends Document {
|
||||||
userId: User["_id"];
|
userId: User["_id"];
|
||||||
isArchive: boolean;
|
isArchive: boolean;
|
||||||
refreshToken: string;
|
refreshToken: string;
|
||||||
resetTokenExpiry?: Date;
|
resetTokenExpiry?: Date;
|
||||||
resetToken: string;
|
resetToken: string;
|
||||||
}
|
}
|
||||||
const tokenSchema: Schema = new Schema({
|
const tokenSchema: Schema = new Schema({
|
||||||
userId: { type: Schema.Types.ObjectId, ref: "User" },
|
userId: { type: Schema.Types.ObjectId, ref: "User" },
|
||||||
isArchive: { type: Boolean, default: false },
|
isArchive: { type: Boolean, default: false },
|
||||||
refreshToken: { type: String },
|
refreshToken: { type: String },
|
||||||
resetToken: { type: String },
|
resetToken: { type: String },
|
||||||
resetTokenExpiry: { type: Date },
|
resetTokenExpiry: { type: Date },
|
||||||
});
|
});
|
||||||
|
|
||||||
const tokenModel = (db: any) => {
|
const tokenModel = (db: any) => {
|
||||||
return MainModel(db, "Token", tokenSchema, "Token");
|
return MainModel(db, "Token", tokenSchema, "Token");
|
||||||
};
|
};
|
||||||
export default tokenModel;
|
export default tokenModel;
|
||||||
|
|||||||
@@ -1,25 +1,25 @@
|
|||||||
import { Schema, Document } from "mongoose";
|
import { Schema, Document } from "mongoose";
|
||||||
import MainModel from "../connection/connection";
|
import MainModel from "../connection/connection";
|
||||||
import { User } from "./userModel";
|
import { User } from "./userModel";
|
||||||
export interface IUserData extends Document {
|
export interface IUserData extends Document {
|
||||||
userId: User["_id"];
|
userId: User["_id"];
|
||||||
isArchive: boolean;
|
isArchive: boolean;
|
||||||
profilePicture: string;
|
profilePicture: string;
|
||||||
recentlyViewed: string[];
|
recentlyViewed: string[];
|
||||||
}
|
}
|
||||||
const userDataSchema: Schema = new Schema({
|
const userDataSchema: Schema = new Schema({
|
||||||
userId: { type: Schema.Types.ObjectId, ref: "User" },
|
userId: { type: Schema.Types.ObjectId, ref: "User" },
|
||||||
isArchive: { type: Boolean, default: false },
|
isArchive: { type: Boolean, default: false },
|
||||||
recentlyViewed: {
|
recentlyViewed: {
|
||||||
type: [String],
|
type: [String],
|
||||||
default: [],
|
default: [],
|
||||||
},
|
},
|
||||||
profilePicture: {
|
profilePicture: {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const userDataModel = (db: any) => {
|
const userDataModel = (db: any) => {
|
||||||
return MainModel(db, "userData", userDataSchema, "userData");
|
return MainModel(db, "userData", userDataSchema, "userData");
|
||||||
};
|
};
|
||||||
export default userDataModel;
|
export default userDataModel;
|
||||||
|
|||||||
@@ -1,36 +1,36 @@
|
|||||||
import { Schema, Document } from "mongoose";
|
import { Schema, Document } from "mongoose";
|
||||||
import MainModel from "../connection/connection";
|
import MainModel from "../connection/connection";
|
||||||
export interface User extends Document {
|
export interface User extends Document {
|
||||||
userName: string;
|
userName: string;
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
isArchive: boolean;
|
isArchive: boolean;
|
||||||
visitorBrowserId: string;
|
visitorBrowserId: string;
|
||||||
role: string;
|
role: string;
|
||||||
}
|
}
|
||||||
const UserSchema: Schema = new Schema({
|
const UserSchema: Schema = new Schema({
|
||||||
userName: {
|
userName: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
role: {
|
role: {
|
||||||
type: String,
|
type: String,
|
||||||
default: "Viewer",
|
default: "Viewer",
|
||||||
enum: ["Editor", "Admin", "Viewer"],
|
enum: ["Editor", "Admin", "Viewer"],
|
||||||
},
|
},
|
||||||
email: {
|
email: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
password: {
|
password: {
|
||||||
type: String,
|
type: String,
|
||||||
min: 8,
|
min: 8,
|
||||||
},
|
},
|
||||||
isArchive: { type: Boolean, default: false },
|
isArchive: { type: Boolean, default: false },
|
||||||
visitorBrowserId: { type: String },
|
visitorBrowserId: { type: String },
|
||||||
});
|
});
|
||||||
|
|
||||||
const userModel = (db: any) => {
|
const userModel = (db: any) => {
|
||||||
return MainModel(db, "Users", UserSchema, "Users");
|
return MainModel(db, "Users", UserSchema, "Users");
|
||||||
};
|
};
|
||||||
export default userModel;
|
export default userModel;
|
||||||
|
|||||||
@@ -1,232 +1,232 @@
|
|||||||
import redis from "../connection/redis";
|
import redis from "../connection/redis";
|
||||||
import tokenModel from "../model/tokenModel";
|
import tokenModel from "../model/tokenModel";
|
||||||
import nodemailer from "nodemailer";
|
import nodemailer from "nodemailer";
|
||||||
import userModel from "../model/userModel";
|
import userModel from "../model/userModel";
|
||||||
import { hashGenerate, hashValidator } from "../utils/hashing";
|
import { hashGenerate, hashValidator } from "../utils/hashing";
|
||||||
import { tokenGenerator, tokenRefreshGenerator } from "../utils/token";
|
import { tokenGenerator, tokenRefreshGenerator } from "../utils/token";
|
||||||
import userDataModel from "../model/userDataModel";
|
import userDataModel from "../model/userDataModel";
|
||||||
|
|
||||||
interface Iresponse {
|
interface Iresponse {
|
||||||
status: string;
|
status: string;
|
||||||
data?: any;
|
data?: any;
|
||||||
}
|
}
|
||||||
interface Isignup {
|
interface Isignup {
|
||||||
userName: string;
|
userName: string;
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
confirmPassword: string;
|
confirmPassword: string;
|
||||||
}
|
}
|
||||||
interface Isignin {
|
interface Isignin {
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
interface IforGotPassword {
|
interface IforGotPassword {
|
||||||
email: string;
|
email: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function existingUserData(email: string, organization: string) {
|
export async function existingUserData(email: string, organization: string) {
|
||||||
const existingData = await userModel(organization).findOne({
|
const existingData = await userModel(organization).findOne({
|
||||||
email: email,
|
email: email,
|
||||||
isArchive: false,
|
isArchive: false,
|
||||||
});
|
});
|
||||||
return existingData;
|
return existingData;
|
||||||
}
|
}
|
||||||
export const signupService = async (data: Isignup): Promise<Iresponse> => {
|
export const signupService = async (data: Isignup): Promise<Iresponse> => {
|
||||||
const { userName, email, password, confirmPassword } = data;
|
const { userName, email, password, confirmPassword } = data;
|
||||||
try {
|
try {
|
||||||
const mailCaseChange = email.toLocaleLowerCase();
|
const mailCaseChange = email.toLocaleLowerCase();
|
||||||
const organization = email.split("@")[1].split(".")[0];
|
const organization = email.split("@")[1].split(".")[0];
|
||||||
const mailExistance = await existingUserData(mailCaseChange, organization);
|
const mailExistance = await existingUserData(mailCaseChange, organization);
|
||||||
if (mailExistance !== null) return { status: "User Already exists" };
|
if (mailExistance !== null) return { status: "User Already exists" };
|
||||||
if (password !== confirmPassword) {
|
if (password !== confirmPassword) {
|
||||||
return { status: "Passwords do not match" };
|
return { status: "Passwords do not match" };
|
||||||
}
|
}
|
||||||
let role;
|
let role;
|
||||||
const passwordHashed = await hashGenerate(password);
|
const passwordHashed = await hashGenerate(password);
|
||||||
const userCount = await userModel(organization).countDocuments({});
|
const userCount = await userModel(organization).countDocuments({});
|
||||||
role = userCount === 0 ? "Admin" : "Viewer";
|
role = userCount === 0 ? "Admin" : "Viewer";
|
||||||
const newUser = await userModel(organization).create({
|
const newUser = await userModel(organization).create({
|
||||||
userName,
|
userName,
|
||||||
email: mailCaseChange,
|
email: mailCaseChange,
|
||||||
password: passwordHashed,
|
password: passwordHashed,
|
||||||
role,
|
role,
|
||||||
});
|
});
|
||||||
if (!newUser) return { status: "Signup unsuccessfull" };
|
if (!newUser) return { status: "Signup unsuccessfull" };
|
||||||
return { status: "Success" };
|
return { status: "Success" };
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
return {
|
return {
|
||||||
status: error.message,
|
status: error.message,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
status: "An unexpected error occurred",
|
status: "An unexpected error occurred",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const signinService = async (data: Isignin): Promise<Iresponse> => {
|
export const signinService = async (data: Isignin): Promise<Iresponse> => {
|
||||||
const { email, password } = data;
|
const { email, password } = data;
|
||||||
try {
|
try {
|
||||||
const mailCaseChange = email.toLocaleLowerCase();
|
const mailCaseChange = email.toLocaleLowerCase();
|
||||||
const organization = email.split("@")[1].split(".")[0];
|
const organization = email.split("@")[1].split(".")[0];
|
||||||
const mailExistance = await existingUserData(mailCaseChange, organization);
|
const mailExistance = await existingUserData(mailCaseChange, organization);
|
||||||
if (mailExistance == null)
|
if (mailExistance == null)
|
||||||
return { status: "User not found!!! Kindly Signup" };
|
return { status: "User not found!!! Kindly Signup" };
|
||||||
const comparePassword = await hashValidator(
|
const comparePassword = await hashValidator(
|
||||||
password,
|
password,
|
||||||
mailExistance.password
|
mailExistance.password
|
||||||
);
|
);
|
||||||
if (!comparePassword)
|
if (!comparePassword)
|
||||||
return { status: "Password is invalid...Check the credentials" };
|
return { status: "Password is invalid...Check the credentials" };
|
||||||
const userDataExistence = await userDataModel(organization).findOne({
|
const userDataExistence = await userDataModel(organization).findOne({
|
||||||
userId: mailExistance._id,
|
userId: mailExistance._id,
|
||||||
isArchive: false,
|
isArchive: false,
|
||||||
});
|
});
|
||||||
if (!userDataExistence) {
|
if (!userDataExistence) {
|
||||||
const userDatacreation = await userDataModel(organization).create({
|
const userDatacreation = await userDataModel(organization).create({
|
||||||
userId: mailExistance._id,
|
userId: mailExistance._id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const tokenValidation = tokenGenerator(
|
const tokenValidation = tokenGenerator(
|
||||||
mailExistance.email,
|
mailExistance.email,
|
||||||
mailExistance.role,
|
mailExistance.role,
|
||||||
mailExistance._id,
|
mailExistance._id,
|
||||||
organization
|
organization
|
||||||
);
|
);
|
||||||
const refreshTokenvalidation = tokenRefreshGenerator(
|
const refreshTokenvalidation = tokenRefreshGenerator(
|
||||||
mailExistance.email,
|
mailExistance.email,
|
||||||
mailExistance.role,
|
mailExistance.role,
|
||||||
mailExistance._id,
|
mailExistance._id,
|
||||||
organization
|
organization
|
||||||
);
|
);
|
||||||
const existingToken = await tokenModel(organization).findOne({
|
const existingToken = await tokenModel(organization).findOne({
|
||||||
userId: mailExistance._id,
|
userId: mailExistance._id,
|
||||||
isArchive: false,
|
isArchive: false,
|
||||||
});
|
});
|
||||||
let finalResult;
|
let finalResult;
|
||||||
if (!existingToken) {
|
if (!existingToken) {
|
||||||
const tokenSave = await tokenModel(organization).create({
|
const tokenSave = await tokenModel(organization).create({
|
||||||
userId: mailExistance._id,
|
userId: mailExistance._id,
|
||||||
isArchive: false,
|
isArchive: false,
|
||||||
refreshToken: refreshTokenvalidation,
|
refreshToken: refreshTokenvalidation,
|
||||||
});
|
});
|
||||||
// await redis.setex(
|
// await redis.setex(
|
||||||
// `user:${mailExistance.Email}`,
|
// `user:${mailExistance.Email}`,
|
||||||
// 3600,
|
// 3600,
|
||||||
// JSON.stringify(tokenSave)
|
// JSON.stringify(tokenSave)
|
||||||
// );
|
// );
|
||||||
finalResult = {
|
finalResult = {
|
||||||
message: "login successfull",
|
message: "login successfull",
|
||||||
email: mailExistance.email,
|
email: mailExistance.email,
|
||||||
name: mailExistance.userName,
|
name: mailExistance.userName,
|
||||||
userId: mailExistance._id,
|
userId: mailExistance._id,
|
||||||
token: tokenValidation,
|
token: tokenValidation,
|
||||||
refreshToken: refreshTokenvalidation,
|
refreshToken: refreshTokenvalidation,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
finalResult = {
|
finalResult = {
|
||||||
message: "login successfull",
|
message: "login successfull",
|
||||||
email: mailExistance.email,
|
email: mailExistance.email,
|
||||||
name: mailExistance.userName,
|
name: mailExistance.userName,
|
||||||
userId: mailExistance._id,
|
userId: mailExistance._id,
|
||||||
token: tokenValidation,
|
token: tokenValidation,
|
||||||
refreshToken: existingToken.refreshToken,
|
refreshToken: existingToken.refreshToken,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return { status: "Success", data: finalResult };
|
return { status: "Success", data: finalResult };
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
return {
|
return {
|
||||||
status: error.message,
|
status: error.message,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
status: "An unexpected error occurred",
|
status: "An unexpected error occurred",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const forgetPassword = async ({
|
export const forgetPassword = async ({
|
||||||
email,
|
email,
|
||||||
}: IforGotPassword): Promise<{ status: string }> => {
|
}: IforGotPassword): Promise<{ status: string }> => {
|
||||||
try {
|
try {
|
||||||
const mailCaseChange = email.toLocaleLowerCase();
|
const mailCaseChange = email.toLocaleLowerCase();
|
||||||
const organization = email.split("@")[1].split(".")[0];
|
const organization = email.split("@")[1].split(".")[0];
|
||||||
const Existing_User = await existingUserData(mailCaseChange, organization);
|
const Existing_User = await existingUserData(mailCaseChange, organization);
|
||||||
if (Existing_User) {
|
if (Existing_User) {
|
||||||
// if (Existing_User.lastPasswordReset) {
|
// if (Existing_User.lastPasswordReset) {
|
||||||
// console.log("if2");
|
// console.log("if2");
|
||||||
// const lastPasswordReset = Existing_User.lastPasswordReset;
|
// const lastPasswordReset = Existing_User.lastPasswordReset;
|
||||||
// const now = Date.now();
|
// const now = Date.now();
|
||||||
// const timeDiff = now - lastPasswordReset;
|
// const timeDiff = now - lastPasswordReset;
|
||||||
// const diffInHours = Math.floor(timeDiff / (1000 * 60 * 60));
|
// const diffInHours = Math.floor(timeDiff / (1000 * 60 * 60));
|
||||||
// if (diffInHours < 24)
|
// if (diffInHours < 24)
|
||||||
// return {
|
// return {
|
||||||
// status: "You can only reset your password once every 24 hours.",
|
// status: "You can only reset your password once every 24 hours.",
|
||||||
// };
|
// };
|
||||||
// }
|
// }
|
||||||
const transport = nodemailer.createTransport({
|
const transport = nodemailer.createTransport({
|
||||||
service: "gmail",
|
service: "gmail",
|
||||||
secure: true,
|
secure: true,
|
||||||
auth: {
|
auth: {
|
||||||
user: process.env.EMAIL_USER,
|
user: process.env.EMAIL_USER,
|
||||||
pass: process.env.EMAIL_PASS,
|
pass: process.env.EMAIL_PASS,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
// const resetToken = tokenGenerator(
|
// const resetToken = tokenGenerator(
|
||||||
// email,
|
// email,
|
||||||
// Existing_User.Role as string,
|
// Existing_User.Role as string,
|
||||||
// Existing_User._id as string,
|
// Existing_User._id as string,
|
||||||
// organization
|
// organization
|
||||||
// );
|
// );
|
||||||
// const userTokenData = await tokenModel(organization).findOne({
|
// const userTokenData = await tokenModel(organization).findOne({
|
||||||
// userId: Existing_User._id,
|
// userId: Existing_User._id,
|
||||||
// isArchive: false,
|
// isArchive: false,
|
||||||
// });
|
// });
|
||||||
// if (!userTokenData) {
|
// if (!userTokenData) {
|
||||||
// await tokenModel(organization).create({
|
// await tokenModel(organization).create({
|
||||||
// // Email: Existing_User.Email,
|
// // Email: Existing_User.Email,
|
||||||
// userId: Existing_User._id,
|
// userId: Existing_User._id,
|
||||||
// resetToken: resetToken,
|
// resetToken: resetToken,
|
||||||
// resetTokenExpiry: Date.now(),
|
// resetTokenExpiry: Date.now(),
|
||||||
// });
|
// });
|
||||||
// } else {
|
// } else {
|
||||||
// userTokenData.resetToken = resetToken;
|
// userTokenData.resetToken = resetToken;
|
||||||
// userTokenData.resetTokenExpiry = new Date();
|
// userTokenData.resetTokenExpiry = new Date();
|
||||||
// await userTokenData.save();
|
// await userTokenData.save();
|
||||||
// }
|
// }
|
||||||
const Receiver = {
|
const Receiver = {
|
||||||
from: process.env.EMAIL_USER,
|
from: process.env.EMAIL_USER,
|
||||||
to: email,
|
to: email,
|
||||||
subject: "Password Reset Request",
|
subject: "Password Reset Request",
|
||||||
// text: "test mail",
|
// text: "test mail",
|
||||||
text: `Click the below link to generate the new password \n ${
|
text: `Click the below link to generate the new password \n ${
|
||||||
process.env.CLIENT_URL
|
process.env.CLIENT_URL
|
||||||
}/reset-password/${tokenGenerator(
|
}/reset-password/${tokenGenerator(
|
||||||
email,
|
email,
|
||||||
Existing_User.Role as string,
|
Existing_User.Role as string,
|
||||||
Existing_User._id as string,
|
Existing_User._id as string,
|
||||||
organization
|
organization
|
||||||
)}`,
|
)}`,
|
||||||
};
|
};
|
||||||
await transport.sendMail(Receiver);
|
await transport.sendMail(Receiver);
|
||||||
|
|
||||||
return { status: "Success" };
|
return { status: "Success" };
|
||||||
} else {
|
} else {
|
||||||
return { status: "Email not found" };
|
return { status: "Email not found" };
|
||||||
}
|
}
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
return {
|
return {
|
||||||
status: error.message,
|
status: error.message,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
status: "An unexpected error occurred",
|
status: "An unexpected error occurred",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,51 +1,51 @@
|
|||||||
import ProjectType from "../../shared/model/projectmodel";
|
import ProjectType from "../../shared/model/projectmodel";
|
||||||
import userDataModel from "../model/userDataModel";
|
import userDataModel from "../model/userDataModel";
|
||||||
import userModel from "../model/userModel";
|
import userModel from "../model/userModel";
|
||||||
|
|
||||||
interface IrecentlyViewed {
|
interface IrecentlyViewed {
|
||||||
organization: string;
|
organization: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
}
|
}
|
||||||
interface Iresponse {
|
interface Iresponse {
|
||||||
status: string;
|
status: string;
|
||||||
data?: any;
|
data?: any;
|
||||||
}
|
}
|
||||||
export const recentlyViewedServices = async (
|
export const recentlyViewedServices = async (
|
||||||
data: IrecentlyViewed
|
data: IrecentlyViewed
|
||||||
): Promise<Iresponse> => {
|
): Promise<Iresponse> => {
|
||||||
const { organization, userId } = data;
|
const { organization, userId } = data;
|
||||||
try {
|
try {
|
||||||
const ExistingUser = await userModel(organization).findOne({
|
const ExistingUser = await userModel(organization).findOne({
|
||||||
_id: userId,
|
_id: userId,
|
||||||
isArchive: false,
|
isArchive: false,
|
||||||
});
|
});
|
||||||
if (!ExistingUser) return { status: "User not found" };
|
if (!ExistingUser) return { status: "User not found" };
|
||||||
const userDatas = await userDataModel(organization)
|
const userDatas = await userDataModel(organization)
|
||||||
.findOne({ userId: userId, isArchive: false })
|
.findOne({ userId: userId, isArchive: false })
|
||||||
.select("recentlyViewed userId");
|
.select("recentlyViewed userId");
|
||||||
const populatedProjects = userDatas.recentlyViewed;
|
const populatedProjects = userDatas.recentlyViewed;
|
||||||
const RecentDatas = await Promise.all(
|
const RecentDatas = await Promise.all(
|
||||||
populatedProjects.map(async (projectId: any) => {
|
populatedProjects.map(async (projectId: any) => {
|
||||||
const projectExisting = await ProjectType(organization)
|
const projectExisting = await ProjectType(organization)
|
||||||
.findOne({
|
.findOne({
|
||||||
_id: projectId,
|
_id: projectId,
|
||||||
isArchive: false,
|
isArchive: false,
|
||||||
})
|
})
|
||||||
.select("_id projectName createdBy thumbnail createdAt isViewed");
|
.select("_id projectName createdBy thumbnail createdAt isViewed");
|
||||||
return projectExisting;
|
return projectExisting;
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
const filteredProjects = RecentDatas.filter(Boolean);
|
const filteredProjects = RecentDatas.filter(Boolean);
|
||||||
return { status: "Success", data: filteredProjects };
|
return { status: "Success", data: filteredProjects };
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
return {
|
return {
|
||||||
status: error.message,
|
status: error.message,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
status: "An unexpected error occurred",
|
status: "An unexpected error occurred",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,24 +1,24 @@
|
|||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
const saltRounds = 10;
|
const saltRounds = 10;
|
||||||
export const hashGenerate = async (Password: string) => {
|
export const hashGenerate = async (Password: string) => {
|
||||||
try {
|
try {
|
||||||
const salt = await bcrypt.genSalt(saltRounds);
|
const salt = await bcrypt.genSalt(saltRounds);
|
||||||
const hash = await bcrypt.hash(Password, salt);
|
const hash = await bcrypt.hash(Password, salt);
|
||||||
|
|
||||||
return hash;
|
return hash;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return error;
|
return error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
export const hashValidator = async (
|
export const hashValidator = async (
|
||||||
password: string,
|
password: string,
|
||||||
hashedPassword: string
|
hashedPassword: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const result = await bcrypt.compare(password, hashedPassword);
|
const result = await bcrypt.compare(password, hashedPassword);
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,139 +1,139 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import Jwt from "jsonwebtoken";
|
import Jwt from "jsonwebtoken";
|
||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
import userModel from "../model/userModel";
|
import userModel from "../model/userModel";
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
export interface AuthenticatedRequest extends Request {
|
export interface AuthenticatedRequest extends Request {
|
||||||
user?: {
|
user?: {
|
||||||
email: string;
|
email: string;
|
||||||
role: string;
|
role: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
organization: string;
|
organization: string;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const jwt_secret = process.env.JWT_SECRET as string;
|
const jwt_secret = process.env.JWT_SECRET as string;
|
||||||
const refresh_jwt_secret = process.env.REFRESH_JWT_SECRET as string;
|
const refresh_jwt_secret = process.env.REFRESH_JWT_SECRET as string;
|
||||||
const tokenGenerator = (
|
const tokenGenerator = (
|
||||||
email: string,
|
email: string,
|
||||||
role: string,
|
role: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
organization: string
|
organization: string
|
||||||
) => {
|
) => {
|
||||||
const token = Jwt.sign(
|
const token = Jwt.sign(
|
||||||
{ email: email, role: role, userId: userId, organization: organization },
|
{ email: email, role: role, userId: userId, organization: organization },
|
||||||
jwt_secret,
|
jwt_secret,
|
||||||
{
|
{
|
||||||
expiresIn: "3h",
|
expiresIn: "3h",
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
return token;
|
return token;
|
||||||
};
|
};
|
||||||
const tokenRefreshGenerator = (
|
const tokenRefreshGenerator = (
|
||||||
email: string,
|
email: string,
|
||||||
role: string,
|
role: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
organization: string
|
organization: string
|
||||||
) => {
|
) => {
|
||||||
const token = Jwt.sign(
|
const token = Jwt.sign(
|
||||||
{ email: email, role: role, userId: userId, organization: organization },
|
{ email: email, role: role, userId: userId, organization: organization },
|
||||||
refresh_jwt_secret,
|
refresh_jwt_secret,
|
||||||
{
|
{
|
||||||
expiresIn: "7d",
|
expiresIn: "7d",
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
return token;
|
return token;
|
||||||
};
|
};
|
||||||
const tokenValidator = async (
|
const tokenValidator = async (
|
||||||
req: AuthenticatedRequest,
|
req: AuthenticatedRequest,
|
||||||
res: Response,
|
res: Response,
|
||||||
next: NextFunction
|
next: NextFunction
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
const token: string | undefined = req.headers.token as string | undefined;
|
const token: string | undefined = req.headers.token as string | undefined;
|
||||||
const refresh_token = req.headers["refresh_token"] as string | undefined;
|
const refresh_token = req.headers["refresh_token"] as string | undefined;
|
||||||
if (!token) {
|
if (!token) {
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
msg: "No token present",
|
msg: "No token present",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const decoded = Jwt.verify(token, jwt_secret) as {
|
const decoded = Jwt.verify(token, jwt_secret) as {
|
||||||
email: string;
|
email: string;
|
||||||
role: string;
|
role: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
organization: string;
|
organization: string;
|
||||||
};
|
};
|
||||||
if (!decoded) {
|
if (!decoded) {
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
success: false,
|
success: false,
|
||||||
status: 403,
|
status: 403,
|
||||||
message: "Invalid Token",
|
message: "Invalid Token",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
req.user = decoded;
|
req.user = decoded;
|
||||||
next();
|
next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!refresh_token) {
|
if (!refresh_token) {
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
success: false,
|
success: false,
|
||||||
status: 403,
|
status: 403,
|
||||||
message: "No refresh token present",
|
message: "No refresh token present",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const decodedRefresh = Jwt.verify(refresh_token, refresh_jwt_secret) as {
|
const decodedRefresh = Jwt.verify(refresh_token, refresh_jwt_secret) as {
|
||||||
email: string;
|
email: string;
|
||||||
role: string;
|
role: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
organization: string;
|
organization: string;
|
||||||
};
|
};
|
||||||
if (!decodedRefresh) {
|
if (!decodedRefresh) {
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
success: false,
|
success: false,
|
||||||
status: 403,
|
status: 403,
|
||||||
message: "Invalid Token",
|
message: "Invalid Token",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const newAccessToken = tokenGenerator(
|
const newAccessToken = tokenGenerator(
|
||||||
decodedRefresh.email,
|
decodedRefresh.email,
|
||||||
decodedRefresh.role,
|
decodedRefresh.role,
|
||||||
decodedRefresh.userId,
|
decodedRefresh.userId,
|
||||||
decodedRefresh.organization
|
decodedRefresh.organization
|
||||||
);
|
);
|
||||||
res.setHeader("x-access-token", newAccessToken);
|
res.setHeader("x-access-token", newAccessToken);
|
||||||
req.user = decodedRefresh;
|
req.user = decodedRefresh;
|
||||||
return next();
|
return next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const decodedAny = Jwt.decode(token || refresh_token) as {
|
const decodedAny = Jwt.decode(token || refresh_token) as {
|
||||||
email?: string;
|
email?: string;
|
||||||
role: string;
|
role: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
organization: string;
|
organization: string;
|
||||||
};
|
};
|
||||||
if (decodedAny?.email) {
|
if (decodedAny?.email) {
|
||||||
const organization = decodedAny?.email.split("@")[1].split(".")[0];
|
const organization = decodedAny?.email.split("@")[1].split(".")[0];
|
||||||
const user = await userModel(organization).findOne({
|
const user = await userModel(organization).findOne({
|
||||||
email: decodedAny.email,
|
email: decodedAny.email,
|
||||||
isArchieve: false,
|
isArchieve: false,
|
||||||
});
|
});
|
||||||
if (user) {
|
if (user) {
|
||||||
user.visitorBrowserID = "";
|
user.visitorBrowserID = "";
|
||||||
await user.save();
|
await user.save();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
success: false,
|
success: false,
|
||||||
status: 403,
|
status: 403,
|
||||||
message: "Invalid Token",
|
message: "Invalid Token",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export { tokenValidator, tokenGenerator, tokenRefreshGenerator };
|
export { tokenValidator, tokenGenerator, tokenRefreshGenerator };
|
||||||
|
|||||||
@@ -1,450 +1,450 @@
|
|||||||
import { Socket, Server } from "socket.io";
|
import { Socket, Server } from "socket.io";
|
||||||
import { EVENTS } from "../events/events";
|
import { EVENTS } from "../events/events";
|
||||||
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
|
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
|
||||||
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
|
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
|
||||||
import { deleteEdge, edgecreation } from "../../shared/services/edgeService";
|
import { deleteEdge, edgecreation } from "../../shared/services/edgeService";
|
||||||
import { addAttributes, DelAttributes, delCollection, DuplicateCollection, Nodecreation, SetCollectionName, UpdateAttributes } from "../../shared/services/collectionService";
|
import { addAttributes, DelAttributes, delCollection, DuplicateCollection, Nodecreation, SetCollectionName, UpdateAttributes } from "../../shared/services/collectionService";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const CollectionHandleEvent = async (
|
export const CollectionHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionCreate || !data?.organization) return;
|
if (event !== EVENTS.collectionCreate || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"position",
|
"position",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionCreateResponse,
|
EVENTS.collectionCreateResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await Nodecreation(data);
|
const result = await Nodecreation(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Node created successfully" },
|
Success: { message: "Node created successfully" },
|
||||||
"Collection node creation unsuccessfull": { message: "Collection node creation unsuccessfull" },
|
"Collection node creation unsuccessfull": { message: "Collection node creation unsuccessfull" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionCreateResponse,
|
EVENTS.collectionCreateResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const CollectioNamenHandleEvent = async (
|
export const CollectioNamenHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionNameSet || !data?.organization) return;
|
if (event !== EVENTS.collectionNameSet || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"collectionName",
|
"collectionName",
|
||||||
"collectionNodeId",
|
"collectionNodeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionNameSetResponse,
|
EVENTS.collectionNameSetResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await SetCollectionName(data);
|
const result = await SetCollectionName(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "collection name updated" },
|
Success: { message: "collection name updated" },
|
||||||
"Collection not found": { message: "Collection not found" },
|
"Collection not found": { message: "Collection not found" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionNameSetResponse,
|
EVENTS.collectionNameSetResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const CollectioDeleteHandleEvent = async (
|
export const CollectioDeleteHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionDelete || !data?.organization) return;
|
if (event !== EVENTS.collectionDelete || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"collectionNodeId",
|
"collectionNodeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionDeleteResponse,
|
EVENTS.collectionDeleteResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await delCollection(data);
|
const result = await delCollection(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Collection deleted successfully" },
|
Success: { message: "Collection deleted successfully" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
"Collection not found": { message: "Collection not found" },
|
"Collection not found": { message: "Collection not found" },
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionDeleteResponse,
|
EVENTS.collectionDeleteResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const CollectioDuplicateHandleEvent = async (
|
export const CollectioDuplicateHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionDuplicate || !data?.organization) return;
|
if (event !== EVENTS.collectionDuplicate || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"collectionNodeId",
|
"collectionNodeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionDeleteResponse,
|
EVENTS.collectionDeleteResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await DuplicateCollection(data);
|
const result = await DuplicateCollection(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Collection deleted successfully" },
|
Success: { message: "Collection deleted successfully" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
"Collection not found": { message: "Collection not found" },
|
"Collection not found": { message: "Collection not found" },
|
||||||
"Duplication unsuccessfull": { message: "Duplication unsuccessfull" },
|
"Duplication unsuccessfull": { message: "Duplication unsuccessfull" },
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionDuplicateResponse,
|
EVENTS.collectionDuplicateResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const setAttributesHandleEvent = async (
|
export const setAttributesHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionAttributeSet || !data?.organization) return;
|
if (event !== EVENTS.collectionAttributeSet || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"attributes",
|
"attributes",
|
||||||
"collectionNodeId",
|
"collectionNodeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionAttributeSetResponse,
|
EVENTS.collectionAttributeSetResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await addAttributes(data);
|
const result = await addAttributes(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Collection Attributes Added" },
|
Success: { message: "Collection Attributes Added" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
"Collection not found": { message: "Collection not found" },
|
"Collection not found": { message: "Collection not found" },
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionAttributeSetResponse,
|
EVENTS.collectionAttributeSetResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const AttributesDeleteHandleEvent = async (
|
export const AttributesDeleteHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionAttributeDelete || !data?.organization) return;
|
if (event !== EVENTS.collectionAttributeDelete || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"attributeId",
|
"attributeId",
|
||||||
"collectionNodeId",
|
"collectionNodeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionAttributeDeleteResponse,
|
EVENTS.collectionAttributeDeleteResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await DelAttributes(data);
|
const result = await DelAttributes(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Field deleted successfully" },
|
Success: { message: "Field deleted successfully" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
"Collection not found": { message: "Collection not found" },
|
"Collection not found": { message: "Collection not found" },
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionAttributeDeleteResponse,
|
EVENTS.collectionAttributeDeleteResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const AttributesUpdateHandleEvent = async (
|
export const AttributesUpdateHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.collectionAttributeUpdate || !data?.organization) return;
|
if (event !== EVENTS.collectionAttributeUpdate || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"attributeId",
|
"attributeId",
|
||||||
"collectionNodeId",
|
"collectionNodeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionAttributeUpdateResponse,
|
EVENTS.collectionAttributeUpdateResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await UpdateAttributes(data);
|
const result = await UpdateAttributes(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Field updated successfully" },
|
Success: { message: "Field updated successfully" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
"Collection not found": { message: "Collection not found" },
|
"Collection not found": { message: "Collection not found" },
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.collectionAttributeUpdateResponse,
|
EVENTS.collectionAttributeUpdateResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -1,134 +1,134 @@
|
|||||||
import { Socket, Server } from "socket.io";
|
import { Socket, Server } from "socket.io";
|
||||||
import { EVENTS } from "../events/events";
|
import { EVENTS } from "../events/events";
|
||||||
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
|
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
|
||||||
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
|
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
|
||||||
import { deleteEdge, edgecreation } from "../../shared/services/edgeService";
|
import { deleteEdge, edgecreation } from "../../shared/services/edgeService";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const edgeHandleEvent = async (
|
export const edgeHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.edgeConnect || !data?.organization) return;
|
if (event !== EVENTS.edgeConnect || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"from",
|
"from",
|
||||||
"to",
|
"to",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.edgeConnectResponse,
|
EVENTS.edgeConnectResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await edgecreation(data);
|
const result = await edgecreation(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "edge Created Successfully" },
|
Success: { message: "edge Created Successfully" },
|
||||||
"User not found": { message: "User not found" },
|
"User not found": { message: "User not found" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
"From collection not found": {
|
"From collection not found": {
|
||||||
message: "From collection not found",
|
message: "From collection not found",
|
||||||
},
|
},
|
||||||
"To collection not found": { message: "To collection not found" },
|
"To collection not found": { message: "To collection not found" },
|
||||||
"Field already exists": { message: "Field already exists" },
|
"Field already exists": { message: "Field already exists" },
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
console.log('result_Datas: ', result_Datas);
|
console.log('result_Datas: ', result_Datas);
|
||||||
|
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.edgeConnectResponse,
|
EVENTS.edgeConnectResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export const deleteEdgeHandleEvent = async (
|
export const deleteEdgeHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.deleteEdgeConnect || !data?.organization) return;
|
if (event !== EVENTS.deleteEdgeConnect || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"edgeId",
|
"edgeId",
|
||||||
"projectId",
|
"projectId",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.deleteEdgeConnectResponse,
|
EVENTS.deleteEdgeConnectResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await deleteEdge(data);
|
const result = await deleteEdge(data);
|
||||||
console.log('result: ', result);
|
console.log('result: ', result);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "edge deleted Successfully" },
|
Success: { message: "edge deleted Successfully" },
|
||||||
"edge not found": { message: "edge not found" },
|
"edge not found": { message: "edge not found" },
|
||||||
"Project not found": { message: "Project not found" },
|
"Project not found": { message: "Project not found" },
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const result_Datas = status === "Success" && result?.data ? result.data : undefined;
|
const result_Datas = status === "Success" && result?.data ? result.data : undefined;
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
console.log('response: ', response);
|
console.log('response: ', response);
|
||||||
|
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.edgeConnectResponse,
|
EVENTS.edgeConnectResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -1,70 +1,70 @@
|
|||||||
import { Socket, Server } from "socket.io";
|
import { Socket, Server } from "socket.io";
|
||||||
import { EVENTS } from "../events/events";
|
import { EVENTS } from "../events/events";
|
||||||
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
|
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
|
||||||
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
|
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
|
||||||
import { projectCreationService } from "../../shared/services/projectService";
|
import { projectCreationService } from "../../shared/services/projectService";
|
||||||
|
|
||||||
export const projectHandleEvent = async (
|
export const projectHandleEvent = async (
|
||||||
event: string,
|
event: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
io: Server,
|
io: Server,
|
||||||
data: any,
|
data: any,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
if (event !== EVENTS.projectCreate || !data?.organization) return;
|
if (event !== EVENTS.projectCreate || !data?.organization) return;
|
||||||
const requiredFields = [
|
const requiredFields = [
|
||||||
"application",
|
"application",
|
||||||
"architecture",
|
"architecture",
|
||||||
"apiType",
|
"apiType",
|
||||||
"projectName",
|
"projectName",
|
||||||
"useableLanguage",
|
"useableLanguage",
|
||||||
"organization",
|
"organization",
|
||||||
];
|
];
|
||||||
const missingFields = validateFields(data, requiredFields);
|
const missingFields = validateFields(data, requiredFields);
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.projectCreateResponse,
|
EVENTS.projectCreateResponse,
|
||||||
ErrorResponse(missingFields, socket, data.organization),
|
ErrorResponse(missingFields, socket, data.organization),
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await projectCreationService(data);
|
const result = await projectCreationService(data);
|
||||||
const status = typeof result?.status === "string" ? result.status : "unknown";
|
const status = typeof result?.status === "string" ? result.status : "unknown";
|
||||||
|
|
||||||
const messages: Record<string, { message: string }> = {
|
const messages: Record<string, { message: string }> = {
|
||||||
Success: { message: "Project Created Successfully" },
|
Success: { message: "Project Created Successfully" },
|
||||||
"Project Already Exists": { message: "Project Already Exists" },
|
"Project Already Exists": { message: "Project Already Exists" },
|
||||||
"Already MVC architecture assigned to this projectId": { message: "Already MVC architecture assigned to this projectId" },
|
"Already MVC architecture assigned to this projectId": { message: "Already MVC architecture assigned to this projectId" },
|
||||||
"Project creation unsuccessfull": {
|
"Project creation unsuccessfull": {
|
||||||
message: "Project creation unsuccessfull",
|
message: "Project creation unsuccessfull",
|
||||||
},
|
},
|
||||||
"New architecture": { message: "New architecture" },
|
"New architecture": { message: "New architecture" },
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const result_Datas =
|
const result_Datas =
|
||||||
status === "Success" && result?.data ? result.data : undefined;
|
status === "Success" && result?.data ? result.data : undefined;
|
||||||
const response = FinalResponse(
|
const response = FinalResponse(
|
||||||
status,
|
status,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
messages,
|
messages,
|
||||||
result_Datas
|
result_Datas
|
||||||
);
|
);
|
||||||
emitToSenderAndAdmins(
|
emitToSenderAndAdmins(
|
||||||
io,
|
io,
|
||||||
socket,
|
socket,
|
||||||
data.organization,
|
data.organization,
|
||||||
EVENTS.projectCreateResponse,
|
EVENTS.projectCreateResponse,
|
||||||
response,
|
response,
|
||||||
connectedUsersByOrg
|
connectedUsersByOrg
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
import { AttributesDeleteHandleEvent, AttributesUpdateHandleEvent, CollectioDeleteHandleEvent, CollectioDuplicateHandleEvent, CollectioNamenHandleEvent, CollectionHandleEvent, setAttributesHandleEvent } from "../controllers/collectionNodeController";
|
import { AttributesDeleteHandleEvent, AttributesUpdateHandleEvent, CollectioDeleteHandleEvent, CollectioDuplicateHandleEvent, CollectioNamenHandleEvent, CollectionHandleEvent, setAttributesHandleEvent } from "../controllers/collectionNodeController";
|
||||||
import { edgeHandleEvent } from "../controllers/edgeController";
|
import { edgeHandleEvent } from "../controllers/edgeController";
|
||||||
import { projectHandleEvent } from "../controllers/projectController";
|
import { projectHandleEvent } from "../controllers/projectController";
|
||||||
import { EVENTS } from "./events";
|
import { EVENTS } from "./events";
|
||||||
|
|
||||||
export const eventHandlerMap: Record<string, Function> = {
|
export const eventHandlerMap: Record<string, Function> = {
|
||||||
[EVENTS.edgeConnect]: edgeHandleEvent,
|
[EVENTS.edgeConnect]: edgeHandleEvent,
|
||||||
[EVENTS.projectCreate]: projectHandleEvent,
|
[EVENTS.projectCreate]: projectHandleEvent,
|
||||||
|
|
||||||
[EVENTS.collectionCreate]: CollectionHandleEvent,
|
[EVENTS.collectionCreate]: CollectionHandleEvent,
|
||||||
[EVENTS.collectionNameSet]: CollectioNamenHandleEvent,
|
[EVENTS.collectionNameSet]: CollectioNamenHandleEvent,
|
||||||
[EVENTS.collectionDelete]: CollectioDeleteHandleEvent,
|
[EVENTS.collectionDelete]: CollectioDeleteHandleEvent,
|
||||||
[EVENTS.collectionDuplicate]: CollectioDuplicateHandleEvent,
|
[EVENTS.collectionDuplicate]: CollectioDuplicateHandleEvent,
|
||||||
[EVENTS.collectionAttributeSet]: setAttributesHandleEvent,
|
[EVENTS.collectionAttributeSet]: setAttributesHandleEvent,
|
||||||
[EVENTS.collectionAttributeDelete]: AttributesDeleteHandleEvent,
|
[EVENTS.collectionAttributeDelete]: AttributesDeleteHandleEvent,
|
||||||
[EVENTS.collectionAttributeUpdate]: AttributesUpdateHandleEvent,
|
[EVENTS.collectionAttributeUpdate]: AttributesUpdateHandleEvent,
|
||||||
};
|
};
|
||||||
@@ -1,35 +1,35 @@
|
|||||||
export const EVENTS = {
|
export const EVENTS = {
|
||||||
connection: "connection",
|
connection: "connection",
|
||||||
disconnect: "disconnect",
|
disconnect: "disconnect",
|
||||||
userConnect: "userConnectResponse",
|
userConnect: "userConnectResponse",
|
||||||
userDisConnect: "userDisConnectResponse",
|
userDisConnect: "userDisConnectResponse",
|
||||||
joinRoom: "joinRoom",
|
joinRoom: "joinRoom",
|
||||||
createroom: "createRoom",
|
createroom: "createRoom",
|
||||||
leaveRoom: "leaveRoom",
|
leaveRoom: "leaveRoom",
|
||||||
roomCreated: "roomCreated",
|
roomCreated: "roomCreated",
|
||||||
roomDeleted: "roomDeleted",
|
roomDeleted: "roomDeleted",
|
||||||
|
|
||||||
|
|
||||||
projectCreate: "v1:project:create",
|
projectCreate: "v1:project:create",
|
||||||
projectCreateResponse: "v1:response:project:create",
|
projectCreateResponse: "v1:response:project:create",
|
||||||
|
|
||||||
collectionCreate: "v1:collection:create",
|
collectionCreate: "v1:collection:create",
|
||||||
collectionCreateResponse: "v1:response:collection:create",
|
collectionCreateResponse: "v1:response:collection:create",
|
||||||
collectionNameSet: "v1:collection:setName",
|
collectionNameSet: "v1:collection:setName",
|
||||||
collectionNameSetResponse: "v1:response:collection:setName",
|
collectionNameSetResponse: "v1:response:collection:setName",
|
||||||
collectionDelete: "v1:collection:delete",
|
collectionDelete: "v1:collection:delete",
|
||||||
collectionDeleteResponse: "v1:response:collection:delete",
|
collectionDeleteResponse: "v1:response:collection:delete",
|
||||||
collectionDuplicate: "v1:collection:duplicate",
|
collectionDuplicate: "v1:collection:duplicate",
|
||||||
collectionDuplicateResponse: "v1:response:collection:duplicate",
|
collectionDuplicateResponse: "v1:response:collection:duplicate",
|
||||||
collectionAttributeSet: "v1:collection:attributeSet",
|
collectionAttributeSet: "v1:collection:attributeSet",
|
||||||
collectionAttributeSetResponse: "v1:response:collection:attributeSet",
|
collectionAttributeSetResponse: "v1:response:collection:attributeSet",
|
||||||
collectionAttributeUpdate: "v1:collection:attributeUpdate",
|
collectionAttributeUpdate: "v1:collection:attributeUpdate",
|
||||||
collectionAttributeUpdateResponse: "v1:response:collection:attributeUpdate",
|
collectionAttributeUpdateResponse: "v1:response:collection:attributeUpdate",
|
||||||
collectionAttributeDelete: "v1:collection:attributeDelete",
|
collectionAttributeDelete: "v1:collection:attributeDelete",
|
||||||
collectionAttributeDeleteResponse: "v1:response:collection:attributeDelete",
|
collectionAttributeDeleteResponse: "v1:response:collection:attributeDelete",
|
||||||
|
|
||||||
edgeConnect: "v1:edge:connect",
|
edgeConnect: "v1:edge:connect",
|
||||||
edgeConnectResponse: "v1:response:edge:connect",
|
edgeConnectResponse: "v1:response:edge:connect",
|
||||||
deleteEdgeConnect: "v1:edge:deleteConnect",
|
deleteEdgeConnect: "v1:edge:deleteConnect",
|
||||||
deleteEdgeConnectResponse: "v1:response:edge:deleteConnect",
|
deleteEdgeConnectResponse: "v1:response:edge:deleteConnect",
|
||||||
}
|
}
|
||||||
@@ -1,32 +1,32 @@
|
|||||||
import express, { Response, Request } from "express";
|
import express, { Response, Request } from "express";
|
||||||
import http from "http";
|
import http from "http";
|
||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
import { Server } from "socket.io";
|
import { Server } from "socket.io";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
import { SocketServer } from "./manager/manager";
|
import { SocketServer } from "./manager/manager";
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const PORT = process.env.SOCKET_PORT;
|
const PORT = process.env.SOCKET_PORT;
|
||||||
const server = http.createServer(app);
|
const server = http.createServer(app);
|
||||||
|
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.get("/", (req: Request, res: Response) => {
|
app.get("/", (req: Request, res: Response) => {
|
||||||
res.send("Hello, I am autoCode RealTime!");
|
res.send("Hello, I am autoCode RealTime!");
|
||||||
});
|
});
|
||||||
const io = new Server(server, {
|
const io = new Server(server, {
|
||||||
cors: {
|
cors: {
|
||||||
origin: "*",
|
origin: "*",
|
||||||
methods: ["GET", "POST"],
|
methods: ["GET", "POST"],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
SocketServer(io);
|
SocketServer(io);
|
||||||
server.listen(PORT, () => {
|
server.listen(PORT, () => {
|
||||||
console.log(`socket-Server is running on http://localhost:${PORT}`);
|
console.log(`socket-Server is running on http://localhost:${PORT}`);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,118 +1,118 @@
|
|||||||
import { Server, Socket } from "socket.io";
|
import { Server, Socket } from "socket.io";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { eventHandlerMap } from "../events/eventHandaler";
|
import { eventHandlerMap } from "../events/eventHandaler";
|
||||||
import { existingUserData } from "../../shared/services/AuthService";
|
import { existingUserData } from "../../shared/services/AuthService";
|
||||||
|
|
||||||
interface UserPayload {
|
interface UserPayload {
|
||||||
userId: string;
|
userId: string;
|
||||||
organization: string;
|
organization: string;
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UserSocketInfo {
|
interface UserSocketInfo {
|
||||||
socketId: string;
|
socketId: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
organization: string;
|
organization: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const connectedUsersByOrg: { [organization: string]: UserSocketInfo[] } = {};
|
const connectedUsersByOrg: { [organization: string]: UserSocketInfo[] } = {};
|
||||||
|
|
||||||
export const SocketServer = async (io: Server) => {
|
export const SocketServer = async (io: Server) => {
|
||||||
|
|
||||||
const namespaceNames = ["/edge", "/project", "/collection"];
|
const namespaceNames = ["/edge", "/project", "/collection"];
|
||||||
|
|
||||||
const onlineUsers: { [organization: string]: Set<string> } = {};
|
const onlineUsers: { [organization: string]: Set<string> } = {};
|
||||||
|
|
||||||
|
|
||||||
namespaceNames.forEach((nspName) => {
|
namespaceNames.forEach((nspName) => {
|
||||||
const namespace = io.of(nspName);
|
const namespace = io.of(nspName);
|
||||||
namespace.use(async (socket: Socket, next) => {
|
namespace.use(async (socket: Socket, next) => {
|
||||||
try {
|
try {
|
||||||
const accessToken = socket.handshake.auth.accessToken as string;
|
const accessToken = socket.handshake.auth.accessToken as string;
|
||||||
const refreshToken = socket.handshake.auth.refreshToken as string;
|
const refreshToken = socket.handshake.auth.refreshToken as string;
|
||||||
if (!accessToken) return next(new Error("No access token provided"));
|
if (!accessToken) return next(new Error("No access token provided"));
|
||||||
const jwt_secret = process.env.JWT_SECRET as string;
|
const jwt_secret = process.env.JWT_SECRET as string;
|
||||||
try {
|
try {
|
||||||
const decoded = jwt.verify(accessToken, jwt_secret) as UserPayload;
|
const decoded = jwt.verify(accessToken, jwt_secret) as UserPayload;
|
||||||
|
|
||||||
const mailExistance = await existingUserData(decoded.email, decoded.organization);
|
const mailExistance = await existingUserData(decoded.email, decoded.organization);
|
||||||
if (!mailExistance) {
|
if (!mailExistance) {
|
||||||
return next(new Error("Unauthorized user - not in system"));
|
return next(new Error("Unauthorized user - not in system"));
|
||||||
}
|
}
|
||||||
|
|
||||||
(socket as any).user = decoded;
|
(socket as any).user = decoded;
|
||||||
return next();
|
return next();
|
||||||
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
if (err.name === "TokenExpiredError") {
|
if (err.name === "TokenExpiredError") {
|
||||||
if (!refreshToken) {
|
if (!refreshToken) {
|
||||||
return next(new Error("Token expired and no refresh token provided"));
|
return next(new Error("Token expired and no refresh token provided"));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const refreshSecret = process.env.REFRESH_JWT_SECRET as string;
|
const refreshSecret = process.env.REFRESH_JWT_SECRET as string;
|
||||||
const decodedRefresh = jwt.verify(refreshToken, refreshSecret) as UserPayload;
|
const decodedRefresh = jwt.verify(refreshToken, refreshSecret) as UserPayload;
|
||||||
const mailExistance = await existingUserData(decodedRefresh.email, decodedRefresh.organization);
|
const mailExistance = await existingUserData(decodedRefresh.email, decodedRefresh.organization);
|
||||||
|
|
||||||
if (!mailExistance) {
|
if (!mailExistance) {
|
||||||
return next(new Error("Unauthorized user - not in system"));
|
return next(new Error("Unauthorized user - not in system"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate new access token
|
// Generate new access token
|
||||||
const newAccessToken = jwt.sign(
|
const newAccessToken = jwt.sign(
|
||||||
{ email: decodedRefresh.email, organization: decodedRefresh.organization },
|
{ email: decodedRefresh.email, organization: decodedRefresh.organization },
|
||||||
jwt_secret,
|
jwt_secret,
|
||||||
{ expiresIn: "3h" } // adjust expiry
|
{ expiresIn: "3h" } // adjust expiry
|
||||||
);
|
);
|
||||||
|
|
||||||
socket.emit("newAccessToken", newAccessToken);
|
socket.emit("newAccessToken", newAccessToken);
|
||||||
|
|
||||||
(socket as any).user = decodedRefresh;
|
(socket as any).user = decodedRefresh;
|
||||||
return next();
|
return next();
|
||||||
} catch (refreshErr) {
|
} catch (refreshErr) {
|
||||||
return next(new Error("Refresh token expired or invalid"));
|
return next(new Error("Refresh token expired or invalid"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return next(new Error("Invalid token"));
|
return next(new Error("Invalid token"));
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return next(new Error("Authentication error"));
|
return next(new Error("Authentication error"));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
namespace.on("connection", (socket: Socket) => {
|
namespace.on("connection", (socket: Socket) => {
|
||||||
const user = (socket as any).user as UserPayload;
|
const user = (socket as any).user as UserPayload;
|
||||||
const { organization, userId } = user;
|
const { organization, userId } = user;
|
||||||
|
|
||||||
if (!onlineUsers[organization]) onlineUsers[organization] = new Set();
|
if (!onlineUsers[organization]) onlineUsers[organization] = new Set();
|
||||||
onlineUsers[organization].add(socket.id);
|
onlineUsers[organization].add(socket.id);
|
||||||
|
|
||||||
if (!connectedUsersByOrg[organization]) connectedUsersByOrg[organization] = [];
|
if (!connectedUsersByOrg[organization]) connectedUsersByOrg[organization] = [];
|
||||||
connectedUsersByOrg[organization].push({ socketId: socket.id, userId, organization });
|
connectedUsersByOrg[organization].push({ socketId: socket.id, userId, organization });
|
||||||
console.log(`✅ Connected to namespace ${nspName}: ${socket.id}`);
|
console.log(`✅ Connected to namespace ${nspName}: ${socket.id}`);
|
||||||
|
|
||||||
// Common event handler
|
// Common event handler
|
||||||
socket.onAny((event: string, data: any, callback: any) => {
|
socket.onAny((event: string, data: any, callback: any) => {
|
||||||
const handler = eventHandlerMap[event];
|
const handler = eventHandlerMap[event];
|
||||||
if (handler) {
|
if (handler) {
|
||||||
handler(event, socket, io, data, connectedUsersByOrg, callback);
|
handler(event, socket, io, data, connectedUsersByOrg, callback);
|
||||||
} else {
|
} else {
|
||||||
console.warn(` No handler found for event: ${event}`);
|
console.warn(` No handler found for event: ${event}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("disconnect", () => {
|
socket.on("disconnect", () => {
|
||||||
onlineUsers[organization]?.delete(socket.id);
|
onlineUsers[organization]?.delete(socket.id);
|
||||||
if (onlineUsers[organization]?.size === 0) {
|
if (onlineUsers[organization]?.size === 0) {
|
||||||
delete onlineUsers[organization];
|
delete onlineUsers[organization];
|
||||||
}
|
}
|
||||||
connectedUsersByOrg[organization] = connectedUsersByOrg[organization]?.filter(
|
connectedUsersByOrg[organization] = connectedUsersByOrg[organization]?.filter(
|
||||||
(u) => u.socketId !== socket.id
|
(u) => u.socketId !== socket.id
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return io;
|
return io;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,104 +1,104 @@
|
|||||||
import { Socket, Server } from "socket.io";
|
import { Socket, Server } from "socket.io";
|
||||||
|
|
||||||
interface EmitOptions {
|
interface EmitOptions {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
data?: any;
|
data?: any;
|
||||||
error?: any;
|
error?: any;
|
||||||
organization: string;
|
organization: string;
|
||||||
socketId: string;
|
socketId: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const emitEventResponse = (
|
export const emitEventResponse = (
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
organization: string,
|
organization: string,
|
||||||
event: string,
|
event: string,
|
||||||
result: EmitOptions
|
result: EmitOptions
|
||||||
) => {
|
) => {
|
||||||
if (!organization) {
|
if (!organization) {
|
||||||
console.log(`Organization missing in response for event: ${event}`);
|
console.log(`Organization missing in response for event: ${event}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.to(organization).emit(event, {
|
socket.to(organization).emit(event, {
|
||||||
// success: result.success,
|
// success: result.success,
|
||||||
message: result.message,
|
message: result.message,
|
||||||
data: result.data,
|
data: result.data,
|
||||||
error: result.error,
|
error: result.error,
|
||||||
socketId: result.socketId,
|
socketId: result.socketId,
|
||||||
organization,
|
organization,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const emitToSenderAndAdmins = (
|
export const emitToSenderAndAdmins = (
|
||||||
io: Server,
|
io: Server,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
organization: string,
|
organization: string,
|
||||||
event: string,
|
event: string,
|
||||||
result: EmitOptions,
|
result: EmitOptions,
|
||||||
connectedUsersByOrg: {
|
connectedUsersByOrg: {
|
||||||
[org: string]: { socketId: string; userId: string; role: string }[];
|
[org: string]: { socketId: string; userId: string; role: string }[];
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
|
|
||||||
console.log('result.data: ', result.data);
|
console.log('result.data: ', result.data);
|
||||||
socket.emit(event, {
|
socket.emit(event, {
|
||||||
message: result.message,
|
message: result.message,
|
||||||
data: result.data,
|
data: result.data,
|
||||||
error: result.error,
|
error: result.error,
|
||||||
socketId: result.socketId,
|
socketId: result.socketId,
|
||||||
organization,
|
organization,
|
||||||
});
|
});
|
||||||
socket.to(`${organization}_admins`).emit(event, {
|
socket.to(`${organization}_admins`).emit(event, {
|
||||||
message: result.message,
|
message: result.message,
|
||||||
data: result.data,
|
data: result.data,
|
||||||
error: result.error,
|
error: result.error,
|
||||||
socketId: result.socketId,
|
socketId: result.socketId,
|
||||||
organization,
|
organization,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
// export const emitToRoom = (
|
// export const emitToRoom = (
|
||||||
// io: Server,
|
// io: Server,
|
||||||
// socket: Socket,
|
// socket: Socket,
|
||||||
// room: string,
|
// room: string,
|
||||||
// event: string,
|
// event: string,
|
||||||
// result: EmitOptions
|
// result: EmitOptions
|
||||||
// ) => {
|
// ) => {
|
||||||
// const payload = {
|
// const payload = {
|
||||||
// message: result.message,
|
// message: result.message,
|
||||||
// data: result.data,
|
// data: result.data,
|
||||||
// socketId: result.socketId,
|
// socketId: result.socketId,
|
||||||
// organization: result.organization,
|
// organization: result.organization,
|
||||||
// };
|
// };
|
||||||
|
|
||||||
// console.log("event: ", event);
|
// console.log("event: ", event);
|
||||||
// console.log("payload: ", payload);
|
// console.log("payload: ", payload);
|
||||||
// console.log("room: ", room);
|
// console.log("room: ", room);
|
||||||
// socket.emit(event, payload); // ✅ FIXED: sends to all in room including sender
|
// socket.emit(event, payload); // ✅ FIXED: sends to all in room including sender
|
||||||
// };
|
// };
|
||||||
export const emitToRoom = (
|
export const emitToRoom = (
|
||||||
io: Server,
|
io: Server,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
room: string,
|
room: string,
|
||||||
event: string,
|
event: string,
|
||||||
result: EmitOptions
|
result: EmitOptions
|
||||||
) => {
|
) => {
|
||||||
const payload = {
|
const payload = {
|
||||||
message: result.message,
|
message: result.message,
|
||||||
data: result.data,
|
data: result.data,
|
||||||
socketId: result.socketId,
|
socketId: result.socketId,
|
||||||
organization: result.organization,
|
organization: result.organization,
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("🔥 EMIT TO ROOM:");
|
console.log("🔥 EMIT TO ROOM:");
|
||||||
console.log("➡️ Event: ", event);
|
console.log("➡️ Event: ", event);
|
||||||
console.log("📦 Full result input: ", result); // 👉 what you passed from observer
|
console.log("📦 Full result input: ", result); // 👉 what you passed from observer
|
||||||
console.log("📤 Final payload being emitted: ", payload); // 👉 actual emitted payload
|
console.log("📤 Final payload being emitted: ", payload); // 👉 actual emitted payload
|
||||||
console.log("🏠 Room: ", room);
|
console.log("🏠 Room: ", room);
|
||||||
|
|
||||||
socket.to(room).emit(event, payload);
|
socket.to(room).emit(event, payload);
|
||||||
|
|
||||||
// ✅ Optional: Emit to sender too (if needed)
|
// ✅ Optional: Emit to sender too (if needed)
|
||||||
socket.emit(event, payload);
|
socket.emit(event, payload);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,41 +1,41 @@
|
|||||||
import { Socket, Server } from "socket.io";
|
import { Socket, Server } from "socket.io";
|
||||||
|
|
||||||
export const validateFields = (
|
export const validateFields = (
|
||||||
data: any,
|
data: any,
|
||||||
requiredFields: string[]
|
requiredFields: string[]
|
||||||
): string[] => {
|
): string[] => {
|
||||||
return requiredFields.filter(
|
return requiredFields.filter(
|
||||||
(field) => data[field] === undefined || data[field] === null
|
(field) => data[field] === undefined || data[field] === null
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ErrorResponse = (
|
export const ErrorResponse = (
|
||||||
missingFields: string[],
|
missingFields: string[],
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
organization: string
|
organization: string
|
||||||
) => ({
|
) => ({
|
||||||
success: false,
|
success: false,
|
||||||
message: `Missing required field(s): ${missingFields.join(", ")}`,
|
message: `Missing required field(s): ${missingFields.join(", ")}`,
|
||||||
status: "MissingFields",
|
status: "MissingFields",
|
||||||
socketId: socket.id,
|
socketId: socket.id,
|
||||||
organization: organization ?? "unknown",
|
organization: organization ?? "unknown",
|
||||||
});
|
});
|
||||||
|
|
||||||
export const FinalResponse = (
|
export const FinalResponse = (
|
||||||
status: string,
|
status: string,
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
organization: string,
|
organization: string,
|
||||||
messages: Record<string, { message: string }>,
|
messages: Record<string, { message: string }>,
|
||||||
data?: any
|
data?: any
|
||||||
) => {
|
) => {
|
||||||
const msg = messages[status] || { message: "Internal server error" };
|
const msg = messages[status] || { message: "Internal server error" };
|
||||||
const includeData = (status === "Success" || status === "updated") && data;
|
const includeData = (status === "Success" || status === "updated") && data;
|
||||||
return {
|
return {
|
||||||
success: status === "Success" || status === "updated",
|
success: status === "Success" || status === "updated",
|
||||||
message: msg.message,
|
message: msg.message,
|
||||||
status,
|
status,
|
||||||
socketId: socket.id,
|
socketId: socket.id,
|
||||||
organization,
|
organization,
|
||||||
...(includeData ? { data } : {}),
|
...(includeData ? { data } : {}),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user