knowyt/server/src/application/removePlayer.go

59 lines
1.3 KiB
Go

package application
import (
"fmt"
"net/http"
"sirlab.de/go/knowyt/game"
"sirlab.de/go/knowyt/log"
"sirlab.de/go/knowyt/user"
)
func (app *Application) RemovePlayer(usr *user.User, w http.ResponseWriter, r *http.Request) {
gameRef := r.URL.Query().Get("g")
gm, err := app.GetGameById(gameRef)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "game not found")
return
}
if usr.GetGameId() != gameRef || !usr.IsGamemaster() {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "forbidden")
return
}
id := r.URL.Query().Get("id")
if id == usr.GetId() {
w.WriteHeader(http.StatusForbidden)
log.Warn("can't delete yourself\n")
fmt.Fprintf(w, "forbidden")
return
}
if err := app.removePlayerById(id, gm); err != nil {
w.WriteHeader(http.StatusForbidden)
log.Warn("%v\n", err.Error())
fmt.Fprintf(w, "forbidden")
return
}
fmt.Fprintf(w, "ok")
}
func (app *Application) removePlayerById(id string, gm *game.Game) error {
userToRemove := app.users[id]
if userToRemove.GetId() != id || userToRemove.GetGameId() != gm.GetId() {
return fmt.Errorf("couldn't find player %s in game %s\n", id, gm.GetId())
}
if err := userToRemove.RemovePlayer(); err != nil {
return err
}
gm.RemovePlayer(userToRemove)
delete(app.users, id)
return nil
}