From 5b6555cd9adafb7d57aaa7b079e41f2ebc4185e5 Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Tue, 10 May 2022 17:47:26 -0600 Subject: [PATCH] Check team existence before registering. Fixes #156 --- cmd/mothd/issues_test.go | 28 ++++++++++++++++++++++++++++ cmd/mothd/server.go | 7 +++++-- cmd/mothd/state.go | 7 +++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 cmd/mothd/issues_test.go diff --git a/cmd/mothd/issues_test.go b/cmd/mothd/issues_test.go new file mode 100644 index 0000000..26a6f6d --- /dev/null +++ b/cmd/mothd/issues_test.go @@ -0,0 +1,28 @@ +package main + +import ( + "testing" + + "github.com/spf13/afero" +) + +func TestIssue156(t *testing.T) { + puzzles := NewTestMothballs() + state := NewTestState() + theme := NewTestTheme() + server := NewMothServer(Configuration{}, theme, state, puzzles) + + afero.WriteFile(state, "teams/bloop", []byte("bloop: the team"), 0644) + state.refresh() + + handler := server.NewHandler("", "bloop") + es := handler.ExportState() + if _, ok := es.TeamNames["self"]; !ok { + t.Fail() + } + + err := handler.Register("bloop: the other team") + if err != ErrAlreadyRegistered { + t.Fail() + } +} diff --git a/cmd/mothd/server.go b/cmd/mothd/server.go index 608e6d6..f53ecdf 100644 --- a/cmd/mothd/server.go +++ b/cmd/mothd/server.go @@ -184,12 +184,15 @@ func (mh *MothRequestHandler) ExportState() *StateExport { return mh.exportStateIfRegistered(false) } -func (mh *MothRequestHandler) exportStateIfRegistered(override bool) *StateExport { +// Export state, replacing the team ID with "self" if the team is registered. +// +// If forceRegistered is true, go ahead and export it anyway +func (mh *MothRequestHandler) exportStateIfRegistered(forceRegistered bool) *StateExport { export := StateExport{} export.Config = mh.Config teamName, err := mh.State.TeamName(mh.teamID) - registered := override || mh.Config.Devel || (err == nil) + registered := forceRegistered || mh.Config.Devel || (err == nil) export.Messages = mh.State.Messages() export.TeamNames = make(map[string]string) diff --git a/cmd/mothd/state.go b/cmd/mothd/state.go index d8f09d1..eca4d5b 100644 --- a/cmd/mothd/state.go +++ b/cmd/mothd/state.go @@ -141,6 +141,13 @@ func (s *State) TeamName(teamID string) (string, error) { // SetTeamName writes out team name. // This can only be done once per team. func (s *State) SetTeamName(teamID, teamName string) error { + s.lock.RLock() + _, ok := s.teamNames[teamID] + s.lock.RUnlock() + if ok { + return ErrAlreadyRegistered + } + idsFile, err := s.Open("teamids.txt") if err != nil { return fmt.Errorf("team IDs file does not exist")