added session closed

main
alex 2023-05-15 21:14:59 +02:00
parent 704ae06edd
commit 61d6c5ee0f
3 changed files with 26 additions and 8 deletions

View File

@ -10,6 +10,12 @@ import (
"github.com/rs/zerolog/log"
)
const (
// Note: Status codes in the range 4000-4999 are reserved for private use
SocketCloseCodeUnauthorized = 4001
SocketCloseCodeSessionClosed = 4002 // when user logs out of the session and has multiple tabs with the same session open
)
type SocketClient struct {
SessionId string
UserId string
@ -32,25 +38,24 @@ type ReceivedMessage struct {
Body map[string]interface{}
}
func (socketClient *SocketClient) SendCloseMessage() error {
return socketClient.writeMessage(websocket.CloseMessage, SendSocketMessage{}, true)
func (socketClient *SocketClient) SendSessionClosedMessage() error {
return socketClient.writeMessage(websocket.CloseMessage, SendSocketMessage{}, SocketCloseCodeSessionClosed)
}
func (socketClient *SocketClient) SendUnauthorizedCloseMessage() error {
return socketClient.writeMessage(websocket.CloseMessage, SendSocketMessage{}, true)
return socketClient.writeMessage(websocket.CloseMessage, SendSocketMessage{}, SocketCloseCodeUnauthorized)
}
func (socketClient *SocketClient) SendMessage(message SendSocketMessage) error {
return socketClient.writeMessage(websocket.TextMessage, message, false)
return socketClient.writeMessage(websocket.TextMessage, message, 0)
}
func (socketClient *SocketClient) writeMessage(messageType int, message SendSocketMessage, closeMessage bool) error {
func (socketClient *SocketClient) writeMessage(messageType int, message SendSocketMessage, closeMessageCode int) error {
var marshaledMessage []byte
var err error
if closeMessage {
// Status codes in the range 4000-4999 are reserved for private use
marshaledMessage = websocket.FormatCloseMessage(4001, "")
if closeMessageCode > 0 {
marshaledMessage = websocket.FormatCloseMessage(closeMessageCode, "")
} else {
marshaledMessage, err = json.Marshal(message)

View File

@ -6,6 +6,7 @@ import (
"janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/socketclients"
"math/big"
"github.com/gofiber/fiber/v2"
@ -78,6 +79,8 @@ func UserLogout(c *fiber.Ctx) error {
database.DB.Delete(&structs.UserSession{}, "id = ?", session)
socketclients.CloseAllUserSessionConnections(session)
return c.SendStatus(fiber.StatusCreated)
}

View File

@ -28,6 +28,16 @@ func SendMessageToUser(userId string, ignoreUserSessionId string, sendSocketMess
}
}
// This close all connections that are connected with one session id.
// For example when a user has two browser tabs opened
func CloseAllUserSessionConnections(sessionId string) {
for _, client := range cache.GetSocketClients() {
if client.SessionId == sessionId {
client.SendSessionClosedMessage()
}
}
}
func GetUserSessions(userId string) []structs.UserSessionSocket {
var userSessions []structs.UserSession