card-jong-be/controller/lobbyws.go

113 lines
2.1 KiB
Go
Raw Normal View History

2024-05-21 14:09:23 +00:00
package controller
import (
2024-05-25 21:17:48 +00:00
"encoding/json"
2024-07-09 23:37:53 +00:00
"errors"
2024-05-21 14:09:23 +00:00
"log"
"net/http"
2024-07-09 23:37:53 +00:00
"strings"
2024-05-21 14:09:23 +00:00
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
2024-05-25 21:17:48 +00:00
type LobbyMsg struct {
2024-07-09 23:37:53 +00:00
Action string `json:"action"`
Value string `json:"value"`
2024-05-25 21:17:48 +00:00
}
2024-05-21 14:09:23 +00:00
func LobbyWsConnect(writer http.ResponseWriter, request *http.Request) {
conn, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
2024-05-25 21:17:48 +00:00
log.Print("upgrade error:", err)
2024-05-21 14:09:23 +00:00
return
}
defer conn.Close()
for {
mt, message, err := conn.ReadMessage()
if err != nil {
2024-05-25 21:17:48 +00:00
log.Print("read error:", err)
2024-05-21 14:09:23 +00:00
break
}
log.Printf("recv: %s, type: %d", message, mt)
2024-05-25 21:17:48 +00:00
var data LobbyMsg
err = json.Unmarshal(message, &data)
if err != nil {
log.Print("json error:", err)
break
}
switch data.Action {
case "auth":
2024-07-09 23:37:53 +00:00
err = authenticateConnection(mt, conn, data.Value)
2024-05-25 21:17:48 +00:00
default:
log.Print("no action :c")
}
2024-05-21 14:09:23 +00:00
if err != nil {
2024-05-25 21:17:48 +00:00
log.Print("error:", err)
2024-05-21 14:09:23 +00:00
break
}
}
}
2024-05-25 21:17:48 +00:00
2024-07-09 23:37:53 +00:00
// 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 ','
2024-05-25 21:17:48 +00:00
2024-07-09 23:37:53 +00:00
var err error
var result string
2024-05-25 21:17:48 +00:00
2024-07-09 23:37:53 +00:00
authSections := strings.Split(authInfo, ",")
if len(authSections) != 2 {
err = errors.New("Expected 2 components to auth, in string " + authInfo)
result = "unauthenticated"
2024-05-25 21:17:48 +00:00
} else {
2024-07-09 23:37:53 +00:00
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)
2024-05-25 21:17:48 +00:00
}
2024-07-09 23:37:53 +00:00
json, err := json.Marshal(LobbyMsg{
Action: "auth",
Value: result,
})
2024-05-25 21:17:48 +00:00
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
}