Merge branch 'branch-1' into branch-v2

This commit is contained in:
2025-05-26 15:13:00 +05:30
114 changed files with 4648 additions and 2462 deletions

View File

@@ -0,0 +1,24 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "./userAuthModel.ts";
export interface Token extends Document {
userId: User["_id"];
isArchive: Boolean;
refreshToken: string;
resetTokenExpiry?: Date;
resetToken: string;
}
const tokenSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
isArchive: { type: Boolean, default: false },
token: { type: String },
refreshToken: { type: String },
tokenCreatedAt: { type: Date },
resetToken: { type: String },
resetTokenExpiry: { type: Date },
});
const tokenType = (db: any) => {
return MainModel(db, "Token", tokenSchema, "Token");
};
export default tokenType;

View File

@@ -0,0 +1,49 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "./userAuthModel.ts";
export interface UserData extends Document {
userId: User["_id"];
isShare: Boolean;
activeStatus: string;
notificationEnable: boolean;
About: string;
isArchive: boolean;
role: string;
profilePicture: string;
recentlyViewed: string[];
}
const UserDataSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
isArchive: { type: Boolean, default: false },
notificationEnable: { type: Boolean, default: false },
About: {
type: String,
},
role: {
type: String,
default: "User",
enum: ["User", "Admin"],
},
isShare: {
type: Boolean,
default: false,
},
activeStatus: {
type: String,
enum: ["online", "offline"],
default: "offline",
},
recentlyViewed: {
type: [String],
default: [],
},
profilePicture: {
type: String,
// default: "default-profile-picture.jpg"
},
});
const UsersDataModel = (db: any) => {
return MainModel(db, "UsersData", UserDataSchema, "UsersData");
};
export default UsersDataModel;

View File

@@ -0,0 +1,34 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface User extends Document {
userName: string;
Email: string;
Password: string;
isArchive: boolean;
visitorBrowserID: string;
lastPasswordReset: number;
}
const AuthSchema: Schema = new Schema({
userName: {
type: String,
required: true,
},
Email: {
type: String,
unique: true,
required: true,
},
Password: {
type: String,
min: 8,
// required: true,
},
isArchive: { type: Boolean, default: false },
lastPasswordReset: { type: Number },
visitorBrowserID: { type: String },
});
const AuthModel = (db: any) => {
return MainModel(db, "UserAuth", AuthSchema, "UserAuth");
};
export default AuthModel;

View File

@@ -0,0 +1,71 @@
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
interface ICommonBase {
type: string;
}
interface IPointsConveyor extends ICommonBase {
points?: {
Uuid: string;
position: [number, number, number];
rotation: [number, number, number];
}[];
}
interface IPoint extends ICommonBase {
point?: {
Uuid: string;
position: [number, number, number];
rotation: [number, number, number];
};
}
export interface AssetData extends Document {
userId: User["_id"];
projectId: Project["_id"];
versionId: Version["_id"];
modelUuid: string;
modelfileID: string;
modelName: string;
isLocked: boolean;
type: string;
isVisible: boolean;
isArchive: false;
// points: [] | {};
position: [];
rotation: {
x: number;
y: number;
z: number;
};
speed: number | string;
eventData: IPoint | IPointsConveyor;
}
const assetDataSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
isArchive: { type: Boolean, default: false },
modelUuid: { type: String },
modelfileID: { type: String },
modelName: { type: String },
type: { type: String },
position: { type: Array },
rotation: {
x: { type: Number },
y: { type: Number },
z: { type: Number },
},
speed: { type: Schema.Types.Mixed },
isLocked: { type: Boolean },
isVisible: { type: Boolean },
eventData: {
type: Schema.Types.Mixed,
},
});
const assetModel = (db: string) => {
return MainModel(db, "Assets", assetDataSchema, "Assets");
};
export default assetModel;

View File

@@ -0,0 +1,51 @@
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
export interface Camera extends Document {
userId: User["_id"];
projectId: Project["_id"];
versionId: Version["_id"];
position: {
x: number;
y: number;
z: number;
};
target: {
x: { type: Number; required: true };
y: { type: Number; required: true };
z: { type: Number; required: true };
};
rotation: {
x: { type: Number; required: true };
y: { type: Number; required: true };
z: { type: Number; required: true };
};
}
const cameraSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
position: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true },
},
target: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true },
},
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true },
},
});
const cameraModel = (db: string) => {
return MainModel(db, "Camera", cameraSchema, "Camera");
};
export default cameraModel;

View File

@@ -0,0 +1,29 @@
import mongoose, { Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
const positionSchema = new mongoose.Schema({
x: { type: Number }, // Optional position fields
y: { type: Number },
z: { type: Number },
});
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false }, // Optional position
uuid: { type: String, required: false }, // Optional uuid
});
const LineSchema = new mongoose.Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
layer: { type: Number, required: true }, // Layer is mandatory
line: { type: [Vector3], required: true }, // Array of line objects
type: { type: String, required: false }, // Optional type
});
const lineModel = (db: string) => {
return MainModel(db, "lines", LineSchema, "lines");
};
export default lineModel;

View File

@@ -0,0 +1,37 @@
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
export interface WallItems extends Document {
userId: User["_id"];
projectId: Project["_id"];
versionId: Version["_id"];
modelUuid: string;
modelName: string;
type: string;
csgposition: [];
csgscale: [];
position: [];
quaternion: [];
scale: [];
}
const wallItemsSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
modelUuid: { type: String, unique: true },
modelName: { type: String },
type: { type: String },
csgposition: { type: Array },
csgscale: { type: Array },
position: { type: Array },
quaternion: { type: Array },
scale: { type: Array },
});
const wallItemModel = (db: string) => {
return MainModel(db, "wallitems", wallItemsSchema, "wallitems");
};
export default wallItemModel;

View File

@@ -0,0 +1,50 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
export interface Zone extends Document {
zoneName: string;
zoneId: string;
zonePoints: [];
viewPortCenter: [];
viewPortposition: [];
isArchive: boolean;
panelOrder: string[];
lockedPanel: string[];
createdBy: User["_id"];
projectId: Project["_id"];
versionId: Version["_id"];
layer: number;
}
const zoneSchema: Schema = new Schema(
{
zoneName: { type: String },
zoneId: { type: String },
createdBy: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
layer: { type: Number },
points: { type: Array },
isArchive: { type: Boolean, default: false },
panelOrder: {
type: [String],
enum: ["left", "right", "top", "bottom"],
},
viewPortCenter: { type: Array, required: true },
viewPortposition: { type: Array, required: true },
lockedPanel: {
type: [String],
default: [],
enum: ["left", "right", "top", "bottom"],
},
// createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
// sceneID: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" },
},
{ timestamps: true }
);
const zoneModel = (db: any) => {
return MainModel(db, "zones", zoneSchema, "zones");
};
export default zoneModel;

View File

@@ -0,0 +1,25 @@
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
export interface Environment extends Document {
userId: User["_id"];
roofVisibility: boolean;
wallVisibility: boolean;
renderDistance: number;
shadowVisibility: boolean;
limitDistance: boolean;
}
const environmentSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User", unique: true },
roofVisibility: { type: Boolean, default: false },
wallVisibility: { type: Boolean, default: false },
shadowVisibility: { type: Boolean, default: false },
renderDistance: { type: Number, default: 40 },
limitDistance: { type: Boolean, default: true },
});
const environmentModel = (db: string) => {
return MainModel(db, "Environment", environmentSchema, "Environment");
};
export default environmentModel;

View File

@@ -0,0 +1,39 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
export interface Project extends Document {
projectUuid: string;
projectName: string;
createdBy: User["_id"];
isArchive: boolean;
isDeleted: boolean;
thumbnail: string;
sharedUsers: [];
DeletedAt: Date;
isViewed: number;
total_versions: string;
Present_version: string;
}
const projectSchema: Schema = new Schema(
{
projectUuid: { type: String },
projectName: { type: String },
thumbnail: { type: String },
isArchive: { type: Boolean, default: false },
createdBy: { type: Schema.Types.ObjectId, ref: "user" },
sharedUsers: [{ type: Schema.Types.ObjectId, ref: "user" }],
DeletedAt: { type: Date, default: null },
isDeleted: { type: Boolean, default: false },
isViewed: { type: Number },
total_versions: { type: String },
Present_version: { type: String },
},
{ timestamps: true }
);
const projectModel = (db: string) => {
return MainModel(db, "Projects", projectSchema, "Projects");
};
export default projectModel;

View File

@@ -0,0 +1,52 @@
import mongoose, { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface IShare extends Document {
Createdby: {
userId: mongoose.Types.ObjectId;
Email: string;
};
isActive: boolean;
Share_People: [
{
userId: mongoose.Types.ObjectId;
Email: string;
AccessPoint: string;
}
];
Description: string;
createdAt: number;
projectId: mongoose.Types.ObjectId;
}
const shareSchema: Schema = new Schema({
CreatedBy: {
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
Email: { type: String, ref: "User", required: true },
},
isActive: { type: Boolean, default: false },
Share_People: [
{
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
Email: { type: String, ref: "User", required: true },
AccessPoint: {
type: String,
default: "Can view",
enum: ["Can view", "Can edit", "Can comment"],
},
},
],
createdAt: {
type: Number,
default: Date.now(),
},
projectId: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" },
});
const shareModel = (db: any) => {
return MainModel(db, "Shared", shareSchema, "Shared");
};
export default shareModel;

View File

@@ -0,0 +1,182 @@
// models/Product.ts
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
interface AssetEventSchema {
modelUuid: string;
modelName: string;
position: [number, number, number];
rotation: [number, number, number];
state: "idle" | "running" | "stopped" | "disabled" | "error";
}
interface TriggerSchema {
triggerUuid: string;
triggerName: string;
triggerType: "onComplete" | "onStart" | "onStop" | "delay" | "onError";
delay: number;
triggeredAsset: {
triggeredModel: { modelName: string; modelUuid: string };
triggeredPoint: { pointName: string; pointUuid: string };
triggeredAction: { actionName: string; actionUuid: string };
} | null;
}
interface ConveyorPointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "default" | "spawn" | "swap" | "despawn";
material: string;
delay: number | "inherit";
spawnInterval: number | "inherit";
spawnCount: number | "inherit";
triggers: TriggerSchema[];
};
}
interface VehiclePointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "travel";
material: string | null;
unLoadDuration: number;
loadCapacity: number;
pickUpPoint: { x: number; y: number; z: number } | null;
unLoadPoint: { x: number; y: number; z: number } | null;
triggers: TriggerSchema[];
};
}
interface RoboticArmPointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
actions: {
actionUuid: string;
actionName: string;
actionType: "pickAndPlace";
process: {
startPoint: [number, number, number];
endPoint: [number, number, number];
};
triggers: TriggerSchema[];
}[];
}
interface MachinePointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "process";
processTime: number;
swapMaterial: string;
triggers: TriggerSchema[];
};
}
interface StoragePointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "storage";
materials: { materialName: string; materialId: string }[];
storageCapacity: number;
};
}
interface ConveyorEventSchema extends AssetEventSchema {
type: "transfer";
speed: number;
points: ConveyorPointSchema[];
}
interface VehicleEventSchema extends AssetEventSchema {
type: "vehicle";
speed: number;
point: VehiclePointSchema;
}
interface RoboticArmEventSchema extends AssetEventSchema {
type: "roboticArm";
speed: number;
point: RoboticArmPointSchema;
}
interface MachineEventSchema extends AssetEventSchema {
type: "machine";
// speed: number;
point: MachinePointSchema;
}
interface StorageEventSchema extends AssetEventSchema {
type: "storageUnit";
// speed: number;
point: StoragePointSchema;
}
interface IPointModel extends Document {
modelUuid: String;
modelName: String;
position: String;
rotation: String;
state: String;
productId: String;
isArchive: boolean;
type: "transfer" | "vehicle" | "roboticArm" | "machine" | "storageUnit";
speed: number;
point:
| VehicleEventSchema
| RoboticArmEventSchema
| MachineEventSchema
| StorageEventSchema;
points: ConveyorEventSchema[];
}
// type EventsSchema = ConveyorEventSchema | VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema;
const BaseEventSchema = new Schema<IPointModel>(
{
modelUuid: { type: String, required: true },
modelName: { type: String, required: true },
position: { type: [Number], required: true },
rotation: { type: [Number], required: true },
speed: { type: Number },
state: {
type: String,
enum: ["idle", "running", "stopped", "disabled", "error"],
default: "idle",
},
type: {
type: String,
required: true,
enum: ["transfer", "vehicle", "roboticArm", "machine", "storageUnit"],
},
point: {
type: Schema.Types.Mixed,
},
points: {
type: Schema.Types.Mixed,
},
productId: { type: String, required: true },
isArchive: { type: Boolean, default: false },
},
{ discriminatorKey: "type", timestamps: true }
);
const EventsDataModel = (db: string) => {
return MainModel(db, "EventDatas", BaseEventSchema, "EventDatas");
};
export default EventsDataModel;

View File

@@ -0,0 +1,26 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
export interface Product extends Document {
productName: string;
productId: string;
projectId: Project["_id"];
versionId: Version["_id"];
eventsData: [];
isArchive: boolean;
}
const ProductSchema = new Schema({
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
productName: { type: String, required: true },
productId: { type: String, required: true },
isArchive: { type: Boolean, default: false },
});
const ProductModel = (db: string) => {
return MainModel(db, "Product", ProductSchema, "Product");
};
export default ProductModel;

View File

@@ -0,0 +1,27 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { Project } from "../Project/project-model.ts";
import { User } from "../Auth/userAuthModel.ts";
export interface Version extends Document {
versionName: string;
projectId: Project["_id"];
createdBy: User["_id"];
isArchive: boolean;
version: number;
}
const versionSchema: Schema = new Schema(
{
versionName: { type: String },
version: { type: Number },
isArchive: { type: Boolean, default: false },
projectId: { type: Schema.Types.ObjectId, ref: "project" },
createdBy: { type: Schema.Types.ObjectId, ref: "user" },
},
{ timestamps: true }
);
const versionModel = (db: string) => {
return MainModel(db, "Versions", versionSchema, "Versions");
};
export default versionModel;

View File

@@ -0,0 +1,37 @@
import { Schema, Document, model } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { Zone } from "../Builder/zoneModel.ts";
export interface Widget3d extends Document {
type: string;
widgetID: string;
widgetName: string;
position: [];
rotation: [];
isArchive: boolean;
zoneId: string;
Data: {
measurements: {};
duration: string;
};
}
const Widget3dSchema: Schema = new Schema(
{
type: { type: String },
widgetID: { type: String },
widgetName: { type: String, default: "Widget3D" },
position: { type: Array },
rotation: { type: Array },
zoneId: { type: String },
Data: {
measurements: { type: Object, default: {} },
duration: { type: String, default: "1h" },
},
isArchive: { type: Boolean, default: false },
},
{ timestamps: true }
);
const widget3dModel = (db: any) => {
return MainModel(db, "3dWidget", Widget3dSchema, "3dWidget");
};
export default widget3dModel;

View File

@@ -0,0 +1,46 @@
import { Schema, Document, model } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { Zone } from "../Builder/zoneModel.ts";
export interface FloatingWidget extends Document {
className: string;
iconName: string;
header: string;
floatWidgetID: string;
position: {};
per: string;
value: string;
isArchive: boolean;
zoneId: string;
Data: {
measurements: {};
duration: string;
};
}
const floatingWidgetSchema: Schema = new Schema(
{
className: { type: String },
iconName: { type: String },
header: { type: String },
floatWidgetID: { type: String },
position: { type: Object },
per: { type: String },
value: { type: String },
zoneId: { type: String },
Data: {
measurements: { type: Object, default: {} },
duration: { type: String, default: "1h" },
},
isArchive: { type: Boolean, default: false },
},
{ timestamps: true }
);
const floatWidgetModel = (db: any) => {
return MainModel(
db,
"FloatingWidget",
floatingWidgetSchema,
"FloatingWidget"
);
};
export default floatWidgetModel;

View File

@@ -0,0 +1,23 @@
import mongoose, { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { Zone } from "../Builder/zoneModel.ts";
export interface Panel extends Document {
zoneId: string;
panelName: string;
widgets: [mongoose.Types.ObjectId];
isArchive: boolean;
}
const panelSchema: Schema = new Schema(
{
zoneId: { type: String },
panelName: { type: String },
widgets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Widget" }],
isArchive: { type: Boolean, default: false },
},
{ timestamps: true }
);
const panelModel = (db: any) => {
return MainModel(db, "Panel", panelSchema, "Panel");
};
export default panelModel;

View File

@@ -0,0 +1,39 @@
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
export interface Template extends Document {
userId: User["_id"];
projectId: Project["_id"];
versionId: Version["_id"];
templateName: string;
templateID: string;
snapshot: string;
panelOrder: [];
widgets: [];
floatWidgets: [];
Widgets3D: [];
isArchive: boolean;
}
const templateSchema: Schema = new Schema(
{
userId: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
templateName: { type: String },
templateID: { type: String },
snapshot: { type: String },
panelOrder: { type: Array },
widgets: { type: Array },
floatWidgets: { type: Array },
Widgets3D: { type: Array },
isArchive: { type: Boolean, default: false },
},
{ timestamps: true }
);
const templateModel = (db: any) => {
return MainModel(db, "Template", templateSchema, "Template");
};
export default templateModel;

View File

@@ -0,0 +1,47 @@
import mongoose, { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { Zone } from "../Builder/zoneModel.ts";
export interface widget extends Document {
widgetName: string;
widgetside: string;
widgetID: string;
widgetOrder: string;
elementType: string;
elementColor: string;
fontFamily: string;
fontStyle: string;
fontWeight: string;
isArchive: boolean;
panelID: mongoose.Types.ObjectId;
Data: {
measurements: {};
duration: string;
};
zoneId: string;
}
const widgetSchema: Schema = new Schema(
{
widgetName: { type: String, default: "Widget" },
widgetside: { type: String },
widgetID: { type: String },
widgetOrder: { type: String },
elementType: { type: String },
elementColor: { type: String },
fontFamily: { type: String },
fontStyle: { type: String },
Data: {
measurements: { type: Object, default: {} },
duration: { type: String, default: "1h" },
},
fontWeight: { type: String },
isArchive: { type: Boolean, default: false },
panelID: { type: mongoose.Schema.Types.ObjectId, ref: "Panel" },
zoneId: { type: String },
},
{ timestamps: true }
);
const widgetModel = (db: any) => {
return MainModel(db, "Widget", widgetSchema, "Widget");
};
export default widgetModel;

View File

@@ -0,0 +1,13 @@
import { Response, Request, NextFunction } from "express";
import { AuthenticatedRequest } from "../../shared/utils/token.ts";
type Role = "Admin" | "User";
const authorizedRoles = (...allowedRoles: Role[]) => {
return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
if (!req.user || !allowedRoles.includes(req.user.role as Role)) {
res.status(403).json({ message: "Access Denied" });
return;
}
next();
};
};
export default authorizedRoles;

View File

@@ -1,57 +1,35 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose.ts';
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
// Interface for TypeScript with PascalCase
export interface floorItenms extends Document {
export interface FloorItems extends Document {
modelUuid: string;
modelfileID: string;
modelName: string
isLocked:boolean
isVisible:boolean
position: []
modelName: string;
isLocked: boolean;
isVisible: boolean;
position: [];
rotation: {
x: number;
y: number;
z: number;
};
}
// Define the Mongoose Schema
const floorItemsSchema: Schema = new Schema({
modelUuid: { type: String },
modelfileID: { type: String },
modelName: { type: String },
position: { type: Array},
isLocked:{type:Boolean},
isVisible:{type:Boolean},
position: { type: Array },
isLocked: { type: Boolean },
isVisible: { type: Boolean },
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
z: { type: Number, required: true },
},
});
// Model for MongoDB collection
// const cameraModel = model<Camera>("Camera", cameraSchema);
// export default cameraModel;
// const floorItemsModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<floorItenms>('floorItenms', floorItenmsSchema,`floorItenms`);
// }
// export default floorItemsModel;
const floorItemsModel = (db:string) => {
return MainModel(db, "floorItems", floorItemsSchema, "floorItems")
const floorItemsModel = (db: string) => {
return MainModel(db, "floorItems", floorItemsSchema, "floorItems");
};
export default floorItemsModel;
export default floorItemsModel;

View File

@@ -1,48 +0,0 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose.ts';
// Interface for TypeScript with PascalCase
export interface wallitems extends Document {
modelUuid: string;
modelName: string
modelfileID: string;
type: string
csgposition: []
csgscale: []
position: []
quaternion: []
scale: []
}
// Define the Mongoose Schema
const wallItemsSchema: Schema = new Schema({
modelUuid: { type: String},
modelfileID: { type: String},
modelName: { type: String},
type: { type: String },
csgposition: { type: Array},
csgscale: { type: Array,},
position: { type: Array },
quaternion: { type: Array},
scale: { type: Array}
});
// const wallItenmModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<wallitenms>('wallitenms', wallItenmsSchema, `wallitenms`);
// }
// export default wallItenmModel;
const wallItenmModel = (db:string) => {
return MainModel(db, "wallitems", wallItemsSchema, "wallitems")
};
export default wallItenmModel;

View File

@@ -1,4 +1,4 @@
import mongoose, { Document, Schema } from "mongoose";
import { Document, Schema } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
interface ICommonBase {
@@ -18,7 +18,7 @@ interface IPoint extends ICommonBase {
rotation: [number, number, number];
};
}
export interface assetData extends Document {
export interface AssetData extends Document {
modelUuid: string;
modelfileID: string;
modelName: string;
@@ -43,7 +43,6 @@ const assetDataSchema: Schema = new Schema({
modelfileID: { type: String },
modelName: { type: String },
type: { type: String },
// points: { type: Schema.Types.Mixed },
position: { type: Array },
rotation: {
x: { type: Number },
@@ -58,101 +57,7 @@ const assetDataSchema: Schema = new Schema({
},
});
// export default floorItemsModel;
const assetModel = (db: string) => {
return MainModel(db, "Assets", assetDataSchema, "Assets");
};
export default assetModel;
// import mongoose, { Document, Schema } from "mongoose";
// import MainModel from "../../../connect/mongoose.ts";
// export interface assetData extends Document {
// modelUuid: string;
// modelfileID: string;
// modelName: string;
// isLocked: boolean;
// type: string;
// isVisible: boolean;
// isArchive: false;
// // position: [];
// // rotation: {
// // x: number;
// // y: number;
// // z: number;
// // };
// points: {
// uuid: string;
// position: [];
// rotation: [];
// actions: [mongoose.Types.ObjectId];
// triggers: [mongoose.Types.ObjectId];
// connections: {
// source: {
// modelUUID: string;
// pointUUID: string;
// };
// targets: [
// {
// modelUUID: string;
// pointUUID: string;
// }
// ];
// }[];
// }[];
// position: [];
// // rotation: [];
// rotation: {
// x: number;
// y: number;
// z: number;
// };
// speed: number | string;
// }
// // Define the Mongoose Schema
// const assetDataSchema: Schema = new Schema({
// isArchive: { type: Boolean, default: false },
// modelUuid: { type: String },
// modelfileID: { type: String },
// modelName: { type: String },
// type: { type: String },
// // assetPosition: { type: Array },
// points: [
// {
// uuid: { type: String },
// position: { type: Array },
// rotation: { type: Array },
// actions: [{ type: mongoose.Schema.Types.ObjectId, ref: "Actions" }],
// triggers: [{ type: mongoose.Schema.Types.ObjectId, ref: "Triggers" }],
// connections: {
// source: {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// targets: [
// {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// ],
// },
// },
// ],
// position: { type: Array },
// // rotation: { type: Array},
// rotation: {
// x: { type: Number },
// y: { type: Number },
// z: { type: Number },
// },
// speed: { type: Schema.Types.Mixed },
// isLocked: { type: Boolean },
// isVisible: { type: Boolean },
// });
// // export default floorItemsModel;
// const assetModel = (db: string) => {
// return MainModel(db, "Assets", assetDataSchema, "Assets");
// };
// export default assetModel;

View File

@@ -1,31 +1,6 @@
import mongoose, { Schema, Document } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
// Common Interfaces
// interface ITriggerConveyor {
// uuid: string;
// name: string;
// type: string;
// isUsed: boolean;
// bufferTime: number;
// }
// interface ITriggerVehicle {
// uuid: string;
// name: string;
// type: string;
// isUsed: boolean;
// }
// interface IConnectionConveyor {
// source: { modelUUID: string; pointUUID: string };
// targets: { modelUUID: string; pointUUID: string }[];
// }
// interface IConnectionVehicle {
// source: { modelUUID: string; pointUUID: string };
// targets: { modelUUID: string; pointUUID: string }[];
// }
// Point Types
interface IPointBase {
uuid: string;
position: number[];
@@ -127,322 +102,8 @@ const PointSchema = new Schema<IPointModel>(
{ timestamps: true }
);
// Model Creation
const pointModel = (db: string) => {
return MainModel(db, "Points", PointSchema, "Points");
};
export default pointModel;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// import mongoose, { Schema, Document } from "mongoose";
// import MainModel from "../../../connect/mongoose.ts";
// interface IActionConveyor {
// uuid: string;
// name: string;
// type: string;
// material: string;
// delay: number | string;
// spawnInterval: number | string;
// spawnMaterial: string;
// isUsed: boolean;
// hitCount: number;
// start: string;
// end: string;
// buffer: number;
// }
// interface ITriggers {
// uuid: string;
// name: string;
// type: string;
// isUsed: boolean;
// bufferTime: number;
// }
// interface IConnection {
// source: { modelUUID: string; pointUUID: string };
// targets: { modelUUID: string; pointUUID: string }[];
// }
// interface IActionVehicle {
// uuid: string;
// name: string;
// type: string;
// isUsed: boolean;
// hitCount: number;
// start: string;
// end: string;
// buffer: number;
// }
// interface IPointConveyor {
// uuid: string;
// position: number[];
// rotation: number[];
// actions: IActionConveyor[];
// triggers: ITriggers[];
// connections: IConnection;
// }
// interface IPointVehicle {
// uuid: string;
// position: number[];
// actions: IActionVehicle[];
// triggers: ITriggers[];
// connections: IConnection;
// }
// interface IBaseModel extends Document {
// modelfileID: string;
// type: "Conveyor" | "Vehicle";
// points: IPointConveyor[] | IPointVehicle;
// }
// const PointconveyorSchema = new Schema<IPointConveyor>({
// uuid: { type: String, required: true },
// position: { type: [Number] },
// rotation: { type: [Number] },
// actions: [
// {
// uuid: { type: String, default: "" },
// name: { type: String },
// type: { type: String },
// material: { type: String },
// delay: { type: Schema.Types.Mixed },
// spawnInterval: { type: Schema.Types.Mixed },
// spawnMaterial: { type: String },
// isUsed: { type: Boolean },
// },
// ],
// triggers: [
// {
// uuid: { type: String, default: "" },
// name: { type: String },
// type: { type: String },
// bufferTime: { type: Number },
// isUsed: { type: Boolean },
// },
// ],
// connections: {
// source: {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// targets: [
// {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// ],
// },
// });
// const PointvehicleSchema = new Schema<IPointVehicle>({
// uuid: { type: String, required: true },
// position: { type: [Number] },
// actions: [
// {
// uuid: { type: String, default: "" },
// name: { type: String },
// type: { type: String },
// isUsed: { type: Boolean },
// hitCount: { type: String },
// start: { type: String },
// end: { type: String },
// buffer: { type: String },
// },
// ],
// triggers: [
// {
// uuid: { type: String, default: "" },
// name: { type: String },
// type: { type: String },
// bufferTime: { type: Number },
// isUsed: { type: Boolean },
// },
// ],
// connections: {
// source: {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// targets: [
// {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// ],
// },
// });
// const BaseSchema = new Schema<IBaseModel>(
// {
// modelfileID: { type: String },
// type: { type: String, enum: ["Conveyor", "Vehicle"] },
// points: {
// type: Schema.Types.Mixed,
// required: true,
// },
// },
// { discriminatorKey: "type", timestamps: true }
// );
// const pointModel = (db: string) => {
// const BasePointModel = MainModel(db, "Points", BaseSchema, "Points");
// const ConveyorModel = BasePointModel.discriminator(
// "Conveyor",
// new Schema({
// points: [PointconveyorSchema],
// })
// );
// const VehicleModel = BasePointModel.discriminator(
// "Vehicle",
// new Schema({
// points: PointvehicleSchema,
// })
// );
// return { ConveyorModel, VehicleModel };
// };
// export default pointModel;
// ===
// const pointModel = (db: string) => {
// const BasePointModel =
// mongoose.models.Points || MainModel(db, "Points", BaseSchema, "Points");
// if (!BasePointModel.discriminators?.Conveyor) {
// BasePointModel.discriminator(
// "Conveyor",
// new Schema({
// points: [PointconveyorSchema],
// })
// );
// }
// if (!BasePointModel.discriminators?.Vehicle) {
// BasePointModel.discriminator(
// "Vehicle",
// new Schema({
// points: PointvehicleSchema,
// })
// );
// }
// const ConveyorModel =
// mongoose.models.Conveyor || BasePointModel.discriminators?.Conveyor;
// const VehicleModel =
// mongoose.models.Vehicle || BasePointModel.discriminators?.Vehicle;
// return { ConveyorModel, VehicleModel, BasePointModel };
// };
// export default pointModel;
// ===========================================
// ===
// import mongoose, { Schema, Document } from "mongoose";
// import MainModel from "../../../connect/mongoose.ts";
// interface IAction {
// uuid: string;
// name: string;
// type: string;
// material: string;
// delay: number | string;
// spawnInterval: number | string;
// spawnMaterial: string;
// isUsed: boolean;
// hitCount: number;
// start: string;
// end: string;
// buffer: number;
// }
// interface ITriggers {
// uuid: string;
// name: string;
// type: string;
// isUsed: boolean;
// bufferTime: number;
// }
// interface IConnection {
// source: { modelUUID: string; pointUUID: string };
// targets: { modelUUID: string; pointUUID: string }[];
// }
// interface IPoint {
// uuid: string;
// position: number[];
// rotation: number[];
// actions: IAction[];
// triggers: ITriggers[];
// connections: IConnection;
// }
// interface IBaseModel extends Document {
// modelfileID: string;
// type: "Conveyor" | "Vehicle";
// points: IPoint[] | IPoint;
// }
// const PointSchema = new Schema<IPoint>({
// uuid: { type: String, required: true },
// position: { type: [Number] },
// rotation: { type: [Number] },
// actions: [
// {
// uuid: { type: String, default: "" },
// name: { type: String },
// type: { type: String },
// material: { type: String },
// delay: { type: String },
// spawnInterval: { type: String },
// spawnMaterial: { type: String },
// isUsed: { type: Boolean },
// hitCount: { type: String },
// start: { type: String },
// end: { type: String },
// buffer: { type: String },
// },
// ],
// triggers: [
// {
// uuid: { type: String, default: "" },
// name: { type: String },
// type: { type: String },
// bufferTime: { type: Number },
// isUsed: { type: Boolean },
// },
// ],
// connections: {
// source: {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// targets: [
// {
// modelUUID: { type: String },
// pointUUID: { type: String },
// },
// ],
// },
// });
// // Base Schema
// const BaseSchema = new Schema<IBaseModel>(
// {
// modelfileID: { type: String },
// type: { type: String, enum: ["Conveyor", "Vehicle"] },
// points: {
// type: Schema.Types.Mixed,
// required: true,
// },
// },
// { discriminatorKey: "type", timestamps: true }
// );
// const pointModel = (db: string) => {
// return MainModel(db, "Points", BaseSchema, "Points");
// };
// export default pointModel;

View File

@@ -1,7 +1,6 @@
import mongoose, { Document, Schema } from "mongoose";
import { Document, Schema } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
// Interface for TypeScript with PascalCase
export interface wallitems extends Document {
export interface WallItems extends Document {
modelUuid: string;
modelName: string;
type: string;
@@ -12,7 +11,6 @@ export interface wallitems extends Document {
scale: [];
}
// Define the Mongoose Schema
const wallItemsSchema: Schema = new Schema({
modelUuid: { type: String, unique: true },
modelName: { type: String },
@@ -24,8 +22,7 @@ const wallItemsSchema: Schema = new Schema({
scale: { type: Array },
});
// export default wallItenmModel;
const wallItenmModel = (db: string) => {
const wallItemModel = (db: string) => {
return MainModel(db, "wallitems", wallItemsSchema, "wallitems");
};
export default wallItenmModel;
export default wallItemModel;

View File

@@ -1,7 +1,6 @@
import mongoose, { Document, Schema } from "mongoose";
import { Document, Schema } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
// Interface for TypeScript with PascalCase
export interface Camera extends Document {
userId: string;
position: {
@@ -21,7 +20,6 @@ export interface Camera extends Document {
};
}
// Define the Mongoose Schema
const cameraSchema: Schema = new Schema({
userId: { type: String },
position: {
@@ -41,7 +39,6 @@ const cameraSchema: Schema = new Schema({
},
});
// export default cameraModel
const cameraModel = (db: string) => {
return MainModel(db, "Camera", cameraSchema, "Camera");
};

View File

@@ -1,24 +0,0 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../../connect/mongoose.ts';
// Interface for TypeScript with PascalCase
export interface environment extends Document {
userId: string;
roofVisibility: boolean
wallVisibility: boolean
}
// Define the Mongoose Schema
const environmentSchema: Schema = new Schema({
userId: { type: String, unique: true },
roofVisibility: { type: Boolean, default: false },
wallVisibility: { type: Boolean, default: false },
shadowVisibility: { type: Boolean, default: false },
});
// export default environmentModel;
const environmentModel = (db: string) => {
return MainModel(db, "environments", environmentSchema, "environments")
};
export default environmentModel;

View File

@@ -1,4 +1,4 @@
import mongoose, { Document, Schema } from "mongoose";
import mongoose from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
const positionSchema = new mongoose.Schema({
x: { type: Number }, // Optional position fields
@@ -6,20 +6,17 @@ const positionSchema = new mongoose.Schema({
z: { type: Number },
});
// Define a schema for the individual line
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false }, // Optional position
uuid: { type: String, required: false }, // Optional uuid
});
// Define the main schema
const LineSchema = new mongoose.Schema({
layer: { type: Number, required: true }, // Layer is mandatory
line: { type: [Vector3], required: true }, // Array of line objects
type: { type: String, required: false }, // Optional type
});
// export default lineModel;
const lineModel = (db: string) => {
return MainModel(db, "lines", LineSchema, "lines");
};

View File

@@ -1,40 +1,5 @@
// import mongoose, { Schema, Document, model } from "mongoose";
// import MainModel from "../../../connect/mongoose.ts";
// export interface Zone extends Document {
// zoneName: string;
// // zoneUUID: string;
// zonePoints: [];
// centerPoints: [];
// isArchive: boolean;
// createdBy: string;
// sceneID: string;
// // createdBy: mongoose.Types.ObjectId;
// // sceneID: mongoose.Types.ObjectId;
// layer: number;
// }
// const zoneSchema: Schema = new Schema(
// {
// zoneName: { type: String },
// // zoneUUID: { type: String },
// createdBy: { type: String },
// sceneID: { type: String },
// layer: { type: Number },
// centerPoints: { type: Array },
// zonePoints: { type: Array },
// isArchive: { type: Boolean, default: false },
// // createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
// // sceneID: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" },
// },
// { timestamps: true }
// );
// const dataModel = (db: any) => {
// return MainModel(db, "Zones", zoneSchema, "Zones");
// };
// export default dataModel;
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
export interface Zone extends Document {

View File

@@ -1,87 +1,45 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose.ts';
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
// Interface for TypeScript with PascalCase
export interface Camera extends Document {
userId: string;
position: {
x: number;
y: number;
z: number;
}
};
target: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
x: { type: Number; required: true };
y: { type: Number; required: true };
z: { type: Number; required: true };
};
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
x: { type: Number; required: true };
y: { type: Number; required: true };
z: { type: Number; required: true };
};
}
// Define the Mongoose Schema
const cameraSchema: Schema = new Schema({
userId: { type: String },
position: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
z: { type: Number, required: true },
},
target: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
z: { type: Number, required: true },
},
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
z: { type: Number, required: true },
},
});
// Model for MongoDB collection
// const cameraModel = model<Camera>("Camera", cameraSchema);
// export default cameraModel;
// const cameraModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<Camera>('Camera', cameraSchema,`Camera`);
// }
// export default cameraModel;
// const cameraModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db,
// serverSelectionTimeoutMS: 60000, // Increased timeout
// });
// dbConnection.on('error', (err) => {
// console.error(`MongoDB connection error for database ${db}:`, err);
// });
// dbConnection.once('open', () => {
// console.log(`Connected to MongoDB database: ${db}`);
// });
// return dbConnection.model<Camera>('Camera', cameraSchema, 'Camera');
// };
// export default cameraModel
const cameraModel = (db:string) => {
return MainModel(db, "Camera", cameraSchema, "Camera")
const cameraModel = (db: string) => {
return MainModel(db, "Camera", cameraSchema, "Camera");
};
export default cameraModel;
export default cameraModel;

View File

@@ -1,7 +1,7 @@
import mongoose, { Document, Schema } from "mongoose";
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
// Interface for TypeScript with PascalCase
export interface environment extends Document {
export interface Environment extends Document {
userId: string;
roofVisibility: boolean;
wallVisibility: boolean;
@@ -10,7 +10,6 @@ export interface environment extends Document {
limitDistance: boolean;
}
// Define the Mongoose Schema
const environmentSchema: Schema = new Schema({
userId: { type: String, unique: true },
roofVisibility: { type: Boolean, default: false },
@@ -20,24 +19,6 @@ const environmentSchema: Schema = new Schema({
limitDistance: { type: Boolean, default: true },
});
// Model for MongoDB collection
// const cameraModel = model<Camera>("Camera", cameraSchema);
// export default cameraModel;
// const environmentModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<environment>('environments', environmentSchema,`environments`);
// }
// export default environmentModel;
const environmentModel = (db: string) => {
return MainModel(db, "environments", environmentSchema, "environments");
};

View File

@@ -18,7 +18,7 @@ export interface Project extends Document {
const projectSchema: Schema = new Schema(
{
projectUuid: { type: String },
projectName: { type: String },
projectName: { type: String },
thumbnail: { type: String },
isArchive: { type: Boolean, default: false },
createdBy: { type: Schema.Types.ObjectId, ref: "user" },

View File

@@ -1,12 +1,9 @@
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Action extends Document {
pointsUUID: string;
// actionUUID: string;
isArchive: string;
// sceneID: string;
// eventData: {
uuid: string;
name: string;
type: string;
@@ -19,13 +16,11 @@ export interface Action extends Document {
start: string;
end: string;
buffer: number;
// };
}
const actionSchema: Schema = new Schema(
{
pointsUUID: { type: String },
isArchive: { type: Boolean, default: false },
// actionUUID: { type: String },
uuid: { type: String, default: "" },
name: { type: String },
type: { type: String },

View File

@@ -1,179 +1,182 @@
// models/Product.ts
import mongoose, { Schema, Document, Types } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
interface AssetEventSchema {
modelUuid: string;
modelName: string;
position: [number, number, number];
rotation: [number, number, number];
state: "idle" | "running" | "stopped" | "disabled" | "error";
};
modelUuid: string;
modelName: string;
position: [number, number, number];
rotation: [number, number, number];
state: "idle" | "running" | "stopped" | "disabled" | "error";
}
interface TriggerSchema {
triggerUuid: string;
triggerName: string;
triggerType: "onComplete" | "onStart" | "onStop" | "delay" | "onError";
delay: number;
triggeredAsset: {
triggeredModel: { modelName: string, modelUuid: string };
triggeredPoint: { pointName: string, pointUuid: string };
triggeredAction: { actionName: string, actionUuid: string };
} | null;
triggerUuid: string;
triggerName: string;
triggerType: "onComplete" | "onStart" | "onStop" | "delay" | "onError";
delay: number;
triggeredAsset: {
triggeredModel: { modelName: string; modelUuid: string };
triggeredPoint: { pointName: string; pointUuid: string };
triggeredAction: { actionName: string; actionUuid: string };
} | null;
}
interface ConveyorPointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "default" | "spawn" | "swap" | "despawn";
material: string;
delay: number | "inherit";
spawnInterval: number | "inherit";
spawnCount: number | "inherit";
triggers: TriggerSchema[];
};
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "default" | "spawn" | "swap" | "despawn";
material: string;
delay: number | "inherit";
spawnInterval: number | "inherit";
spawnCount: number | "inherit";
triggers: TriggerSchema[];
};
}
interface VehiclePointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "travel";
material: string | null;
unLoadDuration: number;
loadCapacity: number;
pickUpPoint: { x: number; y: number, z: number } | null;
unLoadPoint: { x: number; y: number, z: number } | null;
triggers: TriggerSchema[];
};
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "travel";
material: string | null;
unLoadDuration: number;
loadCapacity: number;
pickUpPoint: { x: number; y: number; z: number } | null;
unLoadPoint: { x: number; y: number; z: number } | null;
triggers: TriggerSchema[];
};
}
interface RoboticArmPointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
actions: {
actionUuid: string;
actionName: string;
actionType: "pickAndPlace";
process: { startPoint: [number, number, number]; endPoint: [number, number, number] };
triggers: TriggerSchema[];
}[];
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
actions: {
actionUuid: string;
actionName: string;
actionType: "pickAndPlace";
process: {
startPoint: [number, number, number];
endPoint: [number, number, number];
};
triggers: TriggerSchema[];
}[];
}
interface MachinePointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "process";
processTime: number;
swapMaterial: string;
triggers: TriggerSchema[];
};
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "process";
processTime: number;
swapMaterial: string;
triggers: TriggerSchema[];
};
}
interface StoragePointSchema {
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "storage";
materials: { materialName: string; materialId: string; }[];
storageCapacity: number;
};
uuid: string;
position: [number, number, number];
rotation: [number, number, number];
action: {
actionUuid: string;
actionName: string;
actionType: "storage";
materials: { materialName: string; materialId: string }[];
storageCapacity: number;
};
}
interface ConveyorEventSchema extends AssetEventSchema {
type: "transfer";
speed: number;
points: ConveyorPointSchema[];
type: "transfer";
speed: number;
points: ConveyorPointSchema[];
}
interface VehicleEventSchema extends AssetEventSchema {
type: "vehicle";
speed: number;
point: VehiclePointSchema;
type: "vehicle";
speed: number;
point: VehiclePointSchema;
}
interface RoboticArmEventSchema extends AssetEventSchema {
type: "roboticArm";
speed: number;
point: RoboticArmPointSchema;
type: "roboticArm";
speed: number;
point: RoboticArmPointSchema;
}
interface MachineEventSchema extends AssetEventSchema {
type: "machine";
// speed: number;
point: MachinePointSchema;
type: "machine";
// speed: number;
point: MachinePointSchema;
}
interface StorageEventSchema extends AssetEventSchema {
type: "storageUnit";
// speed: number;
point: StoragePointSchema;
type: "storageUnit";
// speed: number;
point: StoragePointSchema;
}
interface IPointModel extends Document {
modelUuid:String,
modelName:String,
position:String,
rotation:String,
state:String,
productId:String,
isArchive:boolean,
type: "transfer" | "vehicle" | "roboticArm" | "machine" |"storageUnit";
modelUuid: String;
modelName: String;
position: String;
rotation: String;
state: String;
productId: String;
isArchive: boolean;
type: "transfer" | "vehicle" | "roboticArm" | "machine" | "storageUnit";
speed: number;
point: VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema
points: ConveyorEventSchema[]
point:
| VehicleEventSchema
| RoboticArmEventSchema
| MachineEventSchema
| StorageEventSchema;
points: ConveyorEventSchema[];
}
// type EventsSchema = ConveyorEventSchema | VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema;
const BaseEventSchema = new Schema<IPointModel>(
{
modelUuid: { type: String, required: true },
modelName: { type: String, required: true },
position: { type: [Number], required: true },
rotation: { type: [Number], required: true },
speed: { type: Number,},
state: {
type: String,
enum: ["idle", "running", "stopped", "disabled", "error"],
default: "idle"
},
type: {
type: String,
required: true,
enum: ["transfer", "vehicle", "roboticArm", "machine", "storageUnit"]
},
point:{
type:Schema.Types.Mixed,
},
points:{
type:Schema.Types.Mixed,
},
productId: { type:String,required: true },
isArchive: { type: Boolean, default: false }
{
modelUuid: { type: String, required: true },
modelName: { type: String, required: true },
position: { type: [Number], required: true },
rotation: { type: [Number], required: true },
speed: { type: Number },
state: {
type: String,
enum: ["idle", "running", "stopped", "disabled", "error"],
default: "idle",
},
{ discriminatorKey: "type", timestamps: true }
);
const EventsDataModel = (db: string) => {
return MainModel(db, "EventDatas", BaseEventSchema, "EventDatas");
};
export default EventsDataModel;
type: {
type: String,
required: true,
enum: ["transfer", "vehicle", "roboticArm", "machine", "storageUnit"],
},
point: {
type: Schema.Types.Mixed,
},
points: {
type: Schema.Types.Mixed,
},
productId: { type: String, required: true },
isArchive: { type: Boolean, default: false },
},
{ discriminatorKey: "type", timestamps: true }
);
const EventsDataModel = (db: string) => {
return MainModel(db, "EventDatas", BaseEventSchema, "EventDatas");
};
export default EventsDataModel;

View File

@@ -1,97 +0,0 @@
// import mongoose, { Schema, Document, model } from "mongoose";
// import MainModel from "../../connect/mongoose.ts";
// export interface ProductFlow extends Document {
// productName: string;
// ProductData: [
// {
// AssetName: string;
// Assetuuid: string;
// paths: {
// Points: [
// {
// pointuuid: string;
// actions: [mongoose.Types.ObjectId];
// triggers: [mongoose.Types.ObjectId];
// position: [];
// rotation: [number];
// connections: {
// source: {
// // modelUUID: { type: String };
// pointUUID: string;
// };
// targets: [
// {
// // modelUUID: { type: String };
// pointUUID: string;
// }
// ];
// };
// }
// ];
// // endPoint: {
// // pointuuid: string;
// // actions: [mongoose.Types.ObjectId];
// // triggers: [mongoose.Types.ObjectId];
// // position: [];
// // rotation: [];
// // };
// };
// isArchive: false;
// }
// ];
// isArchive: false;
// }
// const productFlowSchema: Schema = new Schema(
// {
// productName: { type: String },
// ProductData: [
// {
// AssetName: { type: String },
// Assetuuid: { type: String },
// paths: {
// Points: [
// {
// pointuuid: { type: String },
// actions: [
// { type: mongoose.Schema.Types.ObjectId, ref: "Actions" },
// ],
// triggers: [
// { type: mongoose.Schema.Types.ObjectId, ref: "Triggers" },
// ],
// connections: {
// source: {
// // modelUUID: { type: String };
// pointUUID: { type: String },
// },
// targets: [
// {
// // modelUUID: { type: String };
// pointUUID: { type: String },
// },
// ],
// },
// position: { type: Array },
// rotation: {
// type: [Number],
// validate: {
// validator: function (value: number[]) {
// return value && value.length > 0; // Ensures it's only stored if it has values
// },
// message: "Rotation array should not be empty",
// },
// },
// },
// ],
// },
// isArchive: { type: Boolean, default: false },
// },
// ],
// },
// { timestamps: true }
// );
// const productFlowModel = (db: any) => {
// return MainModel(db, "ProductFlow", productFlowSchema, "ProductFlow");
// };
// export default productFlowModel;

View File

@@ -1,24 +1,20 @@
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface product extends Document {
export interface Product extends Document {
productName: string;
productId: string;
eventsData: [];
isArchive: boolean;
}
// Product Schema
const ProductSchema = new Schema({
productName: { type: String, required: true },
productId: { type: String, required: true },
isArchive: { type: Boolean, default: false },
});
const ProductModel = (db: string) => {
return MainModel(db, "Product", ProductSchema, "Product");
};
export default ProductModel;
export default ProductModel;

View File

@@ -1,4 +1,4 @@
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Trigger extends Document {

View File

@@ -1,4 +1,4 @@
import mongoose, { Document, Schema } from "mongoose";
import { Document, Schema } from "mongoose";
import MainModel from "../connect/mongoose.ts";
export interface User extends Document {
userName: String;
@@ -48,24 +48,8 @@ const signupschema: Schema = new Schema({
default: [],
},
});
// const userModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || "";
// if (!mongoUrl) {
// throw new Error("MONGO_URI environment variable is not set");
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// // Return the model
// return dbConnection.model("Users", signupschema, "Users");
// };
// export default userModel;
const userModel = (db: string) => {
return MainModel(db, "Users", signupschema, "Users");
const userModel = (db:string) => {
return MainModel(db, "Users", signupschema, "Users")
};
export default userModel;

View File

@@ -1,4 +1,4 @@
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document, model } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Widget3d extends Document {

View File

@@ -1,7 +1,7 @@
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document, model } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface floatingWidget extends Document {
export interface FloatingWidget extends Document {
className: string;
iconName: string;
header: string;

View File

@@ -1,8 +1,7 @@
import mongoose, { Schema, Document, model } from "mongoose";
import mongoose, { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Panel extends Document {
// zoneId: mongoose.Types.ObjectId;
zoneId: string;
panelName: string;
widgets: [mongoose.Types.ObjectId];
@@ -10,7 +9,6 @@ export interface Panel extends Document {
}
const panelSchema: Schema = new Schema(
{
// zoneId: { type: mongoose.Schema.Types.ObjectId, ref: "Zone" },
zoneId: { type: String },
panelName: { type: String },
widgets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Widget" }],

View File

@@ -1,4 +1,4 @@
import mongoose, { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Template extends Document {

View File

@@ -1,4 +1,4 @@
import mongoose, { Schema, Document, model } from "mongoose";
import mongoose, { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface widget extends Document {

21
src/shared/redis/redis.ts Normal file
View File

@@ -0,0 +1,21 @@
import Redis from "ioredis";
import * as dotenv from "dotenv";
dotenv.config();
const redis = new Redis.default({
host:
process.env.REDIS_ENV === "true"
? process.env.REDIS_DOCKER
: process.env.REDIS_LOCAL,
port: parseInt(process.env.REDIS_PORT || "6379"),
password: "",
db: 0,
});
redis.on("connect", () => {
console.log(`Connected to Redis to ${redis.options.port}`);
});
redis.on("error", (err: unknown) => {
console.error("Redis connection error:", err);
});
export default redis;

View File

@@ -1,38 +0,0 @@
import { Request, Response, NextFunction } from 'express';
import * as Jwt from 'jsonwebtoken'; // Correct way to import jsonwebtoken
// Define a new interface extending Request
interface AuthenticatedRequest extends Request {
user?: {
email: string;
// Add more fields as needed based on your JWT payload
};
}
const tokenGenerator = (email: string) => {
const token = Jwt.sign({ email: email }, "Milestone", {
expiresIn: "3hours",
});
return token;
};
const tokenValidator = (req: AuthenticatedRequest, res: Response, next: NextFunction): void => {
const token: string | undefined = req.headers.token as string | undefined;
if (!token) {
res.status(403).json({
msg: "No token present",
});
return; // Make sure to return after sending a response
}
try {
const decoded = Jwt.verify(token,"Milestone") as { email: string }; // adjust if your JWT payload has more fields
req.user = decoded;
next();
} catch (err) {
res.status(401).json({
msg: "Invalid Token",
});
}
};
export { tokenValidator,tokenGenerator };

View File

@@ -0,0 +1,466 @@
import AuthModel from "../../V1Models/Auth/userAuthModel.ts";
import UsersDataModel from "../../V1Models/Auth/user.ts";
import nodemailer from "nodemailer";
import tokenType from "../../V1Models/Auth/tokenModel.ts";
import Jwt from "jsonwebtoken";
import { hashValidator, hashGenerate } from "../../utils/Hasing.ts";
import redis from "../../redis/redis.ts";
import { tokenGenerator, tokenRefreshGenerator } from "../../utils/token.ts";
interface Iserviceuser {
userName: string;
Email: string;
Password: string;
profilePicture: string;
}
interface IloginUser {
Email: string;
Password: string;
fingerprint: string;
}
interface IresetToken {
resetToken: string;
newPassword: string;
confirmPassword: string;
}
interface IUser {
Email: string;
userName: string;
_id: string;
}
const jwt_secret = process.env.JWT_SECRET as string;
export function extractOrg(Email: string) {
return Email.split("@")[1].split(".")[0];
}
async function findExistingUserEmail(Email: string) {
const organization = extractOrg(Email);
const existingUser = await AuthModel(organization).findOne({
Email: Email,
isArchive: false,
});
return existingUser;
}
export const AuthSignup = async (
data: Iserviceuser
): Promise<{
status: string;
}> => {
const { userName, Email, Password, profilePicture } = data;
try {
let role;
const caseChange = Email.toLowerCase();
const organization = extractOrg(caseChange);
const Existing_User = await findExistingUserEmail(caseChange);
if (Existing_User) {
return { status: "User already exists" };
} else {
const hashPassword = await hashGenerate(Password);
const userCount = await AuthModel(organization).countDocuments({});
role = userCount === 0 ? "Admin" : "User";
const isShare = "true";
const newuser = await AuthModel(organization).create({
userName: userName,
Email: caseChange,
Password: hashPassword,
});
const UserDatas = await UsersDataModel(organization).create({
userId: newuser._id,
role: role,
isShare: isShare,
profilePicture: profilePicture,
});
return { status: "Success" };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const AuthLogin = async (
data: IloginUser
): Promise<{ status: string; data?: Object }> => {
try {
const { Email, Password, fingerprint } = data;
const caseChange = Email.toLowerCase();
const organization = extractOrg(caseChange);
const Existing_User = await findExistingUserEmail(caseChange);
if (!Existing_User) return { status: "User Not Found!!! Kindly signup..." };
else {
const existingMail = await getUserFromCacheOrDB(caseChange);
const checkPassword = await hashValidator(
Password,
existingMail.Password
);
if (!checkPassword)
return {
status: "Email & Password is invalid...Check the credentials",
};
const browserID = existingMail.visitorBrowserID;
if (browserID && browserID !== fingerprint) {
await Promise.all([
redis.del(`token:${caseChange}`),
redis.del(`user:${caseChange}`),
]);
await AuthModel(organization).updateOne(
{ Email: caseChange },
{ visitorBrowserID: "" }
);
await tokenType(organization).updateOne(
{ userId: Existing_User._id },
{ refreshToken: "" }
);
return {
status: "Already LoggedIn on another browser....Please logout!!!",
};
}
const UserData = await UsersDataModel(organization).findOne({
userId: existingMail._id,
isArchive: false,
});
if (!UserData)
return {
status: "User_Datas not found",
};
const redisTokenRaw = await redis.get(`token:${caseChange}`);
if (redisTokenRaw) {
const cachedTokens = JSON.parse(redisTokenRaw);
try {
Jwt.verify(cachedTokens.token, jwt_secret);
return {
status: "Success",
data: {
message: "login successfull",
email: existingMail.Email,
name: existingMail.userName,
userId: existingMail._id,
isShare: UserData.isShare,
token: cachedTokens.token,
refreshToken: cachedTokens.refreshToken,
},
};
} catch (err) {
console.log("Access token expired. Generating new...");
}
}
const tokenValidation = tokenGenerator(
existingMail.Email,
UserData.role,
existingMail._id,
organization
);
const refreshTokenvalidation = tokenRefreshGenerator(
existingMail.Email,
UserData.role,
existingMail._id,
organization
);
await handleTokenCache(
existingMail._id.toString(),
existingMail.Email,
tokenValidation,
refreshTokenvalidation
);
const updatedUser = await AuthModel(organization)
.findByIdAndUpdate(
existingMail._id,
{ visitorBrowserID: fingerprint },
{ new: true }
)
.select("-__v -Profilepicture");
if (!updatedUser)
return {
status: "User update failed.",
};
await redis.setex(
`user:${existingMail.Email}`,
3600,
JSON.stringify(updatedUser)
);
const finalResult = {
message: "login successfull",
email: existingMail.Email,
name: existingMail.userName,
userId: existingMail._id,
isShare: UserData.isShare,
// updatedUser: updatedUser as IUser,
token: tokenValidation,
refreshToken: refreshTokenvalidation,
};
return {
status: "Success",
data: finalResult,
};
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const AuthLogout = async ({
Email,
}: Iserviceuser): Promise<{ status: string }> => {
try {
const caseChange = Email.toLowerCase();
const organization = extractOrg(caseChange);
const Existing_User = await findExistingUserEmail(caseChange);
if (!Existing_User) return { status: "User not found" };
const tokenData = await tokenType(organization).findOne({
userId: Existing_User._id,
isArchive: false,
});
if (!tokenData) return { status: "Token not found" };
await Promise.all([
redis.del(`token:${caseChange}`),
redis.del(`user:${caseChange}`),
]);
tokenData.refreshToken = "";
await tokenData.save();
Existing_User.visitorBrowserID = "";
await Existing_User.save();
return { status: "Success" };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const forgetPassword = async ({
Email,
}: Iserviceuser): Promise<{ status: string }> => {
try {
const caseChange = Email.toLowerCase();
const organization = extractOrg(caseChange);
const Existing_User = await findExistingUserEmail(caseChange);
if (Existing_User) {
if (Existing_User.lastPasswordReset) {
const lastPasswordReset = Existing_User.lastPasswordReset;
const now = Date.now();
const timeDiff = now - lastPasswordReset;
const diffInHours = Math.floor(timeDiff / (1000 * 60 * 60));
if (diffInHours < 24)
return {
status: "You can only reset your password once every 24 hours.",
};
}
const transport = nodemailer.createTransport({
service: "gmail",
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
const resetToken = tokenGenerator(
Email,
Existing_User.Role as string,
Existing_User._id as string,
organization
);
const userTokenData = await tokenType(organization).findOne({
Email: Email,
isArchive: false,
});
if (!userTokenData) {
await tokenType(organization).create({
Email: Existing_User.Email,
userId: Existing_User._id,
resetToken: resetToken,
resetTokenExpiry: Date.now(),
});
} else {
userTokenData.resetToken = resetToken;
userTokenData.resetTokenExpiry = new Date();
await userTokenData.save();
}
const Receiver = {
from: process.env.EMAIL_USER,
to: Email,
subject: "Password Reset Request",
text: `Click the below link to generate the new password \n ${
process.env.CLIENT_URL
}/reset-password/${tokenGenerator(
Email,
Existing_User.Role as string,
Existing_User._id as string,
organization
)}`,
};
await transport.sendMail(Receiver);
return { status: "Success" };
} else {
return { status: "Email not found" };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const resetPassword = async ({
resetToken,
newPassword,
confirmPassword,
}: IresetToken): Promise<{ status: string }> => {
try {
const decoded = Jwt.verify(resetToken, "Milestone");
if (typeof decoded === "string" || !("email" in decoded))
return { status: "Invalid token payload." };
const Email = decoded.email;
const organization = extractOrg(Email);
if (newPassword !== confirmPassword) return { status: "Password mismatch" };
const userData = await AuthModel(organization).findOne({
Email: Email,
isArchive: false,
});
const userTokenData = await tokenType(organization).findOne({
Email: Email,
isArchive: false,
});
if (!userData || !userTokenData) return { status: "User not found" };
else {
const tokenexpiry = userTokenData.resetTokenExpiry as Date;
const now = Date.now();
const tokenAge = tokenexpiry ? now - tokenexpiry.getTime() : 0;
const TOKEN_EXPIRATION_TIME = 15 * 60 * 1000;
if (!tokenexpiry || tokenAge > TOKEN_EXPIRATION_TIME)
return { status: "Token is invalid or expired." };
const hashPassword = await hashGenerate(newPassword);
const lastPasswordReset = Date.now();
await AuthModel(organization).findByIdAndUpdate(
userData._id,
{ Password: hashPassword, lastPasswordReset: lastPasswordReset },
{ new: true }
);
userTokenData.resetToken = "";
userTokenData.resetTokenExpiry = undefined;
await userTokenData.save();
await ResetFromCacheOrDB(Email);
return { status: "Success" };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
async function getUserFromCacheOrDB(Email: string) {
const redisUserKey = `user:${Email}`;
try {
const cachedUser = await redis.get(redisUserKey);
if (cachedUser) return JSON.parse(cachedUser);
const Existing_User = await findExistingUserEmail(Email);
if (Existing_User) {
await redis.setex(redisUserKey, 3600, JSON.stringify(Existing_User));
}
return Existing_User;
} catch (error) {
return error;
}
}
async function ResetFromCacheOrDB(Email: string) {
const redisUserKey = `user:${Email}`;
try {
const organization = extractOrg(Email);
const cachedUser = await redis.get(redisUserKey);
if (cachedUser) {
const user = await AuthModel(organization)
.findOne({
Email: Email,
isArchive: false,
})
.lean()
.select("-__v -Profilepicture");
if (user) {
await redis.setex(redisUserKey, 3600, JSON.stringify(user));
}
return user;
}
} catch (error) {
return error;
}
}
async function handleTokenCache(
userId: string,
Email: string,
token: string,
refreshToken: string
) {
const redisTokenKey = `token:${Email}`;
try {
const organization = extractOrg(Email);
const tokenPayload = {
token,
refreshToken,
userId,
Email,
};
await redis.setex(redisTokenKey, 3600, JSON.stringify(tokenPayload));
let tokenDoc = await tokenType(organization).findOne({
userId,
isArchive: false,
});
if (!tokenDoc) {
tokenDoc = await tokenType(organization).create({ userId, refreshToken });
} else {
await tokenType(organization).findByIdAndUpdate(
tokenDoc._id,
{ refreshToken },
{ new: true }
);
}
return tokenPayload;
} catch (error) {
return error;
}
}

View File

@@ -0,0 +1,155 @@
import UsersDataModel from "../../V1Models/Auth/user.ts";
import cameraModel from "../../V1Models/Builder/cameraModel.ts";
import { existingProjectById } from "../helpers/v1projecthelperFns.ts";
interface IcameraData {
userId: string;
role: string;
position: Object;
target: Object;
rotation: Object;
organization: string;
projectId: string;
versionId: string;
}
interface IgetCameras {
organization: string;
userId?: string;
role: string;
}
export const SetCamera = async (
data: IcameraData
): Promise<{ status: string; data?: Object }> => {
try {
const {
userId,
role,
position,
target,
rotation,
organization,
projectId,
versionId,
} = data;
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingCamera = await cameraModel(organization).findOne({
userId: userId,
});
if (existingCamera) {
const updateCamera = await cameraModel(organization).findOneAndUpdate(
{
userId: userId,
projectId: projectId,
versionId: versionId,
isArchive: false,
},
{ position: position, target: target, rotation: rotation },
{ new: true }
);
return {
status: "Update Success",
data: updateCamera,
};
} else {
const newCamera = await cameraModel(organization).create({
userId,
projectId,
versionId,
position,
target,
rotation,
});
return {
status: "Success",
data: newCamera,
};
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const GetCamers = async (
data: IgetCameras
): Promise<{ status: string; data?: Object }> => {
const { userId, organization, role } = data;
try {
const findCamera = await cameraModel(organization).findOne({
userId: userId,
});
if (!findCamera) {
return { status: "Camera not found" };
} else {
return { status: "Success", data: findCamera };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const onlineActiveDatas = async (
data: IgetCameras
): Promise<{ status: string; data?: Object }> => {
const { organization } = data;
try {
const findactiveUsers = await UsersDataModel(organization).find({
activeStatus: "online",
});
const cameraDataPromises = findactiveUsers.map(async (activeUser: any) => {
const cameraData = await cameraModel(organization)
.findOne({ userId: activeUser._id })
.select("position target rotation -_id");
if (cameraData) {
return {
position: cameraData.position,
target: cameraData.target,
rotation: cameraData.rotation,
userData: {
_id: activeUser._id,
userName: activeUser.userName,
email: activeUser.email,
activeStatus: activeUser.activeStatus,
},
};
}
return null;
});
const cameraDatas = (await Promise.all(cameraDataPromises)).filter(
(singledata: any) => singledata !== null
);
return { status: "Success", data: cameraDatas };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};

View File

@@ -76,3 +76,15 @@ export const generateUntitledProjectName = async (
return newNumber === 0 ? "Untitled" : `Untitled ${newNumber}`;
};
export const existingProjectById = async (
projectId: string,
organization: string,
userId: string
) => {
const projectData = await projectModel(organization).findOne({
_id: projectId,
createdBy: userId,
isArchive: false,
});
return projectData;
};

View File

@@ -0,0 +1,90 @@
import projectModel from "../../V1Models/Project/project-model.ts";
import { Types } from "mongoose";
import versionModel from "../../V1Models/Version/versionModel.ts";
import AuthModel from "../../V1Models/Auth/userAuthModel.ts";
export const existingProject = async (
projectUuid: string,
organization: string,
userId: string
) => {
const projectData = await projectModel(organization).findOne({
projectUuid: projectUuid,
createdBy: userId,
isArchive: false,
});
return projectData;
};
export const existingUser = async (userId: string, organization: string) => {
if (!Types.ObjectId.isValid(userId)) {
console.log("Invalid ObjectId format");
return null;
}
const userData = await AuthModel(organization).findOne({
_id: userId,
});
return userData;
};
export const archiveProject = async (
projectId: string,
organization: string
) => {
return await projectModel(organization).findByIdAndUpdate(
projectId,
{ isArchive: true },
{ new: true }
);
};
export const previousVersion = async (
projectId: string,
organization: string
) => {
const result = await versionModel(organization).findOne({
projectId: projectId,
isArchive: false,
});
// .sort({ version: -1 });
return result;
};
export const generateUntitledProjectName = async (
organization: string,
userId: string
): Promise<string> => {
const projects = await projectModel(organization)
.find({
createdBy: userId,
isArchive: false,
projectName: { $regex: /^Untitled(?: \s?\d+)?$/, $options: "i" },
})
.select("projectName");
const usedNumbers = new Set<number>();
for (const proj of projects) {
const match = proj.projectName.match(/^Untitled(?:\s?(\d+))?$/);
if (match) {
const num = match[1] ? parseInt(match[1], 10) : 0;
usedNumbers.add(num);
}
}
let newNumber = 0;
while (usedNumbers.has(newNumber)) {
newNumber++;
}
return newNumber === 0 ? "Untitled" : `Untitled ${newNumber}`;
};
export const existingProjectById = async (
projectId: string,
organization: string,
userId: string
) => {
const projectData = await projectModel(organization).findOne({
_id: projectId,
createdBy: userId,
isArchive: false,
});
return projectData;
};

View File

@@ -57,26 +57,29 @@ export const searchProject = async (data: searchProjectInterface) => {
if (!userExisting) return { status: "User not found" };
const findprojectName = await projectModel(organization).find({
projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive
isArchive: false,
})
if (!findprojectName||findprojectName.length===0) return { status: "Project not found" }
isArchive: false,
});
if (!findprojectName || findprojectName.length === 0)
return { status: "Project not found" };
return { status: "Success", data: findprojectName };
} catch (error: unknown) {
return { status: error };
}
}
};
export const searchTrashProject = async (data: searchProjectInterface) => {
try {
const { userId, organization, searchName } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const findprojectName = await projectModel(organization).find({
projectName: { $regex: `${searchName}`, $options: "i" },
isArchive: true,isDeleted:false
})
if (!findprojectName||findprojectName.length===0) return { status: "Project not found" }
projectName: { $regex: `${searchName}`, $options: "i" },
isArchive: true,
isDeleted: false,
});
if (!findprojectName || findprojectName.length === 0)
return { status: "Project not found" };
return { status: "Success", data: findprojectName };
} catch (error: unknown) {
return { status: error };
}
}
};

View File

@@ -43,7 +43,7 @@ export const createProject = async (data: CreateProjectInput) => {
return {
status: "user_not_found",
};
}
}
const projectExisting = await existingProject(
projectUuid,
organization,
@@ -125,7 +125,7 @@ export const DeleteProject = async (data: ProjectInterface) => {
{ isArchive: true, DeletedAt: new Date() },
{ new: true }
);
if (updateProject) return { status: "Success",project: updateProject };
if (updateProject) return { status: "Success", project: updateProject };
} catch (error: unknown) {
return { status: error };
}

View File

@@ -0,0 +1,208 @@
import projectModel from "../../V1Models/Project/project-model.ts";
import versionModel from "../../V1Models/Version/versionModel.ts";
import {
existingProject,
existingUser,
archiveProject,
previousVersion,
generateUntitledProjectName,
} from "../helpers/v1projecthelperFns.ts";
import UsersDataModel from "../../V1Models/Auth/user.ts";
interface CreateProjectInput {
projectName: string;
projectUuid: string;
userId: string; // user ID
thumbnail?: string;
sharedUsers?: string[];
organization: string;
}
interface updateProjectInput {
projectName: string;
projectId: string;
userId: string; // user ID
thumbnail?: string;
sharedUsers?: string[];
organization: string;
role: string;
}
interface GetProjectsInterface {
userId: string;
organization: string;
role: string;
}
interface ProjectInterface {
projectId: string;
userId: string;
organization: string;
role: string;
}
interface RoleFilter {
isArchive: boolean;
createdBy?: string;
}
export const createProject = async (data: CreateProjectInput) => {
try {
const { thumbnail, sharedUsers, projectUuid, userId, organization } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) {
return {
status: "user_not_found",
};
}
const projectExisting = await existingProject(
projectUuid,
organization,
userId
);
if (projectExisting) {
return {
status: "project_exists",
project: projectExisting,
};
}
const newProjectName = await generateUntitledProjectName(
organization,
userId
);
const project = await projectModel(organization).create({
projectName: newProjectName,
projectUuid: projectUuid,
createdBy: userId,
thumbnail: thumbnail,
sharedUsers: sharedUsers || [],
isArchive: false,
});
const versionData = await previousVersion(project._id, organization);
if (!versionData || versionData.length === 0) {
const newVersion = await versionModel(organization).create({
projectId: project._id,
createdBy: userId,
version: 0.0,
});
await projectModel(organization).findByIdAndUpdate(
{ _id: project._id, isArchive: false },
{ total_versions: `v-${newVersion.version.toFixed(2)}` }
);
}
return {
status: "Success",
project: project,
};
} catch (error) {
console.log("error: ", error);
return {
status: error,
};
}
};
export const GetAllProjects = async (data: GetProjectsInterface) => {
try {
const { userId, organization, role } = data;
await existingUser(userId, organization);
if (!existingUser) return { status: "User not found" };
let filter = { isArchive: false } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const projectDatas = await projectModel(organization)
.find(filter)
.select("_id projectName createdBy thumbnail createdAt projectUuid");
if (projectDatas) return { status: "Success", Datas: projectDatas };
} catch (error: unknown) {
return { status: error };
}
};
export const DeleteProject = async (data: ProjectInterface) => {
try {
const { projectId, organization, userId, role } = data;
const ExistingUser = await existingUser(userId, organization);
if (!ExistingUser) return { status: "User not found" };
let filter = { _id: projectId, isArchive: false } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const existingProject = await projectModel(organization).findOne(filter);
if (!existingProject) return { status: "Project not found" };
const updateProject = await projectModel(organization).findOneAndUpdate(
filter,
{ isArchive: true, DeletedAt: new Date() },
{ new: true }
);
if (updateProject) return { status: "Success", project: updateProject };
} catch (error: unknown) {
return { status: error };
}
};
export const updateProject = async (data: updateProjectInput) => {
try {
const { projectId, organization, userId, projectName, thumbnail, role } =
data;
const ExistingUser = await existingUser(userId, organization);
if (!ExistingUser) return { status: "User not found" };
let filter = { _id: projectId, isArchive: false } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const existingProject = await projectModel(organization).findOne(filter);
if (!existingProject) return { status: "Project not found" };
if (projectName !== undefined) projectName;
if (thumbnail !== undefined) thumbnail;
const updateProject = await projectModel(organization)
.findOneAndUpdate(
filter,
{ projectName: projectName, thumbnail: thumbnail },
{ new: true }
)
.select("_id projectName createdBy thumbnail createdAt");
if (updateProject) return { status: "Success", data: updateProject };
} catch (error: unknown) {
return { status: error };
}
};
const maxLength: number = 6;
export const viewProject = async (data: ProjectInterface) => {
try {
const { projectId, organization, userId, role } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const RecentUserDoc = await UsersDataModel(organization).findOne({
userId: userId,
isArchive: false,
});
let filter = { _id: projectId, isArchive: false } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const existingProject = await projectModel(organization).findOne(filter);
if (!existingProject) return { status: "Project not found" };
const newArr = RecentUserDoc?.recentlyViewed || [];
if (RecentUserDoc?.recentlyViewed.length === 0) {
newArr.push(projectId);
await RecentUserDoc.save();
} else {
const index = newArr.indexOf(projectId);
if (index !== -1) {
newArr.splice(index, 1);
}
newArr.unshift(projectId);
if (newArr.length > maxLength) {
newArr.pop();
}
}
await UsersDataModel(organization).updateOne(
{ _id: userId },
{ recentlyViewed: newArr },
{ new: true }
);
const projectData = await projectModel(organization)
.findOneAndUpdate(filter, { isViewed: Date.now() }, { new: true })
.select("_id projectName createdBy thumbnail createdAt");
return { status: "Success", data: projectData };
} catch (error: unknown) {
return { status: error };
}
};

View File

@@ -0,0 +1,92 @@
import projectModel from "../../V1Models/Project/project-model.ts";
import userModel from "../../model/user-Model.ts";
import UsersDataModel from "../../V1Models/Auth/user.ts";
import { existingUser } from "../helpers/ProjecthelperFn.ts";
interface IRecentData {
organization: string;
userId: string;
role: string;
}
interface IProject {
_id: string;
projectName: string;
createdBy: string;
thumbnail?: string;
createdAt: Date;
isViewed?: number;
}
interface searchProjectInterface {
searchName: string;
userId: string;
organization: string;
}
interface RoleFilter {
isArchive: boolean;
createdBy?: string;
}
export const RecentlyAdded = async (data: IRecentData) => {
try {
const { userId, organization, role } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const userRecentData = await UsersDataModel(organization)
.findOne({ userId: userId, isArchive: false })
.populate({
path: "recentlyViewed",
model: projectModel(organization),
select: "_id",
});
let filter = { isArchive: false } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const populatedProjects = userRecentData.recentlyViewed as IProject[];
const RecentDatas = await Promise.all(
populatedProjects.map(async (project) => {
const projectExisting = await projectModel(organization)
.findOne(filter)
.select("_id projectName createdBy thumbnail createdAt isViewed");
return projectExisting;
})
);
const filteredProjects = RecentDatas.filter(Boolean);
return { status: "Success", data: filteredProjects };
} catch (error) {
return { status: error };
}
};
export const searchProject = async (data: searchProjectInterface) => {
try {
const { userId, organization, searchName } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const findprojectName = await projectModel(organization).find({
projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive
isArchive: false,
});
if (!findprojectName || findprojectName.length === 0)
return { status: "Project not found" };
return { status: "Success", data: findprojectName };
} catch (error: unknown) {
return { status: error };
}
};
export const searchTrashProject = async (data: searchProjectInterface) => {
try {
const { userId, organization, searchName } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const findprojectName = await projectModel(organization).find({
projectName: { $regex: `${searchName}`, $options: "i" },
isArchive: true,
isDeleted: false,
});
if (!findprojectName || findprojectName.length === 0)
return { status: "Project not found" };
return { status: "Success", data: findprojectName };
} catch (error: unknown) {
return { status: error };
}
};

View File

@@ -0,0 +1,75 @@
import projectModel from "../../V1Models/Project/project-model.ts";
interface IOrg {
organization: string;
role: string;
userId: string;
}
interface IRestore {
projectId: string;
organization: string;
role: string;
userId: string;
}
interface RoleFilter {
isArchive: boolean;
createdBy?: string;
}
export const TrashDatas = async (data: IOrg) => {
try {
const { organization, role, userId } = data;
let filter = { isArchive: true, isDeleted: false } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const TrashLists = await projectModel(organization).find(filter);
if (!TrashLists) return { staus: "Trash is Empty" };
const TrashDocs: any[] = [];
for (const Trash of TrashLists) {
const now = new Date();
const deletedPlus15 = new Date(
Trash.DeletedAt.getTime() + 15 * 24 * 60 * 60 * 1000
);
if (now > deletedPlus15) {
console.log("now > deletedPlus15: ", now > deletedPlus15);
await projectModel(organization).updateOne(
{ _id: Trash._id },
{ $set: { isDeleted: true } }
);
} else {
TrashDocs.push(Trash);
}
}
const ListDatas = TrashDocs.map((data) => {
return {
projectName: data.projectName,
thumbnail: data.thumbnail,
createdBy: data.createdBy,
_id: data._id,
};
});
return { status: "Success", ListDatas };
} catch (error) {
return { status: error };
}
};
export const RestoreTrashData = async (data: IRestore) => {
try {
const { projectId, organization, role, userId } = data;
let filter = { isArchive: true, _id: projectId } as RoleFilter;
if (role === "User") {
filter.createdBy = userId;
}
const findProject = await projectModel(organization).findOne(filter);
if (!findProject) return { status: "Project not found" };
const restoreData = await projectModel(organization).findOneAndUpdate(
filter,
{ isArchive: false, DeletedAt: null },
{ new: true }
);
if (!restoreData) return { status: "Project Restore unsuccessfull" };
return { status: "Project Restored successfully" };
} catch (error) {
return { status: error };
}
};

View File

@@ -0,0 +1,127 @@
import projectModel from "../../model/project/project-model.ts";
import assetModel from "../../V1Models/Builder/assetModel.ts";
import versionModel from "../../model/version/versionModel.ts";
class VersionService {
async getCurrentVersion(db: string, projectId: string) {
const project = await projectModel(db).findById(projectId);
if (!project) throw new Error("Project not found");
return {
versionNumber: parseFloat(project.Present_version || "0.0"),
versionString: project.Present_version || "0.0",
};
}
async createNewVersion(
db: string,
projectId: string,
userId: string,
description?: string
) {
const project = await projectModel(db).findById(projectId);
if (!project) throw new Error("Project not found");
const { versionNumber } = await this.getCurrentVersion(db, projectId);
const newVersion = parseFloat((versionNumber + 0.1).toFixed(1));
const versionName = `Version ${newVersion.toFixed(1)}`;
const version = await versionModel(db).create({
versionName,
version: newVersion,
projectId: project._id,
createdBy: userId,
description,
});
await projectModel(db).findByIdAndUpdate(projectId, {
Present_version: newVersion.toFixed(1),
total_versions: newVersion.toFixed(1),
});
return version;
}
async saveCurrentStateAsVersion(
db: string,
projectId: string,
userId: string,
description?: string
) {
// Create new version
const newVersion = await this.createNewVersion(
db,
projectId,
userId,
description
);
// Get all assets from previous version
const previousVersion = parseFloat((newVersion.version - 0.1).toFixed(1));
const previousVersionDoc = await versionModel(db).findOne({
projectId,
version: previousVersion,
});
console.log("previousVersionDoc: ", previousVersionDoc);
let previousAssets = [];
if (previousVersionDoc) {
previousAssets = await assetModel(db).find({
projectId,
versionId: previousVersionDoc._id,
isArchive: false,
});
}
// Copy assets to new version
const newAssets = await Promise.all(
previousAssets.map(async (asset) => {
console.log("previousAssets: ", previousAssets);
const newAsset = { ...asset.toObject(), versionId: newVersion._id };
delete newAsset._id;
return await assetModel(db).create(newAsset);
})
);
return {
version: newVersion,
assets: newAssets,
};
}
async getVersionHistory(db: string, projectId: string) {
const versions = await versionModel(db)
.find({ projectId, isArchive: false })
.sort({ version: 1 })
.populate("createdBy", "name email");
const versionHistory = await Promise.all(
versions.map(async (version) => {
const assets = await assetModel(db).find({
projectId,
versionId: version._id,
isArchive: false,
});
const assetCounts = assets.reduce((acc, asset) => {
acc[asset.type] = (acc[asset.type] || 0) + 1;
return acc;
}, {});
return {
version: version.version.toFixed(1),
versionName: version.versionName,
createdAt: version.createdAt,
createdBy: version.createdBy,
description: version.description,
assets: assetCounts,
totalAssets: assets.length,
};
})
);
return versionHistory;
}
}
export default new VersionService();

View File

@@ -0,0 +1,115 @@
import { Request, Response } from "express";
import wallItemModel from "../../../shared/model/builder/assets/wallitems-Model.ts";
interface IWallSetupData {
modelUuid: string;
modelName: string;
type: string;
csgposition: [];
csgscale: [];
position: [];
quaternion: [];
scale: [];
organization: string;
}
interface IWallItemResult {
data: {};
state: string;
}
export class WallItems {
static async setWallItems(data: IWallSetupData): Promise<IWallItemResult> {
try {
const {
modelUuid,
modelName,
position,
type,
csgposition,
csgscale,
quaternion,
scale,
organization,
} = data;
const findvalue = await wallItemModel(organization).findOne({
modelUuid: modelUuid,
});
if (findvalue) {
const updatevalue = await wallItemModel(organization).findOneAndUpdate(
{ modelUuid: modelUuid },
{
modelName,
position,
type,
csgposition,
csgscale,
quaternion,
scale,
},
{ new: true } // Return the updated document
);
return {
state: "Updated successfully",
data: updatevalue,
};
// res.status(201).json(updatevalue);
} else {
const newValue = await wallItemModel(organization).create({
modelUuid,
modelName,
position,
type,
csgposition,
csgscale,
quaternion,
scale,
});
return {
state: "wall Item created successfully",
data: newValue,
};
// res.status(201).json(newValue);
}
// Send response with the created document
} catch (error:unknown) {
const err = error as Error;
console.error("Error creating wallitems:", error);
return { state: "Failed to create wallitems", data: { message: err.message } };
// return { state: "Failed to create wallitems", data: error } };
// res.status(500).json({ message: "Failed to create wallitems" });
}
}
static async getWallItems(req: Request, res: Response) {
try {
const { organization } = req.params;
const findValue = await wallItemModel(organization).find();
if (!findValue) {
res.status(200).json("wallitems not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error("Error get wallitems:", error);
res.status(500).json({ error: "Failed to get wallitems" });
}
}
static async deleteWallItems(req: Request, res: Response) {
try {
const { modelUuid, modelName, organization } = req.body;
const findValue = await wallItemModel(organization).findOneAndDelete({
modelUuid: modelUuid,
modelName: modelName,
});
if (!findValue) {
res.status(200).json("user not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error("Error get wallitems:", error);
res.status(500).json({ error: "Failed to get wallitems" });
}
}
}

View File

@@ -1,24 +1,25 @@
import bcrypt from 'bcryptjs';
const saltRounds = 10;
export const hashGenerate = async (Password:string) => {
try {
const salt = await bcrypt.genSalt(saltRounds);
const hash = await bcrypt.hash(Password, salt);
return hash;
} catch (error) {
return error;
}
};
export const hashValidator = async (password:string, hashedPassword:string) => {
try {
const result = await bcrypt.compare(password, hashedPassword);
return result;
} catch (error) {
return false;
}
};
;
import bcrypt from "bcryptjs";
const saltRounds = 10;
export const hashGenerate = async (Password: string) => {
try {
const salt = await bcrypt.genSalt(saltRounds);
const hash = await bcrypt.hash(Password, salt);
return hash;
} catch (error) {
return error;
}
};
export const hashValidator = async (
password: string,
hashedPassword: string
) => {
try {
const result = await bcrypt.compare(password, hashedPassword);
return result;
} catch (error) {
return false;
}
};

View File

@@ -1,34 +1,34 @@
import { MongoClient } from 'mongodb'
export default async function mongoAdminCreation() {
const uri = process.env.MONGO_URI!; // Replace with your MongoDB URI
const client = new MongoClient(uri);
const user = {
user:"admin",
pwd: process.env.MONGO_PASSWORD!,
roles: [{ role: "root", db: process.env.MONGO_AUTH_DB || "admin" }],
};
try {
await client.connect();
const db = client.db('admin'); // Specify the actual database where the user should be created
// Check if the user already exists
const userExists = await db.collection('system.users').findOne({ user: user.user});
if (userExists) {
console.log(`User ${user} already exists`);
return; // Exit if the user already exists
}
// Create the user
await db.command({ createUser: user.user, pwd: user.pwd, roles: user.roles });
console.log("User created successfully!")
} catch (error) {
console.error("Error creating user:",error);
} finally {
await client.close();
}
}
import { MongoClient } from 'mongodb'
export default async function mongoAdminCreation() {
const uri = process.env.MONGO_URI!; // Replace with your MongoDB URI
const client = new MongoClient(uri);
const user = {
user:"admin",
pwd: process.env.MONGO_PASSWORD!,
roles: [{ role: "root", db: process.env.MONGO_AUTH_DB || "admin" }],
};
try {
await client.connect();
const db = client.db('admin'); // Specify the actual database where the user should be created
// Check if the user already exists
const userExists = await db.collection('system.users').findOne({ user: user.user});
if (userExists) {
console.log(`User ${user} already exists`);
return; // Exit if the user already exists
}
// Create the user
await db.command({ createUser: user.user, pwd: user.pwd, roles: user.roles });
console.log("User created successfully!")
} catch (error) {
console.error("Error creating user:",error);
} finally {
await client.close();
}
}
// mongoAdminCreation

143
src/shared/utils/token.ts Normal file
View File

@@ -0,0 +1,143 @@
import { Request, Response, NextFunction } from "express";
import Jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { extractOrg } from "../services/auth/authServices.ts";
import AuthModel from "../V1Models/Auth/userAuthModel.ts";
dotenv.config();
export interface AuthenticatedRequest extends Request {
user?: {
Email: string;
role: string;
userId: string;
organization: string;
};
}
const jwt_secret = process.env.JWT_SECRET as string;
const refresh_jwt_secret = process.env.REFRESH_JWT_SECRET as string;
const tokenGenerator = (
Email: string,
role: string,
userId: string,
organization: string
) => {
const token = Jwt.sign(
{ Email: Email, role: role, userId, organization: organization },
jwt_secret,
{
expiresIn: "3h",
}
);
return token;
};
const tokenRefreshGenerator = (
Email: string,
role: string,
userId: string,
organization: string
) => {
const token = Jwt.sign(
{ Email: Email, role: role, userId, organization: organization },
refresh_jwt_secret,
{
expiresIn: "30d",
}
);
return token;
};
const tokenValidator = async (
req: AuthenticatedRequest,
res: Response,
next: NextFunction
): Promise<void> => {
const token: string | undefined = req.headers.token as string | undefined;
const refresh_token = req.headers["refresh_token"] as string | undefined;
if (!token) {
res.status(403).json({
msg: "No token present",
});
return;
}
try {
const decoded = Jwt.verify(token, jwt_secret) as {
Email: string;
role: string;
userId: string;
organization: string;
};
if (!decoded) {
res.status(403).json({
success: false,
status: 403,
message: "Invalid Token",
});
return;
}
req.user = decoded;
next();
} catch (err) {
// res.status(401).json({
// msg: "Invalid Token",
// });
if (!refresh_token) {
res.status(403).json({
success: false,
status: 403,
message: "No refresh token present",
});
return;
}
try {
const decodedRefresh = Jwt.verify(refresh_token, refresh_jwt_secret) as {
Email: string;
role: string;
userId: string;
organization: string;
};
if (!decodedRefresh) {
res.status(403).json({
success: false,
status: 403,
message: "Invalid Token",
});
return;
}
const newAccessToken = tokenGenerator(
decodedRefresh.Email,
decodedRefresh.role,
decodedRefresh.userId,
decodedRefresh.organization
);
res.setHeader("x-access-token", newAccessToken);
req.user = decodedRefresh;
return next();
} catch (err) {
const decodedAny = Jwt.decode(token || refresh_token) as {
Email?: string;
role: string;
userId: string;
organization: string;
};
if (decodedAny?.Email) {
const organization = extractOrg(decodedAny?.Email);
const user = await AuthModel(organization).findOne({
Email: decodedAny.Email,
isArchieve: false,
});
if (user) {
user.visitorBrowserID = "";
await user.save();
}
}
res.status(403).json({
success: false,
status: 403,
message: "Invalid Token",
});
return;
}
}
};
export { tokenValidator, tokenGenerator, tokenRefreshGenerator };