Skip to content

Commit

Permalink
Merge pull request #52 from sanam2405/ws
Browse files Browse the repository at this point in the history
sync ui and ws broadcasted loc data
  • Loading branch information
sanam2405 authored May 26, 2024
2 parents 2c17eca + 3f9436b commit 1e93050
Show file tree
Hide file tree
Showing 110 changed files with 8,730 additions and 706 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ dist-ssr
*.njsproj
*.sln
*.sw?
*.zip
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
<i> Design and Implementation of Security-Conscious,
Location-Sharing in a Geosocial Network </i>

[Link to the presentation](papers/Panel_2_Team16_PrivacyNetwork.pptx)
[Link to the Presentation](papers/Panel_2_Team16_PrivacyNetwork.pptx)

[Link to the Thesis](papers/Design_and_Implementation_of_Security_Conscious__Location_Sharing_in_a_Geosocial_Network.pdf)

[Link to the reference research paper](https://ieeexplore.ieee.org/abstract/document/9288801)

Expand Down Expand Up @@ -116,7 +118,7 @@ _![OpenAPI Swagger Schemas](./idea/high/swaggerschema.png)_

![](idea/gifs/Auth2.gif)

### Landing Page
### Dashboard Page

![](idea/gifs/Dashboard.gif)

Expand Down
2 changes: 1 addition & 1 deletion backend/loc/src/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ userRouter.put(
return;
}

// Check if the user already has a location, the update the previous loc
// Check if the user already has a location, then update the previous loc
if (existingUser.locationId !== null) {
// Update the user's location
const updatedUser = await prisma.user.update({
Expand Down
2 changes: 1 addition & 1 deletion backend/ws/.env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
SECRET_KEY=<CLIENT_SECRET: verifying the JWT token>
TS_BACKEND_URI=<TS_BACKEND_URI: for user auth from ts-backend>
TS_BACKEND_URI=<TS_BACKEND_URI: for user auth from ts-backend>
34 changes: 33 additions & 1 deletion backend/ws/src/UserManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import { OUTGOING_MESSAGE } from "./messages/outgoingMessages";
interface User {
name: string;
id: string;
email: string;
age: number;
gender: string;
college: string;
lat: number;
lng: number;
dist_meters?: number | undefined;
Photo?: string | undefined;
mask?: boolean | undefined;
conn: WebSocket;
}

Expand All @@ -17,7 +26,21 @@ export class UserManager {
this.rooms = new Map<string, Room>();
}

addUser(name: string, userId: string, roomId: string, socket: WebSocket) {
addUser(
name: string,
userId: string,
roomId: string,
socket: WebSocket,
email: string,
age: number,
gender: string,
college: string,
lat: number,
lng: number,
dist_meters: number | undefined,
Photo: string | undefined,
mask: boolean | undefined,
) {
if (!this.rooms.get(roomId)) {
this.rooms.set(roomId, {
users: [],
Expand All @@ -34,6 +57,15 @@ export class UserManager {
id: userId,
name,
conn: socket,
email,
age,
gender,
college,
lat,
lng,
dist_meters,
Photo,
mask,
});
console.log(`User with id ${userId} added!`);
socket.on("close", () => {
Expand Down
2 changes: 2 additions & 0 deletions backend/ws/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const HEARTBEAT_INTERVAL = 1000 * 5; // 5 seconds
export const HEARTBEAT_VALUE = 1;
162 changes: 88 additions & 74 deletions backend/ws/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,17 @@
import { WebSocketServer, WebSocket } from "ws";
import express from "express";
import url from "url";
import axios from "axios";
import { WebSocketServer, WebSocket } from "ws";
import {
INCOMING_MESSAGE,
SUPPORTED_MESSAGES,
} from "./messages/incomingMessages";
import {
OUTGOING_MESSAGE,
SUPPORTED_MESSAGES as OUTGOING_SUPPORTED_MESSAGE,
} from "./messages/outgoingMessages";
INCOMING_SUPPORTED_MESSAGE,
OUTGOING_SUPPORTED_MESSAGE,
} from "./messages";

import { HEARTBEAT_INTERVAL, HEARTBEAT_VALUE } from "./constants";
import tokenIsValid from "./utils";
import { UserManager } from "./UserManager";
import { InMemoryStore } from "./store/inMemoryStore";
import tokenIsValid from "./utils";

const userManager = new UserManager();
const store = new InMemoryStore();

const app = express();
const PORT: string | number = process.env.PORT || 8080;

const httpServer = app.listen(PORT, () => {
console.log(`HTTP Server is running on PORT ${PORT}`);
});

const HEARTBEAT_INTERVAL = 1000 * 5; // 5 seconds
const HEARTBEAT_VALUE = 1;

function onSocketPreError(e: Error) {
console.log(e);
Expand All @@ -36,7 +22,6 @@ function onSocketPostError(e: Error) {
}

function ping(ws: WebSocket) {
console.log("Ping initiated from ws backend");
ws.send(
JSON.stringify({
type: "PING",
Expand All @@ -45,79 +30,88 @@ function ping(ws: WebSocket) {
);
}

const userManager = new UserManager();
const store = new InMemoryStore();

const app = express();
const PORT: string | number = process.env.PORT || 8080;

const httpServer = app.listen(PORT, () => {
console.log(`HTTP Server is running on PORT ${PORT}`);
});

const wss = new WebSocketServer({ noServer: true });

httpServer.on("upgrade", (req, socket, head) => {
socket.on("error", onSocketPreError);

console.log(
`HTTP Server requesting to upgraded to ws to run on PORT ${PORT}`,
);

wss.handleUpgrade(req, socket, head, (ws) => {
socket.removeListener("error", onSocketPreError);
wss.emit("connection", ws, req);
});
});

wss.on("connection", async function connection(ws: WebSocket, req) {
console.log(
`HTTP Server upgraded to WSS Server and is running on PORT ${PORT}`,
);

// const queryParams = url.parse(req.url, true).query;
// const token = queryParams.token;

// @ts-ignore
const token: string = url.parse(req.url, true).query.token || "";
// const userId = extractUserId(token);

const checkIfAuthorized = await tokenIsValid(token);
// Perform auth
if (!token || !checkIfAuthorized) {
console.log("Unauthorized user from ws backend");
console.log("Unauthorized user received in ws backend");
// Send an unauthorized message to the client
ws.send(
JSON.stringify({
type: "UNAUTHORIZED",
payload: {
message: "You are not authorized to connect to the WebSocketServer",
STATUS_CODE: 401,
message:
"You are not authorized to connect to the ws WebSocketServer",
},
}),
);
// Close the WebSocket connection
ws.terminate();
return;
} else {
ws.isAlive = true;

ws.on("error", onSocketPostError);

ws.on("message", function message(data: any, isBinary: boolean) {
try {
// If data is binary, convert it to a string
const dataString = data.toString();
const jsonData = JSON.parse(dataString);
console.log("JSON DATA received from client : ", jsonData);

messageHandler(ws, token, jsonData);
// wss.clients.forEach(function each(client) {
// if (client.readyState === WebSocket.OPEN) {
// client.send(data, { binary: isBinary });
// }
// });
} catch (error) {
console.error(error);
}
});

// ws.send(
// `A Privacy-Preserving Efficient Location-Sharing Scheme for Mobile Online Social Network Applications ~ Built with &#x1F499 by sanam`,
// );
ws.on("close", () => {
console.log("Connection closed from ws server");
});
}
console.log("Client is authorized and authenticated in ws backend");
console.log(
`HTTP protocol is upgraded to WS protocol and is communicating on PORT ${PORT}`,
);

ws.isAlive = true;

ws.on("error", onSocketPostError);

ws.on("message", function message(data: any) {
try {
const jsonData = JSON.parse(data.toString());
// console.log("JSON DATA received from client : ", jsonData);

// jsonData.wscale = "Hi from sanam wscale!";
// wss.clients.forEach(function each(client) {
// if (client.readyState === WebSocket.OPEN) {
// client.send(JSON.stringify(jsonData));
// }
// });

messageHandler(ws, jsonData);
} catch (error) {
console.error(error);
}
});

ws.on("close", () => {
console.log("Connection closed from ws server");
});
});

const interval = setInterval(() => {
console.log("PING initiated from ws backend");
wss.clients.forEach((client: any) => {
if (!client.isAlive) {
client.terminate();
Expand All @@ -133,25 +127,38 @@ wss.on("close", () => {
clearInterval(interval);
});

function messageHandler(
ws: WebSocket,
token: string,
message: INCOMING_MESSAGE,
) {
if (message.type == SUPPORTED_MESSAGES.PONG) {
console.log("Pong received by ws backend");
function messageHandler(ws: WebSocket, message: INCOMING_MESSAGE) {
if (message.type == INCOMING_SUPPORTED_MESSAGE.PONG) {
console.log("PONG received by ws backend!");
const payload = message.payload;
if (payload.HEARTBEAT_VALUE == HEARTBEAT_VALUE) {
ws.isAlive = true;
}
}

if (message.type == SUPPORTED_MESSAGES.JOIN_ROOM) {
// handle form here, code here --------------------------------------

if (message.type == INCOMING_SUPPORTED_MESSAGE.JOIN_ROOM) {
console.log(message);
const payload = message.payload;
userManager.addUser(payload.name, payload.userId, payload.roomId, ws);
userManager.addUser(
payload.name,
payload.userId,
payload.roomId,
ws,
payload.email,
payload.age,
payload.gender,
payload.college,
payload.lat,
payload.lng,
payload.dist_meters ?? undefined,
payload.Photo ?? undefined,
payload.mask ?? undefined,
);
}

if (message.type == SUPPORTED_MESSAGES.LEAVE_ROOM) {
if (message.type == INCOMING_SUPPORTED_MESSAGE.LEAVE_ROOM) {
const payload = message.payload;
const user = userManager.getUser(payload.roomId, payload.userId);

Expand All @@ -167,7 +174,6 @@ function messageHandler(
payload: {
userId: payload.userId,
roomId: payload.roomId,
STATUS_CODE: 404, // 404 status code signifies that the client has disconnected. This has to be broadcasted
},
};

Expand All @@ -178,7 +184,7 @@ function messageHandler(
);
}

if (message.type === SUPPORTED_MESSAGES.SEND_MESSAGE) {
if (message.type === INCOMING_SUPPORTED_MESSAGE.SEND_MESSAGE) {
const payload = message.payload;
const user = userManager.getUser(payload.roomId, payload.userId);

Expand All @@ -202,7 +208,7 @@ function messageHandler(
);
}

if (message.type === SUPPORTED_MESSAGES.SEND_LOCATION) {
if (message.type === INCOMING_SUPPORTED_MESSAGE.SEND_LOCATION) {
const payload = message.payload;
const user = userManager.getUser(payload.roomId, payload.userId);

Expand Down Expand Up @@ -239,12 +245,20 @@ function messageHandler(
const outgoingPayload: OUTGOING_MESSAGE = {
type: OUTGOING_SUPPORTED_MESSAGE.ADD_LOCATION,
payload: {
name: payload.name,
userId: payload.userId,
roomId: payload.roomId,
position: {
lat: payload.position.lat,
lng: payload.position.lng,
},
email: payload.email,
age: payload.age,
gender: payload.gender,
college: payload.college,
Photo: payload.Photo,
mask: payload.mask,
dist_meters: payload.dist_meters,
},
};
userManager.broadcastToRoom(
Expand Down
Loading

1 comment on commit 1e93050

@vercel
Copy link

@vercel vercel bot commented on 1e93050 May 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.