card-jong-be/controller/lobbyws.go

113 lines
2.1 KiB
Go

package controller
import (
"encoding/json"
"errors"
"log"
"net/http"
"strings"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type LobbyMsg struct {
Action string `json:"action"`
Value string `json:"value"`
}
func LobbyWsConnect(writer http.ResponseWriter, request *http.Request) {
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
log.Print("upgrade error:", err)
return
}
defer conn.Close()
for {
mt, message, err := conn.ReadMessage()
if err != nil {
log.Print("read error:", err)
break
}
log.Printf("recv: %s, type: %d", message, mt)
var data LobbyMsg
err = json.Unmarshal(message, &data)
if err != nil {
log.Print("json error:", err)
break
}
switch data.Action {
case "auth":
err = authenticateConnection(mt, conn, data.Value)
default:
log.Print("no action :c")
}
if err != nil {
log.Print("error:", err)
break
}
}
}
// Verifies that the user id & lobby id are valid, and that the user has permission to
// access the lobby
func authenticateConnection(mt int, conn *websocket.Conn, authInfo string) error {
// TODO: split userId by ','
var err error
var result string
authSections := strings.Split(authInfo, ",")
if len(authSections) != 2 {
err = errors.New("Expected 2 components to auth, in string " + authInfo)
result = "unauthenticated"
} else {
userId := authSections[0]
lobbyId := authSections[1]
if !VerifyLobbyAccess(userId, lobbyId) {
log.Printf("Unathorized to enter lobby: user %s to lobby %s", userId, lobbyId)
result = "unauthenticated"
} else {
_, ok := Users[userId]
// TODO: Verify lobby id
if ok {
result = "authenticated"
} else {
result = "unauthenticated"
}
}
}
if err != nil {
log.Print("auth error: ", err)
}
json, err := json.Marshal(LobbyMsg{
Action: "auth",
Value: result,
})
if err != nil {
log.Print("json marshal: ", err)
return err
}
err = conn.WriteMessage(mt, json)
if err != nil {
log.Print("write error: ", err)
}
return err
}