Skip to content

Commit 416e7c9

Browse files
committed
Add verify user on connection
1 parent 84830a8 commit 416e7c9

File tree

10 files changed

+106
-14
lines changed

10 files changed

+106
-14
lines changed

collab/main.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"encoding/json"
45
"log"
56
"net/http"
67
"sync"
@@ -19,6 +20,7 @@ var upgrader = websocket.Upgrader{
1920
type Client struct {
2021
conn *websocket.Conn
2122
roomID string
23+
authenticated bool
2224
}
2325

2426
// Hub maintains the set of active clients, broadcasts messages, and stores the current workspace per roomID
@@ -37,6 +39,31 @@ type Message struct {
3739
content []byte
3840
}
3941

42+
func verifyToken(token string) bool {
43+
client := &http.Client{}
44+
req, err := http.NewRequest("GET", "http://localhost:3001/auth/verify-token", nil)
45+
if err != nil {
46+
log.Println("Error creating request:", err)
47+
return false
48+
}
49+
50+
req.Header.Set("Authorization", "Bearer " + token)
51+
52+
resp, err := client.Do(req)
53+
if err != nil {
54+
log.Println("Error making request:", err)
55+
return false
56+
}
57+
defer resp.Body.Close()
58+
59+
if resp.StatusCode != http.StatusOK {
60+
log.Println("Token verification failed with status:", resp.Status)
61+
return false
62+
}
63+
64+
return true;
65+
}
66+
4067
// NewHub creates a new hub instance
4168
func NewHub() *Hub {
4269
return &Hub{
@@ -116,6 +143,32 @@ func handleMessages(client *Client, hub *Hub) {
116143
break
117144
}
118145

146+
var msgData map[string]interface{}
147+
if err := json.Unmarshal(message, &msgData); err != nil {
148+
log.Printf("Failed to parse message: %v", err)
149+
continue
150+
}
151+
152+
// Handle authentication message
153+
if msgData["type"] == "auth" {
154+
token, ok := msgData["token"].(string)
155+
if !ok {
156+
log.Printf("Auth message missing token")
157+
continue
158+
}
159+
if verifyToken(token) { // Implement this function to verify the token
160+
client.authenticated = true
161+
log.Println("Client authenticated successfully")
162+
} else {
163+
log.Println("Invalid auth token")
164+
client.conn.WriteMessage(websocket.TextMessage, []byte("Authentication failed"))
165+
client.conn.Close()
166+
break
167+
}
168+
continue
169+
}
170+
171+
119172
// Broadcast the message to other clients
120173
hub.broadcast <- Message{roomID: client.roomID, content: message}
121174
}

matching-service-api/log/matching_service_api.log

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,5 @@ time="2024-10-16T12:12:09+08:00" level=info msg="request from user user1 success
3333
time="2024-10-16T12:12:14+08:00" level=info msg="request from user user2 successfully published"
3434
time="2024-10-16T12:16:10+08:00" level=info msg="request from user user1 successfully published"
3535
time="2024-10-16T12:16:15+08:00" level=info msg="request from user user2 successfully published"
36+
time="2024-10-25T22:40:44+08:00" level=info msg="Server started at time: 2024-10-25 22:40:44.6771508 +0800 +08 m=+0.090065801"
37+
time="2024-10-25T23:25:28+08:00" level=info msg="request from user 6702c9a3f1217a1b2123575b successfully published"

matching-service/log/matching_service.log

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,6 @@ time="2024-10-17T22:43:06+08:00" level=info msg="Beginning consumption from mess
2323
time="2024-10-17T22:43:06+08:00" level=info msg="Begin processing requests"
2424
time="2024-10-17T22:51:23+08:00" level=info msg="Beginning consumption from message queue"
2525
time="2024-10-17T22:51:23+08:00" level=info msg="Begin processing requests"
26+
time="2024-10-25T22:40:12+08:00" level=info msg="Beginning consumption from message queue"
27+
time="2024-10-25T22:40:12+08:00" level=info msg="Begin processing requests"
28+
time="2024-10-25T23:25:28+08:00" level=error msg="error handling incoming request: dial tcp [::1]:6379: connectex: No connection could be made because the target machine actively refused it."

peerprep/api/gateway.ts

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
import { cookies } from "next/headers";
2-
import { LoginResponse, Question, UserServiceResponse, StatusBody } from "./structs";
2+
import {
3+
LoginResponse,
4+
Question,
5+
UserServiceResponse,
6+
StatusBody,
7+
} from "./structs";
38
import DOMPurify from "isomorphic-dompurify";
49

510
export function generateAuthHeaders() {
611
return {
7-
"Authorization": `Bearer ${cookies().get("session")?.value}`,
8-
};;
12+
Authorization: `Bearer ${cookies().get("session")?.value}`,
13+
};
14+
}
15+
16+
export function getSessionToken() {
17+
return cookies().get("session")?.value;
918
}
1019

1120
export function generateJSONHeaders() {
@@ -16,15 +25,15 @@ export function generateJSONHeaders() {
1625
}
1726

1827
export async function fetchQuestion(
19-
questionId: string,
28+
questionId: string
2029
): Promise<Question | StatusBody> {
2130
try {
2231
const response = await fetch(
2332
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions/solve/${questionId}`,
2433
{
2534
method: "GET",
2635
headers: generateAuthHeaders(),
27-
},
36+
}
2837
);
2938
if (!response.ok) {
3039
return {
@@ -56,7 +65,7 @@ export async function getSessionLogin(validatedFields: {
5665
headers: {
5766
"Content-type": "application/json; charset=UTF-8",
5867
},
59-
},
68+
}
6069
);
6170
const json = await res.json();
6271

peerprep/api/structs.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export interface MatchData {
5959
roomId: string;
6060
user1: string;
6161
user2: string;
62+
QuestionId: string
6263
}
6364

6465
export interface MatchResponse {

peerprep/app/questions/[question]/[roomID]/page.tsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { fetchQuestion } from "@/api/gateway";
1+
import { fetchQuestion, getSessionToken } from "@/api/gateway";
22
import { Question as QnType, StatusBody, isError } from "@/api/structs";
33
import styles from "@/style/question.module.css";
44
import ErrorBlock from "@/components/shared/ErrorBlock";
@@ -20,7 +20,11 @@ async function Question({ params }: Props) {
2020
{isError(question) ? (
2121
<ErrorBlock err={question as StatusBody} />
2222
) : (
23-
<QuestionBlock question={question as QnType} roomID={params.roomID} />
23+
<QuestionBlock
24+
question={question as QnType}
25+
roomID={params.roomID}
26+
authToken={getSessionToken()}
27+
/>
2428
)}
2529
</div>
2630
);

peerprep/app/questions/[question]/[roomID]/question.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import DOMPurify from "dompurify";
1212
interface Props {
1313
question: Question;
1414
roomID?: String;
15+
authToken?: String;
1516
}
1617

1718
interface DifficultyChipProps {
@@ -28,7 +29,7 @@ function DifficultyChip({ diff }: DifficultyChipProps) {
2829
);
2930
}
3031

31-
function QuestionBlock({ question, roomID }: Props) {
32+
function QuestionBlock({ question, roomID, authToken }: Props) {
3233
const router = useRouter();
3334

3435
const handleDelete = async () => {

peerprep/components/questionpage/CollabEditor.tsx

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,10 @@ themes.forEach((theme) => require(`ace-builds/src-noconflict/theme-${theme}`));
4545
interface Props {
4646
question: Question;
4747
roomID?: String;
48+
authToken?: String;
4849
}
4950

50-
export default function CollabEditor({ question, roomID }: Props) {
51+
export default function CollabEditor({ question, roomID, authToken }: Props) {
5152
const [theme, setTheme] = useState("terminal");
5253
const [fontSize, setFontSize] = useState(18);
5354
const [language, setLanguage] = useState("python");
@@ -76,15 +77,24 @@ export default function CollabEditor({ question, roomID }: Props) {
7677
newSocket.onopen = () => {
7778
console.log("WebSocket connection established");
7879
setConnected(true);
80+
81+
const authMessage = {
82+
type: "auth",
83+
token: authToken,
84+
};
85+
newSocket.send(JSON.stringify(authMessage));
7986
};
8087

8188
newSocket.onmessage = (event) => {
89+
if (event.data == "Authentication failed") {
90+
console.log("Authentication failed");
91+
return;
92+
}
93+
8294
const message = JSON.parse(event.data);
83-
console.log("Received WebSocket message:", message);
8495

85-
// Handle incoming WebSocket messages
8696
if (message.type === "content_change") {
87-
setValue(message.data); // Update the editor value
97+
setValue(message.data);
8898
}
8999
};
90100

peerprep/components/questionpage/Matchmaking.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,9 @@ const Matchmaking = () => {
134134
User2: ${matchRes.data.user2}`;
135135
window.alert(message);
136136
// redirect to question page
137-
router.push(`/questions/1/${matchRes.data.roomId}`);
137+
router.push(
138+
`/questions/${matchRes.data.QuestionId}/${matchRes.data.roomId}`
139+
);
138140
};
139141

140142
usePeriodicCallback(queryResource, QUERY_INTERVAL_MILLISECONDS, isMatching);

storage-blob-api/log/matching_service_api.log

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,10 @@ time="2024-10-16T11:55:08+08:00" level=error msg="unable to unmarshal topicTags
88
time="2024-10-16T11:57:16+08:00" level=info msg="Server started running successfully"
99
time="2024-10-16T12:15:40+08:00" level=info msg="Server started running successfully"
1010
time="2024-10-16T12:16:23+08:00" level=info msg="Request handled successfully"
11+
time="2024-10-25T22:39:43+08:00" level=info msg="Server started running successfully"
12+
time="2024-10-25T23:25:33+08:00" level=error msg="error retrieving userId from database: dial tcp 127.0.0.1:6379: connectex: No connection could be made because the target machine actively refused it."
13+
time="2024-10-25T23:25:38+08:00" level=error msg="error retrieving userId from database: dial tcp 127.0.0.1:6379: connectex: No connection could be made because the target machine actively refused it."
14+
time="2024-10-25T23:25:43+08:00" level=error msg="error retrieving userId from database: dial tcp 127.0.0.1:6379: connectex: No connection could be made because the target machine actively refused it."
15+
time="2024-10-25T23:25:48+08:00" level=error msg="error retrieving userId from database: dial tcp 127.0.0.1:6379: connectex: No connection could be made because the target machine actively refused it."
16+
time="2024-10-25T23:25:53+08:00" level=error msg="error retrieving userId from database: dial tcp 127.0.0.1:6379: connectex: No connection could be made because the target machine actively refused it."
17+
time="2024-10-25T23:25:58+08:00" level=error msg="error retrieving userId from database: dial tcp 127.0.0.1:6379: connectex: No connection could be made because the target machine actively refused it."

0 commit comments

Comments
 (0)