Sanitize settings on Get() and add convenience getters

Sanitizing options on Get() ensures that when someone asks
for a given option which may not be defined (`nosubject`, `nosender`),
we'll return a valid value (`'true'` or `'false'`) and not `''` (empty
string, undefined).

This way, users do not need to wonder if "nosender is not set" is
handled like "true" or "false" or in some 3rd way. They also don't need
to think about "how to unset this setting, now that I've set it to something".
Options will appear to have a default sanitized value no matter if
they've explicitly been set or not.

The `NoSender()` and `NoSubject()` getters are just there for
convenience, so that we won't need to do casting in other places.
This commit is contained in:
Slavi Pantaleev
2022-08-24 10:16:28 +03:00
parent d361e31a60
commit 16ce4314b9
2 changed files with 18 additions and 3 deletions

View File

@@ -102,12 +102,12 @@ func (b *Bot) Send(ctx context.Context, from, to, subject, plaintext, html strin
}
var text strings.Builder
if !utils.Bool(settings.Get("nosender")) {
if !settings.NoSender() {
text.WriteString("From: ")
text.WriteString(from)
text.WriteString("\n\n")
}
if !utils.Bool(settings.Get("nosubject")) {
if !settings.NoSubject() {
text.WriteString("# ")
text.WriteString(subject)
text.WriteString("\n\n")

View File

@@ -6,6 +6,7 @@ import (
"strings"
"github.com/getsentry/sentry-go"
"gitlab.com/etke.cc/postmoogle/utils"
"maunium.net/go/mautrix/id"
)
@@ -39,7 +40,21 @@ func (s settings) Allowed(noowner bool, userID id.UserID) bool {
// Get option
func (s settings) Get(key string) string {
return s[strings.ToLower(strings.TrimSpace(key))]
rawValue := s[strings.ToLower(strings.TrimSpace(key))]
sanitizer, exists := sanitizers[key]
if exists {
return sanitizer(rawValue)
}
return rawValue
}
func (s settings) NoSender() bool {
return utils.Bool(s.Get("nosender"))
}
func (s settings) NoSubject() bool {
return utils.Bool(s.Get("nosubject"))
}
// Set option