89 lines
1.8 KiB
Go
89 lines
1.8 KiB
Go
package controller
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/nrednav/cuid2"
|
|
)
|
|
|
|
// TODO: This struct should have a creation time
|
|
type Lobby struct {
|
|
LobbyOwner string
|
|
LobbyPlayers []string
|
|
}
|
|
|
|
type LobbyResult struct {
|
|
LobbyId string
|
|
}
|
|
|
|
type LobbyCreateInput struct {
|
|
UserId string
|
|
}
|
|
|
|
// 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")
|
|
|
|
authOk := AuthHeaderIsValid(request.Header.Get("Authorization"))
|
|
if !authOk {
|
|
writer.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
lobbyId := cuid2.Generate()
|
|
|
|
result := LobbyResult{LobbyId: lobbyId}
|
|
lobbies[lobbyId] = Lobby{
|
|
LobbyOwner: data.UserId,
|
|
LobbyPlayers: make([]string, 3),
|
|
}
|
|
log.Printf("Created lobby with id %s/%s", lobbyId, data.UserId)
|
|
|
|
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)
|
|
}
|
|
|
|
// 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
|
|
}
|