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.
This commit is contained in:
2026-05-28 18:01:57 +03:30
parent 0b4cb868e7
commit 4d6ae9efc3
7 changed files with 114 additions and 73 deletions
+2 -3
View File
@@ -27,11 +27,10 @@ FROM scratch
COPY --from=builder /s /dist COPY --from=builder /s /dist
# 2. Copy public assets (FIXED syntax) # 2. Copy public assets (FIXED syntax)
COPY .env /.env
# COPY --from=builder /public /public # COPY --from=builder /public /public
# 3. Copy SSL certs (UNCOMMENTED) # 3. Copy SSL certs
# COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
# 4. Security # 4. Security
USER 248:248 USER 248:248
+89 -56
View File
@@ -4,6 +4,7 @@ import (
json "encoding/json" json "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io"
"log" "log"
"net/http" "net/http"
"strconv" "strconv"
@@ -12,7 +13,9 @@ import (
"github.com/gofrs/uuid/v5" "github.com/gofrs/uuid/v5"
"golang.org/x/text/cases" "golang.org/x/text/cases"
"golang.org/x/text/language" "golang.org/x/text/language"
"medad.fun/internal/api/v1/middleware"
"medad.fun/internal/config" "medad.fun/internal/config"
"medad.fun/internal/database"
"medad.fun/internal/game" "medad.fun/internal/game"
"medad.fun/internal/state" "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) { func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Request) {
if err := request.ParseForm(); err != nil { if err := request.ParseForm(); err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest) http.Error(writer, err.Error(), http.StatusBadRequest)
return 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 var requestErrors []string
// The lobby ID is normally autogenerated and it isn't advisble to set it // The lobby ID is normally autogenerated and it isn't advisble to set it
// yourself, but for certain integrations / automations this can be useful. // 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 // However, to avoid any kind of abuse, this needs to be a valid UUID at
// least. // least.
lobbyId := request.Form.Get("lobby_id") lobbyId := body.LobbyID
if lobbyId != "" { if lobbyId != "" {
var err error var err error
_, err = uuid.FromString(lobbyId) _, 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(body.Language)
languageData, languageKey, languageInvalid := ParseLanguage(request.Form.Get("language")) scoreCalculation, scoreCalculationInvalid := ParseScoreCalculation(body.ScoreCalculation)
drawingTime, drawingTimeInvalid := ParseDrawingTime(handler.cfg, request.Form.Get("drawing_time")) drawingTime, drawingTimeInvalid := ParseDrawingTime(handler.cfg, strconv.Itoa(body.DrawingTime))
rounds, roundsInvalid := ParseRounds(handler.cfg, request.Form.Get("rounds")) rounds, roundsInvalid := ParseRounds(handler.cfg, strconv.Itoa(body.Rounds))
maxPlayers, maxPlayersInvalid := ParseMaxPlayers(handler.cfg, request.Form.Get("max_players")) maxPlayers, maxPlayersInvalid := ParseMaxPlayers(handler.cfg, strconv.Itoa(body.MaxPlayers))
wordsPerTurn, wordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("words_per_turn"), config.Default.LobbySettingBounds.MaxWordsPerTurn) wordsPerTurn, wordsPerTurnInvalid := ParseCustomWordsPerTurn(strconv.Itoa(body.WordsPerTurn), config.Default.LobbySettingBounds.MaxWordsPerTurn)
customWordsPerTurn, customWordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("custom_words_per_turn"), config.Default.LobbySettingBounds.MaxCustomWordsPerTurn) customWordsPerTurn, customWordsPerTurnInvalid := ParseCustomWordsPerTurn(strconv.Itoa(body.CustomWordsPerTurn), config.Default.LobbySettingBounds.MaxCustomWordsPerTurn)
clientsPerIPLimit, clientsPerIPLimitInvalid := ParseClientsPerIPLimit(handler.cfg, request.Form.Get("clients_per_ip_limit")) clientsPerIPLimit, clientsPerIPLimitInvalid := ParseClientsPerIPLimit(handler.cfg, strconv.Itoa(body.ClientsPerIPLimit))
publicLobby, publicLobbyInvalid := ParseBoolean("public", request.Form.Get("public"))
var lowercaser cases.Caser var lowercaser cases.Caser
if languageInvalid != nil { if languageInvalid != nil {
@@ -156,18 +185,22 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re
if clientsPerIPLimitInvalid != nil { if clientsPerIPLimitInvalid != nil {
requestErrors = append(requestErrors, clientsPerIPLimitInvalid.Error()) requestErrors = append(requestErrors, clientsPerIPLimitInvalid.Error())
} }
if publicLobbyInvalid != nil {
requestErrors = append(requestErrors, publicLobbyInvalid.Error())
}
if len(requestErrors) != 0 { if len(requestErrors) != 0 {
http.Error(writer, strings.Join(requestErrors, ";"), http.StatusBadRequest) http.Error(writer, strings.Join(requestErrors, ";"), http.StatusBadRequest)
return return
} }
playerName := GetPlayername(request) // Get user
player, lobby, err := game.CreateLobby(lobbyId, playerName, var playerName string
languageKey, publicLobby, drawingTime, rounds, maxPlayers, wordsPerTurn, 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) customWordsPerTurn, clientsPerIPLimit, customWords, scoreCalculation)
if err != nil { if err != nil {
http.Error(writer, err.Error(), http.StatusBadRequest) http.Error(writer, err.Error(), http.StatusBadRequest)
@@ -198,7 +231,6 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re
return return
} }
// We only add the lobby if everything else was successful.
state.AddLobby(lobby) state.AddLobby(lobby)
} }
@@ -227,7 +259,17 @@ func (handler *V1Handler) postPlayer(writer http.ResponseWriter, request *http.R
return 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) newPlayer.SetLastKnownAddress(requestAddress)
// Use the players generated usersession and pass it as a cookie. // Use the players generated usersession and pass it as a cookie.
@@ -285,42 +327,18 @@ func SetGameplayCookies(
player *game.Player, player *game.Player,
lobby *game.Lobby, lobby *game.Lobby,
) { ) {
discordInstanceId := GetDiscordInstanceId(request) http.SetCookie(w, &http.Cookie{
if discordInstanceId != "" { Name: "usersession",
http.SetCookie(w, &http.Cookie{ Value: player.GetUserSession().String(),
Name: "usersession", Path: "/",
Value: player.GetUserSession().String(), SameSite: http.SameSiteStrictMode,
Domain: discordDomain, })
Path: "/", http.SetCookie(w, &http.Cookie{
SameSite: http.SameSiteNoneMode, Name: "lobby-id",
Partitioned: true, Value: lobby.LobbyID,
Secure: true, Path: "/",
}) SameSite: http.SameSiteStrictMode,
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,
})
}
} }
func (handler *V1Handler) patchLobby(writer http.ResponseWriter, request *http.Request) { 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 // While unofficial clients will probably need all of these values, the
// official webclient doesn't use all of them as of now. // official webclient doesn't use all of them as of now.
type LobbyData struct { type LobbyData struct {
LobbyID string `json:"lobby_id"`
game.SettingBounds game.SettingBounds
game.EditableLobbySettings game.EditableLobbySettings
*GameConstants *GameConstants
@@ -488,6 +507,7 @@ type LobbyData struct {
// from the passed Lobby. // from the passed Lobby.
func CreateLobbyData(cfg *config.Config, lobby *game.Lobby) *LobbyData { func CreateLobbyData(cfg *config.Config, lobby *game.Lobby) *LobbyData {
return &LobbyData{ return &LobbyData{
LobbyID: lobby.LobbyID,
SettingBounds: cfg.LobbySettingBounds, SettingBounds: cfg.LobbySettingBounds,
EditableLobbySettings: lobby.EditableLobbySettings, EditableLobbySettings: lobby.EditableLobbySettings,
GameConstants: GameConstantsData, 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 "" return ""
} }
@@ -557,8 +591,7 @@ func GetPlayername(request *http.Request) string {
func GetLobbyId(request *http.Request) string { func GetLobbyId(request *http.Request) string {
lobbyId := request.PathValue("lobby_id") lobbyId := request.PathValue("lobby_id")
if lobbyId == "" { if lobbyId == "" {
cookie, _ := request.Cookie("lobby-id") lobbyId = request.Header.Get("Lobbyid")
lobbyId = cookie.Value
} }
return lobbyId return lobbyId
} }
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"net/http" "net/http"
txtTemplate "text/template" txtTemplate "text/template"
"github.com/gofrs/uuid/v5"
"golang.org/x/text/cases" "golang.org/x/text/cases"
"golang.org/x/text/language" "golang.org/x/text/language"
"medad.fun/internal/api" "medad.fun/internal/api"
@@ -275,7 +276,7 @@ func (handler *SSRHandler) ssrCreateLobby(writer http.ResponseWriter, request *h
clientsPerIPLimit = maxPlayers 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, publicLobby, drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn,
clientsPerIPLimit, customWords, scoreCalculation) clientsPerIPLimit, customWords, scoreCalculation)
if err != nil { if err != nil {
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"net/http" "net/http"
"strings" "strings"
"github.com/gofrs/uuid/v5"
"golang.org/x/text/language" "golang.org/x/text/language"
"medad.fun/internal/api" "medad.fun/internal/api"
"medad.fun/internal/game" "medad.fun/internal/game"
@@ -93,7 +94,7 @@ func (handler *SSRHandler) ssrEnterLobbyNoChecks(
return return
} }
newPlayer := lobby.JoinPlayer(api.GetPlayername(request)) newPlayer := lobby.JoinPlayer(api.GetPlayername(request), uuid.Must(uuid.NewV4()))
newPlayer.SetLastKnownAddress(requestAddress) newPlayer.SetLastKnownAddress(requestAddress)
api.SetGameplayCookies(writer, request, newPlayer, lobby) api.SetGameplayCookies(writer, request, newPlayer, lobby)
+10 -4
View File
@@ -1024,7 +1024,7 @@ func (lobby *Lobby) selectWord(index int) error {
// optionally returns an error, if any occurred during creation. // optionally returns an error, if any occurred during creation.
func CreateLobby( func CreateLobby(
desiredLobbyId string, desiredLobbyId string,
playerName, chosenLanguage string, playerName string, playerID uuid.UUID, chosenLanguage string,
publicLobby bool, publicLobby bool,
drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn, clientsPerIPLimit int, drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn, clientsPerIPLimit int,
customWords []string, customWords []string,
@@ -1074,7 +1074,7 @@ func CreateLobby(
} }
} }
player := lobby.JoinPlayer(playerName) player := lobby.JoinPlayer(playerName, playerID)
lobby.OwnerID = player.ID lobby.OwnerID = player.ID
return player, lobby, nil 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 // JoinPlayer creates a new player object using the given name and adds it
// to the lobbies playerlist. The new players is returned. // 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{ player := &Player{
Name: SanitizeName(name), Name: SanitizeName(name),
ID: uuid.Must(uuid.NewV4()), ID: id,
userSession: uuid.Must(uuid.NewV4()), userSession: uuid.Must(uuid.NewV4()),
votedForKick: make(map[uuid.UUID]bool), votedForKick: make(map[uuid.UUID]bool),
messageTimestamps: NewRing[time.Time](5), messageTimestamps: NewRing[time.Time](5),
@@ -1220,6 +1220,12 @@ func (lobby *Lobby) JoinPlayer(name string) *Player {
} }
lobby.players = append(lobby.players, 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 return player
} }
+7 -7
View File
@@ -215,7 +215,7 @@ func Test_handleNameChangeEvent(t *testing.T) {
lobby := &Lobby{} lobby := &Lobby{}
lobby.WriteObject = noOpWriteObject lobby.WriteObject = noOpWriteObject
lobby.WritePreparedMessage = noOpWritePreparedMessage lobby.WritePreparedMessage = noOpWritePreparedMessage
player := lobby.JoinPlayer("Kevin") player := lobby.JoinPlayer("Kevin", uuid.Must(uuid.NewV4()))
handleNameChangeEvent(player, lobby, "Jim") handleNameChangeEvent(player, lobby, "Jim")
@@ -274,7 +274,7 @@ func Test_wordSelectionEvent(t *testing.T) {
return nil return nil
} }
drawer := lobby.JoinPlayer("Drawer") drawer := lobby.JoinPlayer("Drawer", uuid.Must(uuid.NewV4()))
drawer.Connected = true drawer.Connected = true
lobby.OwnerID = drawer.ID lobby.OwnerID = drawer.ID
@@ -282,7 +282,7 @@ func Test_wordSelectionEvent(t *testing.T) {
t.Errorf("Couldn't start lobby: %s", err) t.Errorf("Couldn't start lobby: %s", err)
} }
guesser := lobby.JoinPlayer("Guesser") guesser := lobby.JoinPlayer("Guesser", uuid.Must(uuid.NewV4()))
guesser.Connected = true guesser.Connected = true
err := lobby.HandleEvent(EventTypeChooseWord, []byte(`{"data": 0}`), drawer) err := lobby.HandleEvent(EventTypeChooseWord, []byte(`{"data": 0}`), drawer)
@@ -340,13 +340,13 @@ func Test_kickDrawer(t *testing.T) {
lobby.WriteObject = noOpWriteObject lobby.WriteObject = noOpWriteObject
lobby.WritePreparedMessage = noOpWritePreparedMessage lobby.WritePreparedMessage = noOpWritePreparedMessage
marcel := lobby.JoinPlayer("marcel") marcel := lobby.JoinPlayer("marcel", uuid.Must(uuid.NewV4()))
marcel.Connected = true marcel.Connected = true
lobby.OwnerID = marcel.ID lobby.OwnerID = marcel.ID
kevin := lobby.JoinPlayer("kevin") kevin := lobby.JoinPlayer("kevin", uuid.Must(uuid.NewV4()))
kevin.Connected = true kevin.Connected = true
chantal := lobby.JoinPlayer("chantal") chantal := lobby.JoinPlayer("chantal", uuid.Must(uuid.NewV4()))
chantal.Connected = true chantal.Connected = true
if err := lobby.HandleEvent(EventTypeStart, nil, marcel); err != nil { 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) { func Test_NoPrematureGameOver(t *testing.T) {
t.Parallel() 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) require.NoError(t, err)
lobby.WriteObject = noOpWriteObject lobby.WriteObject = noOpWriteObject
+2 -1
View File
@@ -3,6 +3,7 @@ package state
import ( import (
"testing" "testing"
"github.com/gofrs/uuid/v5"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"medad.fun/internal/config" "medad.fun/internal/config"
"medad.fun/internal/game" "medad.fun/internal/game"
@@ -13,7 +14,7 @@ func TestAddAndRemove(t *testing.T) {
require.Empty(t, lobbies, "Lobbies should be empty when test starts") require.Empty(t, lobbies, "Lobbies should be empty when test starts")
createLobby := func() *game.Lobby { 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) require.NoError(t, err)
lobby.OnPlayerDisconnect(player) lobby.OnPlayerDisconnect(player)
return lobby return lobby