WebSocketServer/main.go

86 lines
2.1 KiB
Go

package main
import (
"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/utils"
"clickandjoin.app/websocketserver/socketserver"
gocnjhelper "git.clickandjoin.umbach.dev/ClickandJoin/go-cnj-helper"
"git.clickandjoin.umbach.dev/ClickandJoin/go-cnj-helper/dbstructs"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
func init() {
config.LoadConfig()
cfg := config.Cfg
gocnjhelper.InitLogger(cfg.Debug,
true,
true,
gocnjhelper.GetConnectionString(cfg.RabbitMq.Username, cfg.RabbitMq.Password, cfg.RabbitMq.Host),
cfg.ServiceName,
cfg.ServiceType)
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 := dbstructs.UserWebSocketSession{Id: wsSessionId}
q := scylladb.Session.Query(gocnjhelper.DbMWebSocketSessions.Get("id", "user_id")).BindStruct(foundWsSession)
if err := q.GetRelease(&foundWsSession); err != nil {
gocnjhelper.LogDebugf("Failed to find ws session: %s, err: %s", wsSessionId, err)
return c.SendStatus(fiber.StatusUnauthorized)
}
// TODO: Further security checks such as the change of IP, user agents
c.Locals("wsSessionId", wsSessionId)
c.Locals("userId", foundWsSession.UserId)
return c.Next()
}
return fiber.ErrUpgradeRequired
})
go socketserver.RunHub()
socketserver.WebSocketServer(app)
cfg := config.Cfg
app.Listen(cfg.Host + ":" + cfg.Port)
}