card-jong-be/controller/lobby.go

89 lines
1.8 KiB
Go
Raw Normal View History

2024-05-16 21:17:41 +00:00
package controller
import (
"encoding/json"
"fmt"
2024-07-09 23:37:53 +00:00
"log"
2024-05-16 21:17:41 +00:00
"net/http"
2024-07-09 23:37:53 +00:00
"github.com/nrednav/cuid2"
2024-05-16 21:17:41 +00:00
)
// TODO: This struct should have a creation time
type Lobby struct {
LobbyOwner string
2024-07-09 23:37:53 +00:00
LobbyPlayers []string
2024-05-16 21:17:41 +00:00
}
type LobbyResult struct {
LobbyId string
}
2024-07-09 23:37:53 +00:00
type LobbyCreateInput struct {
UserId string
}
2024-05-16 21:17:41 +00:00
// TODO: We should remove entries from this map when they expire.
// TODO: Define how long lobbies last
var lobbies = make(map[string]Lobby)
func CreateLobby(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
2024-05-16 22:15:52 +00:00
authOk := AuthHeaderIsValid(request.Header.Get("Authorization"))
if !authOk {
writer.WriteHeader(http.StatusUnauthorized)
return
}
2024-07-09 23:37:53 +00:00
// Get the UserId from the JSON payload
decoder := json.NewDecoder(request.Body)
var data LobbyCreateInput
err := decoder.Decode(&data)
if err != nil {
fmt.Printf("Error in JSON decoding: %s\n", err)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "{\"error\": \"%s\"}", err)
return
}
2024-05-16 21:17:41 +00:00
lobbyId := cuid2.Generate()
result := LobbyResult{LobbyId: lobbyId}
2024-07-09 23:37:53 +00:00
lobbies[lobbyId] = Lobby{
LobbyOwner: data.UserId,
LobbyPlayers: make([]string, 3),
}
log.Printf("Created lobby with id %s/%s", lobbyId, data.UserId)
2024-05-16 21:17:41 +00:00
jsonData, err := json.Marshal(result)
if err != nil {
fmt.Printf("Error in JSON marshal: %s\n", err)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "{\"error\": \"%s\"}", err)
return
}
fmt.Fprintf(writer, "%s", jsonData)
}
2024-07-09 23:37:53 +00:00
// Verifies that the userId has access to the lobbyId
func VerifyLobbyAccess(userId, lobbyId string) bool {
lobby, ok := lobbies[lobbyId]
if !ok {
return false
}
if lobby.LobbyOwner == userId {
return true
}
for _, playerId := range lobby.LobbyPlayers {
if playerId == userId {
return true
}
}
return false
}