From 4d6ae9efc3cbd2849832bd1dffef383f73a33bab Mon Sep 17 00:00:00 2001 From: amirHosein Date: Thu, 28 May 2026 18:01:57 +0330 Subject: [PATCH] feat(authentication): authed lobby-joining method Players can now join by their authenticatied account to lobbies. Only one account can join to a specific lobby. --- Dockerfile | 5 +- internal/api/v1.go | 145 ++++++++++++++++++++------------- internal/frontend/index.go | 3 +- internal/frontend/lobby.go | 3 +- internal/game/lobby.go | 14 +++- internal/game/lobby_test.go | 14 ++-- internal/state/lobbies_test.go | 3 +- 7 files changed, 114 insertions(+), 73 deletions(-) diff --git a/Dockerfile b/Dockerfile index 07cb33c..5b2595e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,11 +27,10 @@ FROM scratch COPY --from=builder /s /dist # 2. Copy public assets (FIXED syntax) -COPY .env /.env # COPY --from=builder /public /public -# 3. Copy SSL certs (UNCOMMENTED) -# COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +# 3. Copy SSL certs +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ # 4. Security USER 248:248 diff --git a/internal/api/v1.go b/internal/api/v1.go index 1225eab..1cc3d87 100644 --- a/internal/api/v1.go +++ b/internal/api/v1.go @@ -4,6 +4,7 @@ import ( json "encoding/json" "errors" "fmt" + "io" "log" "net/http" "strconv" @@ -12,7 +13,9 @@ import ( "github.com/gofrs/uuid/v5" "golang.org/x/text/cases" "golang.org/x/text/language" + "medad.fun/internal/api/v1/middleware" "medad.fun/internal/config" + "medad.fun/internal/database" "medad.fun/internal/game" "medad.fun/internal/state" ) @@ -90,19 +93,46 @@ func (handler *V1Handler) getLobbies(writer http.ResponseWriter, _ *http.Request } } +type postLobbyBody struct { + LobbyID string `json:"lobby_id"` + Language string `json:"language"` + ScoreCalculation string `json:"score_calculation"` + DrawingTime int `json:"drawing_time"` + Rounds int `json:"rounds"` + MaxPlayers int `json:"max_players"` + WordsPerTurn int `json:"words_per_turn"` + CustomWordsPerTurn int `json:"custom_words_per_turn"` + ClientsPerIPLimit int `json:"clients_per_ip_limit"` + Public bool `json:"public"` +} + func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Request) { if err := request.ParseForm(); err != nil { http.Error(writer, err.Error(), http.StatusBadRequest) return } + // parse body + bodyReq, err := io.ReadAll(request.Body) + if err != nil { + http.Error(writer, err.Error(), http.StatusBadRequest) + return + } + var body postLobbyBody + if err := json.Unmarshal(bodyReq, &body); err != nil { + http.Error(writer, err.Error(), http.StatusBadRequest) + return + } + + log.Print(body) + var requestErrors []string // The lobby ID is normally autogenerated and it isn't advisble to set it // yourself, but for certain integrations / automations this can be useful. // However, to avoid any kind of abuse, this needs to be a valid UUID at // least. - lobbyId := request.Form.Get("lobby_id") + lobbyId := body.LobbyID if lobbyId != "" { var err error _, err = uuid.FromString(lobbyId) @@ -111,15 +141,14 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re } } - scoreCalculation, scoreCalculationInvalid := ParseScoreCalculation(request.Form.Get("score_calculation")) - languageData, languageKey, languageInvalid := ParseLanguage(request.Form.Get("language")) - drawingTime, drawingTimeInvalid := ParseDrawingTime(handler.cfg, request.Form.Get("drawing_time")) - rounds, roundsInvalid := ParseRounds(handler.cfg, request.Form.Get("rounds")) - maxPlayers, maxPlayersInvalid := ParseMaxPlayers(handler.cfg, request.Form.Get("max_players")) - wordsPerTurn, wordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("words_per_turn"), config.Default.LobbySettingBounds.MaxWordsPerTurn) - customWordsPerTurn, customWordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("custom_words_per_turn"), config.Default.LobbySettingBounds.MaxCustomWordsPerTurn) - clientsPerIPLimit, clientsPerIPLimitInvalid := ParseClientsPerIPLimit(handler.cfg, request.Form.Get("clients_per_ip_limit")) - publicLobby, publicLobbyInvalid := ParseBoolean("public", request.Form.Get("public")) + languageData, languageKey, languageInvalid := ParseLanguage(body.Language) + scoreCalculation, scoreCalculationInvalid := ParseScoreCalculation(body.ScoreCalculation) + drawingTime, drawingTimeInvalid := ParseDrawingTime(handler.cfg, strconv.Itoa(body.DrawingTime)) + rounds, roundsInvalid := ParseRounds(handler.cfg, strconv.Itoa(body.Rounds)) + maxPlayers, maxPlayersInvalid := ParseMaxPlayers(handler.cfg, strconv.Itoa(body.MaxPlayers)) + wordsPerTurn, wordsPerTurnInvalid := ParseCustomWordsPerTurn(strconv.Itoa(body.WordsPerTurn), config.Default.LobbySettingBounds.MaxWordsPerTurn) + customWordsPerTurn, customWordsPerTurnInvalid := ParseCustomWordsPerTurn(strconv.Itoa(body.CustomWordsPerTurn), config.Default.LobbySettingBounds.MaxCustomWordsPerTurn) + clientsPerIPLimit, clientsPerIPLimitInvalid := ParseClientsPerIPLimit(handler.cfg, strconv.Itoa(body.ClientsPerIPLimit)) var lowercaser cases.Caser if languageInvalid != nil { @@ -156,18 +185,22 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re if clientsPerIPLimitInvalid != nil { requestErrors = append(requestErrors, clientsPerIPLimitInvalid.Error()) } - if publicLobbyInvalid != nil { - requestErrors = append(requestErrors, publicLobbyInvalid.Error()) - } if len(requestErrors) != 0 { http.Error(writer, strings.Join(requestErrors, ";"), http.StatusBadRequest) return } - playerName := GetPlayername(request) - player, lobby, err := game.CreateLobby(lobbyId, playerName, - languageKey, publicLobby, drawingTime, rounds, maxPlayers, wordsPerTurn, + // Get user + var playerName string + playerID := uuid.Must(uuid.NewV4()) + playerName = GetPlayername(request) + if request.Context().Value(middleware.UserIDKey) != "" && request.Header.Get("Guest") != "1" { + playerID = uuid.FromStringOrNil(request.Context().Value(middleware.UserIDKey).(string)) + } + + player, lobby, err := game.CreateLobby(lobbyId, playerName, playerID, + languageKey, body.Public, drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn, clientsPerIPLimit, customWords, scoreCalculation) if err != nil { http.Error(writer, err.Error(), http.StatusBadRequest) @@ -198,7 +231,6 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re return } - // We only add the lobby if everything else was successful. state.AddLobby(lobby) } @@ -227,7 +259,17 @@ func (handler *V1Handler) postPlayer(writer http.ResponseWriter, request *http.R return } - newPlayer := lobby.JoinPlayer(GetPlayername(request)) + newPlayerID := uuid.Must(uuid.NewV4()) + if request.Context().Value(middleware.UserIDKey) != "" { + newPlayerID = uuid.Must(uuid.FromString(request.Context().Value(middleware.UserIDKey).(string))) + } + + if lobby.GetPlayerByID(newPlayerID) != nil { + http.Error(writer, "this auth_user already joined", http.StatusUnauthorized) + return + } + + newPlayer := lobby.JoinPlayer(GetPlayername(request), newPlayerID) newPlayer.SetLastKnownAddress(requestAddress) // Use the players generated usersession and pass it as a cookie. @@ -285,42 +327,18 @@ func SetGameplayCookies( player *game.Player, lobby *game.Lobby, ) { - discordInstanceId := GetDiscordInstanceId(request) - if discordInstanceId != "" { - http.SetCookie(w, &http.Cookie{ - Name: "usersession", - Value: player.GetUserSession().String(), - Domain: discordDomain, - Path: "/", - SameSite: http.SameSiteNoneMode, - Partitioned: true, - Secure: true, - }) - http.SetCookie(w, &http.Cookie{ - Name: "lobby-id", - Value: lobby.LobbyID, - Domain: discordDomain, - Path: "/", - SameSite: http.SameSiteNoneMode, - Partitioned: true, - Secure: true, - }) - } else { - // For the discord case, we need both, as the discord specific cookies - // aren't available during the readirect from ssrCreate to ssrEnter. - http.SetCookie(w, &http.Cookie{ - Name: "usersession", - Value: player.GetUserSession().String(), - Path: "/", - SameSite: http.SameSiteStrictMode, - }) - http.SetCookie(w, &http.Cookie{ - Name: "lobby-id", - Value: lobby.LobbyID, - Path: "/", - SameSite: http.SameSiteStrictMode, - }) - } + http.SetCookie(w, &http.Cookie{ + Name: "usersession", + Value: player.GetUserSession().String(), + Path: "/", + SameSite: http.SameSiteStrictMode, + }) + http.SetCookie(w, &http.Cookie{ + Name: "lobby-id", + Value: lobby.LobbyID, + Path: "/", + SameSite: http.SameSiteStrictMode, + }) } func (handler *V1Handler) patchLobby(writer http.ResponseWriter, request *http.Request) { @@ -478,6 +496,7 @@ var GameConstantsData = &GameConstants{ // While unofficial clients will probably need all of these values, the // official webclient doesn't use all of them as of now. type LobbyData struct { + LobbyID string `json:"lobby_id"` game.SettingBounds game.EditableLobbySettings *GameConstants @@ -488,6 +507,7 @@ type LobbyData struct { // from the passed Lobby. func CreateLobbyData(cfg *config.Config, lobby *game.Lobby) *LobbyData { return &LobbyData{ + LobbyID: lobby.LobbyID, SettingBounds: cfg.LobbySettingBounds, EditableLobbySettings: lobby.EditableLobbySettings, GameConstants: GameConstantsData, @@ -550,6 +570,20 @@ func GetPlayername(request *http.Request) string { } } + if request.Context().Value(middleware.UserIDKey) != "" && request.Header.Get("Guest") != "1" { + var name, username string + err := database.Pool.QueryRow(request.Context(), `SELECT name, username FROM "user" WHERE id = $1 LIMIT 1`, request.Context().Value(middleware.UserIDKey)).Scan( + &name, &username, + ) + if err == nil { + if name != "" { + return name + } else { + return username + } + } + } + return "" } @@ -557,8 +591,7 @@ func GetPlayername(request *http.Request) string { func GetLobbyId(request *http.Request) string { lobbyId := request.PathValue("lobby_id") if lobbyId == "" { - cookie, _ := request.Cookie("lobby-id") - lobbyId = cookie.Value + lobbyId = request.Header.Get("Lobbyid") } return lobbyId } diff --git a/internal/frontend/index.go b/internal/frontend/index.go index fc1fd66..bd061b3 100644 --- a/internal/frontend/index.go +++ b/internal/frontend/index.go @@ -9,6 +9,7 @@ import ( "net/http" txtTemplate "text/template" + "github.com/gofrs/uuid/v5" "golang.org/x/text/cases" "golang.org/x/text/language" "medad.fun/internal/api" @@ -275,7 +276,7 @@ func (handler *SSRHandler) ssrCreateLobby(writer http.ResponseWriter, request *h clientsPerIPLimit = maxPlayers } - player, lobby, err := game.CreateLobby(lobbyId, playerName, languageKey, + player, lobby, err := game.CreateLobby(lobbyId, playerName, uuid.Must(uuid.NewV4()), languageKey, publicLobby, drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn, clientsPerIPLimit, customWords, scoreCalculation) if err != nil { diff --git a/internal/frontend/lobby.go b/internal/frontend/lobby.go index b523cec..58e6904 100644 --- a/internal/frontend/lobby.go +++ b/internal/frontend/lobby.go @@ -5,6 +5,7 @@ import ( "net/http" "strings" + "github.com/gofrs/uuid/v5" "golang.org/x/text/language" "medad.fun/internal/api" "medad.fun/internal/game" @@ -93,7 +94,7 @@ func (handler *SSRHandler) ssrEnterLobbyNoChecks( return } - newPlayer := lobby.JoinPlayer(api.GetPlayername(request)) + newPlayer := lobby.JoinPlayer(api.GetPlayername(request), uuid.Must(uuid.NewV4())) newPlayer.SetLastKnownAddress(requestAddress) api.SetGameplayCookies(writer, request, newPlayer, lobby) diff --git a/internal/game/lobby.go b/internal/game/lobby.go index 8abcbbe..0b5d270 100644 --- a/internal/game/lobby.go +++ b/internal/game/lobby.go @@ -1024,7 +1024,7 @@ func (lobby *Lobby) selectWord(index int) error { // optionally returns an error, if any occurred during creation. func CreateLobby( desiredLobbyId string, - playerName, chosenLanguage string, + playerName string, playerID uuid.UUID, chosenLanguage string, publicLobby bool, drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn, clientsPerIPLimit int, customWords []string, @@ -1074,7 +1074,7 @@ func CreateLobby( } } - player := lobby.JoinPlayer(playerName) + player := lobby.JoinPlayer(playerName, playerID) lobby.OwnerID = player.ID return player, lobby, nil @@ -1202,10 +1202,10 @@ func (lobby *Lobby) GetAvailableWordHints(player *Player) []*WordHint { // JoinPlayer creates a new player object using the given name and adds it // to the lobbies playerlist. The new players is returned. -func (lobby *Lobby) JoinPlayer(name string) *Player { +func (lobby *Lobby) JoinPlayer(name string, id uuid.UUID) *Player { player := &Player{ Name: SanitizeName(name), - ID: uuid.Must(uuid.NewV4()), + ID: id, userSession: uuid.Must(uuid.NewV4()), votedForKick: make(map[uuid.UUID]bool), messageTimestamps: NewRing[time.Time](5), @@ -1220,6 +1220,12 @@ func (lobby *Lobby) JoinPlayer(name string) *Player { } lobby.players = append(lobby.players, player) + // log.Print("List of players {") + // for _, v := range lobby.players { + // log.Print(v.ID, " ", v.Name, " ", v.userSession) + // } + // log.Print("}") + return player } diff --git a/internal/game/lobby_test.go b/internal/game/lobby_test.go index 822be2f..409a470 100644 --- a/internal/game/lobby_test.go +++ b/internal/game/lobby_test.go @@ -215,7 +215,7 @@ func Test_handleNameChangeEvent(t *testing.T) { lobby := &Lobby{} lobby.WriteObject = noOpWriteObject lobby.WritePreparedMessage = noOpWritePreparedMessage - player := lobby.JoinPlayer("Kevin") + player := lobby.JoinPlayer("Kevin", uuid.Must(uuid.NewV4())) handleNameChangeEvent(player, lobby, "Jim") @@ -274,7 +274,7 @@ func Test_wordSelectionEvent(t *testing.T) { return nil } - drawer := lobby.JoinPlayer("Drawer") + drawer := lobby.JoinPlayer("Drawer", uuid.Must(uuid.NewV4())) drawer.Connected = true lobby.OwnerID = drawer.ID @@ -282,7 +282,7 @@ func Test_wordSelectionEvent(t *testing.T) { t.Errorf("Couldn't start lobby: %s", err) } - guesser := lobby.JoinPlayer("Guesser") + guesser := lobby.JoinPlayer("Guesser", uuid.Must(uuid.NewV4())) guesser.Connected = true err := lobby.HandleEvent(EventTypeChooseWord, []byte(`{"data": 0}`), drawer) @@ -340,13 +340,13 @@ func Test_kickDrawer(t *testing.T) { lobby.WriteObject = noOpWriteObject lobby.WritePreparedMessage = noOpWritePreparedMessage - marcel := lobby.JoinPlayer("marcel") + marcel := lobby.JoinPlayer("marcel", uuid.Must(uuid.NewV4())) marcel.Connected = true lobby.OwnerID = marcel.ID - kevin := lobby.JoinPlayer("kevin") + kevin := lobby.JoinPlayer("kevin", uuid.Must(uuid.NewV4())) kevin.Connected = true - chantal := lobby.JoinPlayer("chantal") + chantal := lobby.JoinPlayer("chantal", uuid.Must(uuid.NewV4())) chantal.Connected = true if err := lobby.HandleEvent(EventTypeStart, nil, marcel); err != nil { @@ -530,7 +530,7 @@ func Test_lobby_calculateDrawerScore(t *testing.T) { func Test_NoPrematureGameOver(t *testing.T) { t.Parallel() - player, lobby, err := CreateLobby("", "test", "english", false, 120, 4, 4, 3, 3, 1, nil, ChillScoring) + player, lobby, err := CreateLobby("", "test", uuid.Must(uuid.NewV4()), "english", false, 120, 4, 4, 3, 3, 1, nil, ChillScoring) require.NoError(t, err) lobby.WriteObject = noOpWriteObject diff --git a/internal/state/lobbies_test.go b/internal/state/lobbies_test.go index 52326f5..2bf443c 100644 --- a/internal/state/lobbies_test.go +++ b/internal/state/lobbies_test.go @@ -3,6 +3,7 @@ package state import ( "testing" + "github.com/gofrs/uuid/v5" "github.com/stretchr/testify/require" "medad.fun/internal/config" "medad.fun/internal/game" @@ -13,7 +14,7 @@ func TestAddAndRemove(t *testing.T) { require.Empty(t, lobbies, "Lobbies should be empty when test starts") createLobby := func() *game.Lobby { - player, lobby, err := game.CreateLobby("", "player", "dutch", true, 100, 10, 10, 3, 3, 1, nil, game.ChillScoring) + player, lobby, err := game.CreateLobby("", "player", uuid.Must(uuid.NewV4()), "dutch", true, 100, 10, 10, 3, 3, 1, nil, game.ChillScoring) require.NoError(t, err) lobby.OnPlayerDisconnect(player) return lobby