Skip to content

Commit c2f0dbb

Browse files
committed
Add room verification
1 parent a09ab51 commit c2f0dbb

File tree

9 files changed

+283
-47
lines changed

9 files changed

+283
-47
lines changed

collab/go.mod

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
1-
module gin-gonic/gin
2-
1+
module collab
32
go 1.20
43

4+
require (
5+
github.com/gin-gonic/gin v1.10.0
6+
github.com/go-redis/redis/v8 v8.11.5
7+
github.com/gorilla/websocket v1.5.3
8+
)
9+
510
require (
611
github.com/bytedance/sonic v1.11.6 // indirect
712
github.com/bytedance/sonic/loader v0.1.1 // indirect
13+
github.com/cespare/xxhash/v2 v2.1.2 // indirect
814
github.com/cloudwego/base64x v0.1.4 // indirect
915
github.com/cloudwego/iasm v0.2.0 // indirect
16+
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
1017
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
1118
github.com/gin-contrib/sse v0.1.0 // indirect
12-
github.com/gin-gonic/gin v1.10.0
1319
github.com/go-playground/locales v0.14.1 // indirect
1420
github.com/go-playground/universal-translator v0.18.1 // indirect
1521
github.com/go-playground/validator/v10 v10.20.0 // indirect
1622
github.com/goccy/go-json v0.10.2 // indirect
17-
github.com/gorilla/websocket v1.5.3
1823
github.com/json-iterator/go v1.1.12 // indirect
1924
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
2025
github.com/leodido/go-urn v1.4.0 // indirect

collab/go.sum

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,36 @@ github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc
22
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
33
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
44
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
5+
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
6+
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
57
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
68
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
79
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
810
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
911
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
12+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
1013
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
14+
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
15+
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
16+
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
1117
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
1218
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
1319
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
1420
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
1521
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
1622
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
23+
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
1724
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
1825
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
1926
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
2027
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
2128
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
2229
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
30+
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
31+
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
2332
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
2433
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
34+
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
2535
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
2636
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
2737
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
@@ -40,8 +50,12 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
4050
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
4151
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
4252
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
53+
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
54+
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
55+
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
4356
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
4457
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
58+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
4559
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
4660
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
4761
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
@@ -53,6 +67,7 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
5367
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
5468
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
5569
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
70+
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
5671
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
5772
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
5873
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
@@ -71,9 +86,13 @@ golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
7186
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
7287
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
7388
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
89+
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
7490
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
7591
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
92+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
7693
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
94+
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
95+
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
7796
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
7897
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
7998
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

collab/main.go

Lines changed: 62 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package main
22

33
import (
4+
verify "collab/verify"
45
"encoding/json"
6+
"io"
57
"log"
68
"net/http"
79
"os"
@@ -37,33 +39,57 @@ type Message struct {
3739
content []byte
3840
}
3941

40-
func verifyToken(token string) bool {
42+
func verifyToken(token string) (bool, string) {
4143
client := &http.Client{}
4244
USER_SERVICE_URI := os.Getenv("USER_SERVICE_URI")
4345
if USER_SERVICE_URI == "" {
4446
USER_SERVICE_URI = "http://localhost:3001"
4547
}
46-
req, err := http.NewRequest("GET", USER_SERVICE_URI + "/auth/verify-token", nil)
48+
req, err := http.NewRequest("GET", USER_SERVICE_URI+"/auth/verify-token", nil)
4749
if err != nil {
4850
log.Println("Error creating request:", err)
49-
return false
51+
return false, ""
5052
}
5153

52-
req.Header.Set("Authorization", "Bearer " + token)
54+
req.Header.Set("Authorization", "Bearer "+token)
5355

5456
resp, err := client.Do(req)
5557
if err != nil {
5658
log.Println("Error making request:", err)
57-
return false
59+
return false, ""
5860
}
5961
defer resp.Body.Close()
6062

63+
var response struct {
64+
Message string `json:"message"`
65+
Data struct {
66+
ID string `json:"id"`
67+
Username string `json:"username"`
68+
Email string `json:"email"`
69+
IsAdmin bool `json:"isAdmin"`
70+
} `json:"data"`
71+
}
72+
73+
body, err := io.ReadAll(resp.Body)
74+
if err != nil {
75+
log.Println("Error reading response body:", err)
76+
return false, ""
77+
}
78+
79+
// Unmarshal the response body into the struct
80+
if err := json.Unmarshal(body, &response); err != nil {
81+
log.Println("Error unmarshaling response:", err)
82+
return false, ""
83+
}
84+
85+
// Check if the token was verified successfully
6186
if resp.StatusCode != http.StatusOK {
6287
log.Println("Token verification failed with status:", resp.Status)
63-
return false
88+
return false, ""
6489
}
6590

66-
return true;
91+
// Return true and the ID from the response
92+
return true, response.Data.ID
6793
}
6894

6995
// NewHub creates a new hub instance
@@ -114,7 +140,7 @@ func (h *Hub) Run() {
114140
}
115141

116142
// ServeWs handles WebSocket requests
117-
func serveWs(hub *Hub, c *gin.Context) {
143+
func serveWs(hub *Hub, c *gin.Context, roomMappings *verify.RoomMappings) {
118144
roomID := c.Query("roomID")
119145
if roomID == "" {
120146
http.Error(c.Writer, "roomID required", http.StatusBadRequest)
@@ -130,10 +156,19 @@ func serveWs(hub *Hub, c *gin.Context) {
130156
client := &Client{conn: conn, roomID: roomID}
131157
hub.register <- client
132158

133-
go handleMessages(client, hub)
159+
go handleMessages(client, hub, roomMappings)
160+
}
161+
162+
func authenticateClient(token string, client *Client, roomMappings *verify.RoomMappings) bool {
163+
ok, userID := verifyToken(token)
164+
if !ok {
165+
log.Println("bruh")
166+
return false
167+
}
168+
return verify.VerifyRoom(roomMappings, client.roomID, userID)
134169
}
135170

136-
func handleMessages(client *Client, hub *Hub) {
171+
func handleMessages(client *Client, hub *Hub, roomMappings *verify.RoomMappings) {
137172
defer func() {
138173
hub.unregister <- client
139174
}()
@@ -150,25 +185,18 @@ func handleMessages(client *Client, hub *Hub) {
150185
log.Printf("Failed to parse message: %v", err)
151186
continue
152187
}
153-
154188
// Handle authentication message
155189
if msgData["type"] == "auth" {
156-
token, ok := msgData["token"].(string)
157-
if !ok {
158-
log.Printf("Auth message missing token")
159-
continue
160-
}
161-
if verifyToken(token) { // Implement this function to verify the token
162-
client.authenticated = true
163-
log.Println("Client authenticated successfully")
164-
} else {
165-
log.Println("Invalid auth token")
166-
client.conn.WriteMessage(websocket.TextMessage, []byte("Authentication failed"))
167-
client.conn.Close()
168-
break
169-
}
170-
continue
171-
}
190+
token, ok := msgData["token"].(string)
191+
if !ok || !authenticateClient(token, client, roomMappings) {
192+
log.Println("Authentication failed")
193+
client.conn.WriteMessage(websocket.TextMessage, []byte("Authentication failed"))
194+
client.conn.Close()
195+
break
196+
}
197+
client.authenticated = true
198+
log.Println("Client authenticated successfully")
199+
}
172200

173201
if msgData["type"] == "close_session" {
174202
closeMessage := Message{
@@ -218,9 +246,15 @@ func main() {
218246
hub := NewHub()
219247
go hub.Run()
220248

249+
REDIS_URI := os.Getenv("REDIS_URI")
250+
if REDIS_URI == "" {
251+
REDIS_URI = "localhost:9190"
252+
}
253+
roomMappings := verify.InitialiseRoomMappings(REDIS_URI, 1)
254+
221255
// WebSocket connection endpoint
222256
r.GET("/ws", func(c *gin.Context) {
223-
serveWs(hub, c)
257+
serveWs(hub, c, roomMappings)
224258
})
225259

226260
// Status endpoint

collab/verify/roomMappings.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package verify
2+
3+
import (
4+
"context"
5+
"log"
6+
7+
redis "github.com/go-redis/redis/v8"
8+
)
9+
10+
// same as client mappings, but separated for type safety
11+
type RoomMappings struct {
12+
Conn *redis.Client
13+
}
14+
15+
func InitialiseRoomMappings(addr string, db_num int) *RoomMappings {
16+
conn := redis.NewClient(&redis.Options{
17+
Addr: addr,
18+
DB: db_num,
19+
})
20+
21+
return &RoomMappings{
22+
Conn: conn,
23+
}
24+
}
25+
26+
func VerifyRoom(roomMappings *RoomMappings, roomID string, userID string) bool {
27+
data, err := roomMappings.Conn.HGetAll(context.Background(), userID).Result()
28+
if err != nil {
29+
log.Printf("Error retrieving data for userID %s: %v", userID, err)
30+
return false
31+
}
32+
33+
return data["roomId"] == roomID
34+
}

0 commit comments

Comments
 (0)