Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,11 +609,6 @@ const docTemplate = `{
},
"/chat/ws": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Establece una conexión WebSocket para mensajería en tiempo real",
"consumes": [
"application/json"
Expand All @@ -625,6 +620,15 @@ const docTemplate = `{
"Chat"
],
"summary": "Conexión WebSocket para chat en tiempo real",
"parameters": [
{
"type": "string",
"description": "Firebase Auth Token",
"name": "token",
"in": "query",
"required": true
}
],
"responses": {
"101": {
"description": "Switching Protocols a WebSocket",
Expand Down
14 changes: 9 additions & 5 deletions docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -602,11 +602,6 @@
},
"/chat/ws": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Establece una conexión WebSocket para mensajería en tiempo real",
"consumes": [
"application/json"
Expand All @@ -618,6 +613,15 @@
"Chat"
],
"summary": "Conexión WebSocket para chat en tiempo real",
"parameters": [
{
"type": "string",
"description": "Firebase Auth Token",
"name": "token",
"in": "query",
"required": true
}
],
"responses": {
"101": {
"description": "Switching Protocols a WebSocket",
Expand Down
8 changes: 6 additions & 2 deletions docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,12 @@ paths:
consumes:
- application/json
description: Establece una conexión WebSocket para mensajería en tiempo real
parameters:
- description: Firebase Auth Token
in: query
name: token
required: true
type: string
produces:
- application/json
responses:
Expand All @@ -514,8 +520,6 @@ paths:
description: No autorizado
schema:
type: string
security:
- BearerAuth: []
summary: Conexión WebSocket para chat en tiempo real
tags:
- Chat
Expand Down
33 changes: 26 additions & 7 deletions internal/handlers/websocket_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handlers
import (
"log"
"net/http"
"strings"

"github.com/Parchat/backend/internal/config"
pws "github.com/Parchat/backend/internal/pkg/websocket"
Expand Down Expand Up @@ -38,15 +39,33 @@ func NewWebSocketHandler(hub *pws.Hub, firebaseAuth *config.FirebaseAuth) *WebSo
// @Tags Chat
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 101 {string} string "Switching Protocols a WebSocket"
// @Failure 401 {string} string "No autorizado"
// @Param token query string true "Firebase Auth Token"
// @Success 101 {string} string "Switching Protocols a WebSocket"
// @Failure 401 {string} string "No autorizado"
// @Router /chat/ws [get]
func (h *WebSocketHandler) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
// Verificar el token desde el contexto (añadido por el middleware de autenticación)
userID, ok := r.Context().Value("userID").(string)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
// Extraer el token desde el parámetro de consulta
token := r.URL.Query().Get("token")
if token == "" {
http.Error(w, "Token not provided", http.StatusUnauthorized)
return
}

// Limpiar el token (por si viene con "Bearer ")
token = strings.TrimPrefix(token, "Bearer ")

// Verificar el token con Firebase
authToken, err := h.firebaseAuth.VerifyIDToken(r.Context(), token)
if err != nil {
log.Printf("Error verifying token: %v", err)
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}

// Extraer el userID del token verificado
userID := authToken.UID
if userID == "" {
http.Error(w, "Invalid user ID in token", http.StatusUnauthorized)
return
}

Expand Down
39 changes: 20 additions & 19 deletions internal/routes/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,28 +56,29 @@ func NewRouter(

// Rutas de chat (protegidas)
r.Route("/chat", func(r chi.Router) {
// Aplicar middleware de autenticación
r.Use(authMw.VerifyToken)
// WebSocket endpoint
r.Get("/ws", webSocketHandler.HandleWebSocket)

// Rutas de salas
r.Route("/rooms", func(r chi.Router) {
r.Post("/", chatHandler.CreateRoom)
r.Get("/me", chatHandler.GetUserRooms)
r.Get("/", chatHandler.GetAllRooms)
r.Get("/{roomId}", chatHandler.GetRoom)
r.Get("/{roomId}/messages", chatHandler.GetRoomMessages)
r.Post("/{roomId}/join", chatHandler.JoinRoom)
})
r.Group(func(r chi.Router) {
r.Use(authMw.VerifyToken) // Aplicar middleware de autenticación

// Rutas de chats directos
r.Route("/direct", func(r chi.Router) {
r.Post("/{otherUserId}", chatHandler.CreateDirectChat)
r.Get("/me", chatHandler.GetUserDirectChats)
r.Get("/{chatId}/messages", chatHandler.GetDirectChatMessages)
})
// Rutas de salas
r.Route("/rooms", func(r chi.Router) {
r.Post("/", chatHandler.CreateRoom)
r.Get("/me", chatHandler.GetUserRooms)
r.Get("/", chatHandler.GetAllRooms)
r.Get("/{roomId}", chatHandler.GetRoom)
r.Get("/{roomId}/messages", chatHandler.GetRoomMessages)
r.Post("/{roomId}/join", chatHandler.JoinRoom)
})

// WebSocket endpoint
r.Get("/ws", webSocketHandler.HandleWebSocket)
// Rutas de chats directos
r.Route("/direct", func(r chi.Router) {
r.Post("/{otherUserId}", chatHandler.CreateDirectChat)
r.Get("/me", chatHandler.GetUserDirectChats)
r.Get("/{chatId}/messages", chatHandler.GetDirectChatMessages)
})
})
})
})

Expand Down