jlelse
/
MailyGo
Archived
1
Fork 0
This repository has been archived on 2024-01-02. You can view files and clone it, but cannot push or open issues or pull requests.
MailyGo/forms.go

72 lines
1.7 KiB
Go
Raw Normal View History

2020-03-14 21:26:34 +00:00
package main
import (
2020-03-15 15:54:00 +00:00
"html"
2020-03-14 21:26:34 +00:00
"net/http"
"net/url"
2020-04-12 10:34:51 +00:00
"github.com/microcosm-cc/bluemonday"
2020-03-14 21:26:34 +00:00
)
type FormValues map[string][]string
func FormHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
_, _ = w.Write([]byte("MailyGo works!"))
return
}
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
return
}
_ = r.ParseForm()
2020-04-12 10:34:51 +00:00
sanitizedForm := sanitizeForm(&r.PostForm)
2020-03-21 10:53:40 +00:00
go func() {
if !isBot(sanitizedForm) {
sendForm(sanitizedForm)
}
}()
2020-03-14 21:26:34 +00:00
sendResponse(sanitizedForm, w)
return
}
2020-04-12 10:34:51 +00:00
func sanitizeForm(values *url.Values) *FormValues {
2020-03-14 21:26:34 +00:00
p := bluemonday.StrictPolicy()
sanitizedForm := make(FormValues)
2020-04-12 10:34:51 +00:00
for key, values := range *values {
2020-03-14 21:26:34 +00:00
var sanitizedValues []string
for _, value := range values {
2020-03-15 15:54:00 +00:00
sanitizedValues = append(sanitizedValues, html.UnescapeString(p.Sanitize(value)))
2020-03-14 21:26:34 +00:00
}
2020-03-15 15:54:00 +00:00
sanitizedForm[html.UnescapeString(p.Sanitize(key))] = sanitizedValues
2020-03-14 21:26:34 +00:00
}
2020-04-12 10:34:51 +00:00
return &sanitizedForm
2020-03-14 21:26:34 +00:00
}
2020-04-12 10:34:51 +00:00
func isBot(values *FormValues) bool {
2020-03-14 21:26:34 +00:00
for _, honeyPot := range appConfig.HoneyPots {
2020-04-12 10:34:51 +00:00
if len((*values)[honeyPot]) > 0 {
for _, value := range (*values)[honeyPot] {
2020-03-14 21:26:34 +00:00
if value != "" {
return true
}
}
}
}
2020-03-21 12:03:56 +00:00
return checkValues(values)
2020-03-14 21:26:34 +00:00
}
2020-04-12 10:34:51 +00:00
func sendResponse(values *FormValues, w http.ResponseWriter) {
if len((*values)["_redirectTo"]) == 1 && (*values)["_redirectTo"][0] != "" {
w.Header().Add("Location", (*values)["_redirectTo"][0])
2020-03-14 21:26:34 +00:00
w.WriteHeader(http.StatusSeeOther)
2020-04-12 10:34:51 +00:00
_, _ = w.Write([]byte("Go to " + (*values)["_redirectTo"][0]))
2020-03-14 21:26:34 +00:00
return
} else {
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte("Submitted form"))
return
}
2020-04-12 10:34:51 +00:00
}