Skip to content

Commit

Permalink
Refactor WebSocket client handling and token validation
Browse files Browse the repository at this point in the history
Centralize WebSocket client initialization in the main server setup and remove redundant code. Introduce middleware token validation in WebSocket connections to verify user authenticity and enhance logging for client connections and disconnections.
  • Loading branch information
mukulmantosh committed Sep 18, 2024
1 parent 8bf2083 commit 1eb9df1
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 11 deletions.
4 changes: 3 additions & 1 deletion cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ func main() {
// Connect NATS
natServer, err := nats.NewNATS()

// WebSocket Clients
wsClients := make(map[string]*websocket.Conn)

s := handler.NewServer(db)

// Initialize Validator
Expand Down Expand Up @@ -71,7 +74,6 @@ func main() {
delv.NewDeliveryHandler(s, "/delivery", deliveryService, middlewares, validate)

// Notification
wsClients := make(map[string]*websocket.Conn)
notifyService := notification.NewNotificationService(db, env, natServer)
err = notifyService.SubscribeNewOrders(wsClients)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions cmd/api/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type UserClaims struct {
jwt.RegisteredClaims
}

func validateToken(token string) (bool, int64) {
func ValidateToken(token string) (bool, int64) {

tokenInfo, err := jwt.ParseWithClaims(token, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET_KEY")), nil
Expand Down Expand Up @@ -50,7 +50,7 @@ func AuthMiddleware() gin.HandlerFunc {
}
token := tokenParts[1]

tokenValidation, userID := validateToken(token)
tokenValidation, userID := ValidateToken(token)
if !tokenValidation {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Token"})
c.Abort()
Expand Down
20 changes: 15 additions & 5 deletions pkg/handler/notification/notify.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package notification

import (
"Go_Food_Delivery/cmd/api/middleware"
"github.com/gin-gonic/gin"
"log"
"strconv"
)

func (s *NotifyHandler) notifyOrders(c *gin.Context) {
Expand All @@ -19,15 +21,23 @@ func (s *NotifyHandler) notifyOrders(c *gin.Context) {
conn.Close()
return
}
userId := "1"
s.clients[userId] = conn
log.Printf("New client connected::%s", userId)
valid, userIdInt := middleware.ValidateToken(token)
if !valid {
log.Println("Invalid Token!")
conn.Close()
return
}

userID := strconv.FormatInt(userIdInt, 10)

s.clients[userID] = conn
log.Printf("New client connected::%s", userID)

for {
_, _, err := conn.ReadMessage()
if err != nil {
log.Printf("Client disconnected: %s::%v", userId, err)
delete(s.clients, userId)
log.Printf("Client disconnected: %s::%v", userID, err)
delete(s.clients, userID)
break
}
}
Expand Down
3 changes: 0 additions & 3 deletions pkg/nats/nats_server.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package nats

import (
"fmt"
"github.com/gorilla/websocket"
"github.com/nats-io/nats.go"
"log"
Expand Down Expand Up @@ -34,10 +33,8 @@ func (n *NATS) Sub(topic string, clients map[string]*websocket.Conn) error {
_, err := n.Conn.Subscribe(topic, func(msg *nats.Msg) {
message := string(msg.Data)
slog.Info("MESSAGE_REPLY_FROM_NATS", "RECEIVED_MESSAGE", message)
fmt.Println("CLIENTS::", clients)
userId, messageData := n.formatMessage(message)
if conn, ok := clients[userId]; ok {
fmt.Println("SENDING_MESSAGE_TO_CLIENT")
err := conn.WriteMessage(websocket.TextMessage, []byte(messageData))
if err != nil {
log.Println("Error sending message to client:", err)
Expand Down

0 comments on commit 1eb9df1

Please sign in to comment.