From 92849b83ba4043534fdcf79058be5d93c90a55f9 Mon Sep 17 00:00:00 2001 From: Xevion Date: Sun, 9 Jun 2024 18:44:26 -0500 Subject: [PATCH] Validate location existence, validate code pattern --- commands.go | 12 +++++++++--- data.go | 7 +++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/commands.go b/commands.go index f1cea0d..e871130 100644 --- a/commands.go +++ b/commands.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "regexp" "strconv" "time" @@ -15,6 +16,8 @@ import ( // In order for the modal submission to be useful, the context for it's initial request must be stored. var SubmissionContexts = timedmap.New(5 * time.Minute) +var codePattern = regexp.MustCompile(`^[a-zA-Z0-9]{4,12}$`) + var CodeCommandDefinition = &discordgo.ApplicationCommand{ Name: "code", Description: "Set the guest code for a given location", @@ -51,9 +54,12 @@ func CodeCommandHandler(session *discordgo.Session, interaction *discordgo.Inter code := data.Options[1].StringValue() userId, _ := strconv.Atoi(interaction.Member.User.ID) - // TODO: Validate that the location exists - // TODO: Validate that the code has no invalid characters - already_set := StoreCode(code, int64(location_id), user_id) + // Validate that the location exists + if !LocationExists(int64(locationId)) { + HandleError(session, interaction, nil, "The location provided does not exist.") + return + } + // Validate that the code has no invalid characters if !codePattern.MatchString(code) { HandleError(session, interaction, nil, "The code provided contains invalid characters.") diff --git a/data.go b/data.go index 9cb1574..6bff94e 100644 --- a/data.go +++ b/data.go @@ -4,6 +4,13 @@ import ( "fmt" ) +// LocationExists checks if a location identifier is valid (as known by the cache). +// Cache rarely will change, so this is a good way to check if a location is valid. +func LocationExists(location int64) bool { + _, ok := cachedLocationsMap[uint(location)] + return ok +} + func StoreCode(code string, location int64, member_id int) bool { key := fmt.Sprintf("code:%d:%d", location, member_id) already_set := db.Exists(key).Val() == 1