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
+89 -56
View File
@@ -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
}