Skip to content

Commit

Permalink
Verify user's auth status
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolelim02 committed Nov 6, 2024
1 parent 297bbd8 commit ad3c6c4
Show file tree
Hide file tree
Showing 13 changed files with 137 additions and 2 deletions.
3 changes: 3 additions & 0 deletions backend/communication-service/.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ SERVER_PORT=3005

# Origins for cors
ORIGINS=http://localhost:5173,http://127.0.0.1:5173

# Other service APIs
USER_SERVICE_URL=http://user-service:3001/api
6 changes: 5 additions & 1 deletion backend/communication-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,18 @@

![image2.png](./docs/images/postman-setup2.png)

- To send a message, go to the `Message` tab and ensure that your message is being parsed as `JSON`.
- Add a valid JWT token in the `Authorization` header.

![image3.png](./docs/images/postman-setup3.png)

- In the `Event name` input, input the correct event name. Click on `Send` to send a message.

![image4.png](./docs/images/postman-setup4.png)

- To send a message, go to the `Message` tab and ensure that your message is being parsed as `JSON`.

![image5.png](./docs/images/postman-setup5.png)

## Events Available

| Event Name | Description | Parameters | Response Event |
Expand Down
Binary file modified backend/communication-service/docs/images/postman-setup2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified backend/communication-service/docs/images/postman-setup3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
79 changes: 79 additions & 0 deletions backend/communication-service/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/communication-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"license": "ISC",
"description": "",
"dependencies": {
"axios": "^1.7.7",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const handleWebsocketCommunicationEvents = (socket: Socket) => {
CommunicationEvents.JOIN,
async ({ roomId, username }: { roomId: string; username: string }) => {
connectUser(username);
console.log(username, roomId);
const room = io.sockets.adapter.rooms.get(roomId);
if (room?.has(socket.id)) {
socket.emit(CommunicationEvents.ALREADY_JOINED);
Expand Down
17 changes: 16 additions & 1 deletion backend/communication-service/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,31 @@ import app, { allowedOrigins } from "./app";
import { createServer } from "http";
import { Server } from "socket.io";
import { handleWebsocketCommunicationEvents } from "./handlers/websocketHandler";
import { verifyToken } from "./utils/userServiceApi";

const PORT = process.env.SERVICE_PORT || 3005;

const server = createServer(app);

export const io = new Server(server, {
cors: { origin: allowedOrigins, methods: ["GET", "POST"] },
cors: { origin: allowedOrigins, methods: ["GET", "POST"], credentials: true },
connectionStateRecovery: {},
});

io.use((socket, next) => {
const token =
socket.handshake.headers.authorization || socket.handshake.auth.token;
verifyToken(token)
.then(() => {
console.log("Valid credentials");
next();
})
.catch((err) => {
console.error(err);
next(new Error("Unauthorized"));
});
});

io.on("connection", handleWebsocketCommunicationEvents);

server.listen(PORT, () => {
Expand Down
15 changes: 15 additions & 0 deletions backend/communication-service/src/utils/userServiceApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import axios from "axios";

const USER_SERVICE_URL =
process.env.USER_SERVICE_URL || "http://localhost:3001/api";

const userClient = axios.create({
baseURL: USER_SERVICE_URL,
withCredentials: true,
});

export const verifyToken = (token: string | undefined) => {
return userClient.get("/auth/verify-token", {
headers: { authorization: token },
});
};
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ services:
env_file: ./backend/communication-service/.env
ports:
- 3005:3005
depends_on:
- user-service
networks:
- peerprep-network
volumes:
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/components/Chat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
USE_MATCH_ERROR_MESSAGE,
} from "../../utils/constants";
import { useAuth } from "../../contexts/AuthContext";
import { toast } from "react-toastify";

type Message = {
from: string;
Expand All @@ -36,6 +37,7 @@ const Chat: React.FC<ChatProps> = ({ isActive }) => {
const match = useMatch();
const auth = useAuth();
const messagesRef = useRef<HTMLDivElement>(null);
const errorHandledRef = useRef(false);

if (!match) {
throw new Error(USE_MATCH_ERROR_MESSAGE);
Expand Down Expand Up @@ -68,10 +70,17 @@ const Chat: React.FC<ChatProps> = ({ isActive }) => {
const listener = (message: Message) => {
setMessages((prevMessages) => [...prevMessages, message]);
};
const errorListener = () => {
if (!errorHandledRef.current) {
toast.error("Connection error. Please try again.");
errorHandledRef.current = true;
}
};

communicationSocket.on(CommunicationEvents.USER_JOINED, listener);
communicationSocket.on(CommunicationEvents.TEXT_MESSAGE_RECEIVED, listener);
communicationSocket.on(CommunicationEvents.DISCONNECTED, listener);
communicationSocket.on(CommunicationEvents.CONNECT_ERROR, errorListener);

return () => {
communicationSocket.off(CommunicationEvents.USER_JOINED, listener);
Expand All @@ -80,6 +89,7 @@ const Chat: React.FC<ChatProps> = ({ isActive }) => {
listener
);
communicationSocket.off(CommunicationEvents.DISCONNECTED, listener);
communicationSocket.off(CommunicationEvents.CONNECT_ERROR, errorListener);
};
}, []);

Expand Down
5 changes: 5 additions & 0 deletions frontend/src/utils/communicationSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export enum CommunicationEvents {
USER_JOINED = "user_joined",
ALREADY_JOINED = "already_joined",
TEXT_MESSAGE_RECEIVED = "text_message_received",
CONNECT_ERROR = "connect_error",
DISCONNECTED = "disconnected",
}

Expand All @@ -19,4 +20,8 @@ const COMMUNICATION_SOCKET_URL = "http://localhost:3005";
export const communicationSocket = io(COMMUNICATION_SOCKET_URL, {
reconnectionAttempts: 3,
autoConnect: false,
withCredentials: true,
auth: {
token: `Bearer ${localStorage.getItem("token")}`,
},
});

0 comments on commit ad3c6c4

Please sign in to comment.