add reCaptcha support

This commit is contained in:
Chris Camel 2020-06-02 15:27:08 +02:00
parent 40f4fd2d30
commit 310cd75505
No known key found for this signature in database
GPG Key ID: 125EFEF60AEF6949
2 changed files with 38 additions and 4 deletions

View File

@ -40,7 +40,9 @@ var routes = Routes{
"SendMail", "SendMail",
"POST", "POST",
"/sendmail", "/sendmail",
MuxSecAllowedDomainsHandler(http.HandlerFunc(SendMail)), MuxSecAllowedDomainsHandler(
MuxSecReCaptchaHandler(
http.HandlerFunc(SendMail))),
}, },
Route{ Route{
"Healthz", "Healthz",

View File

@ -27,6 +27,7 @@ import (
"net/smtp" "net/smtp"
"strings" "strings"
"github.com/dpapathanasiou/go-recaptcha"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -180,6 +181,37 @@ func MuxSecAllowedDomainsHandler(next http.Handler) http.Handler {
}) })
} }
// MuxSecReCaptchaHandler is a security middleware which verifies the challenge code from
// the reCaptcha human verification system (provided by Google).
func MuxSecReCaptchaHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
recaptchaResponse, found := r.Form["g-recaptcha-response"]
if found {
remoteIp, _, _ := net.SplitHostPort(r.RemoteAddr)
recaptchaPrivateKey := viper.GetString("RECAPTCHA_PRIVATE_KEY")
recaptcha.Init(recaptchaPrivateKey)
result, err := recaptcha.Confirm(remoteIp, recaptchaResponse[0])
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Errorln("reCaptcha server error")
w.WriteHeader(http.StatusForbidden)
return
}
if !result {
w.WriteHeader(http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r)
})
}
// SendMail handles HTTP request to send email // SendMail handles HTTP request to send email
func SendMail(httpResp http.ResponseWriter, httpReq *http.Request) { func SendMail(httpResp http.ResponseWriter, httpReq *http.Request) {
httpReq.ParseForm() httpReq.ParseForm()
@ -234,12 +266,12 @@ func SendMail(httpResp http.ResponseWriter, httpReq *http.Request) {
replyTplFile := "" replyTplFile := ""
if contactRequest.RequestTarget == "demo" { if contactRequest.RequestTarget == "demo" {
replyTplFile = viper.GetString("TEMPLATE_DEMO_REQUEST_REPLY"); replyTplFile = viper.GetString("TEMPLATE_DEMO_REQUEST_REPLY")
if replyTplFile == "" { if replyTplFile == "" {
replyTplFile = "./templates/template_reply_demo_request.html" replyTplFile = "./templates/template_reply_demo_request.html"
} }
} else { } else {
replyTplFile = viper.GetString("TEMPLATE_CONTACT_REQUEST_REPLY"); replyTplFile = viper.GetString("TEMPLATE_CONTACT_REQUEST_REPLY")
if replyTplFile == "" { if replyTplFile == "" {
replyTplFile = "./templates/template_reply_contact_request.html" replyTplFile = "./templates/template_reply_contact_request.html"
} }