WebSocketServer/main.go

94 lines
2.3 KiB
Go

package main
import (
"os"
"time"
"clickandjoin.app/websocketserver/modules/config"
"clickandjoin.app/websocketserver/modules/rabbitmq"
"clickandjoin.app/websocketserver/modules/redis"
"clickandjoin.app/websocketserver/modules/scylladb"
"clickandjoin.app/websocketserver/modules/structs"
"clickandjoin.app/websocketserver/modules/utils"
"clickandjoin.app/websocketserver/socketserver"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
"github.com/sirupsen/logrus"
)
func init() {
config.LoadConfig()
if config.Cfg.Debug {
logrus.SetLevel(logrus.DebugLevel)
}
logrus.Println("Debug:", config.Cfg.Debug)
scylladb.InitDatabase()
redis.Init()
go rabbitmq.Init()
}
func main() {
app := fiber.New()
// wait so that rabbitmq can connect
// TODO: better way to handle this
time.Sleep(500 * time.Millisecond)
app.Use("/", func(c *fiber.Ctx) error {
// IsWebSocketUpgrade returns true if the client
// requested upgrade to the WebSocket protocol.
if websocket.IsWebSocketUpgrade(c) {
wsSessionId := c.Query("auth")
// no auth query available
if len(wsSessionId) != utils.LenWebSocketSession {
return c.SendStatus(fiber.StatusUnauthorized)
}
// validate ws session
foundWsSession := structs.UserWebSocketSession{Id: wsSessionId}
q := scylladb.Session.Query(scylladb.WebSocketSessions.Get("id", "user_id")).BindStruct(foundWsSession)
if err := q.GetRelease(&foundWsSession); err != nil {
logrus.Errorln("Failed to find ws session:", wsSessionId, "err:", err)
return c.SendStatus(fiber.StatusUnauthorized)
}
//
if redis.ExistsUserWebSocketSessionId(foundWsSession.UserId, wsSessionId) {
logrus.Println("ws id already in list")
// TODO: kick out the other connected socket with this session
} else {
redis.AddUserWebSocketSessionId(foundWsSession.UserId, wsSessionId)
}
// TODO: Further security checks such as the change of IP, user agents or whether the session ID has already opened another connection.
c.Locals("wsSessionId", wsSessionId)
c.Locals("userId", foundWsSession.UserId)
return c.Next()
}
return fiber.ErrUpgradeRequired
})
go socketserver.RunHub()
socketserver.WebSocketServer(app)
if len(os.Args) < 2 {
logrus.Fatalln("Please specify port")
}
app.Listen("127.0.0.1:" + os.Args[1])
}