You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.go 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/gorilla/csrf"
  6. "github.com/gorilla/mux"
  7. "github.com/jamiealquiza/envy"
  8. "html/template"
  9. "log"
  10. "math/rand"
  11. "net/http"
  12. "net/smtp"
  13. "os"
  14. "strings"
  15. )
  16. const (
  17. csrfFieldName = "csrf.Token"
  18. )
  19. var (
  20. fromAddress, toAddress, subject, smtpServer, smtpUsername, smtpPassword, csrfKey *string
  21. smtpPort, port *int
  22. formTemplate, successTemplate, failureTemplate *template.Template
  23. )
  24. func sendMail(replyTo, message string) bool {
  25. auth := smtp.PlainAuth("", *smtpUsername, *smtpPassword, *smtpServer)
  26. body := fmt.Sprintf("To: %s\r\nSubject: %s\r\nReply-to: %s\r\nFrom: Online contact form <%s>\r\n\r\n%s\r\n", *toAddress, *subject, replyTo, *fromAddress, message)
  27. err := smtp.SendMail(fmt.Sprintf("%s:%d", *smtpServer, *smtpPort), auth, *fromAddress, []string{*toAddress}, []byte(body))
  28. if err != nil {
  29. log.Printf("Unable to send mail: %s", err)
  30. return false
  31. }
  32. return true
  33. }
  34. func handleForm(rw http.ResponseWriter, req *http.Request) {
  35. body := ""
  36. for k, v := range req.Form {
  37. if k != csrfFieldName {
  38. body += fmt.Sprintf("%s:\r\n%s\r\n\r\n", strings.ToUpper(k), v[0])
  39. }
  40. }
  41. if sendMail(req.Form.Get("from"), body) {
  42. rw.Header().Add("Location", "success")
  43. } else {
  44. rw.Header().Add("Location", "failure")
  45. }
  46. rw.WriteHeader(http.StatusSeeOther)
  47. }
  48. func showForm(rw http.ResponseWriter, req *http.Request) {
  49. _ = formTemplate.ExecuteTemplate(rw, "form.html", map[string]interface{}{
  50. csrf.TemplateTag: csrf.TemplateField(req),
  51. })
  52. }
  53. func showSuccess(rw http.ResponseWriter, req *http.Request) {
  54. _ = successTemplate.ExecuteTemplate(rw, "success.html", map[string]interface{}{
  55. csrf.TemplateTag: csrf.TemplateField(req),
  56. })
  57. }
  58. func showFailure(rw http.ResponseWriter, req *http.Request) {
  59. _ = failureTemplate.ExecuteTemplate(rw, "failure.html", map[string]interface{}{
  60. csrf.TemplateTag: csrf.TemplateField(req),
  61. })
  62. }
  63. func randomKey() string {
  64. var runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  65. b := make([]rune, 32)
  66. for i := range b {
  67. b[i] = runes[rand.Intn(len(runes))]
  68. }
  69. return string(b)
  70. }
  71. func checkFlag(value string, name string) {
  72. if len(value) == 0 {
  73. _, _ = fmt.Fprintf(os.Stderr, "No %s specified\n", name)
  74. flag.Usage()
  75. os.Exit(1)
  76. }
  77. }
  78. func loadTemplate(file string) (result *template.Template) {
  79. var err error
  80. result, err = template.ParseFiles(file)
  81. if err != nil {
  82. _, _ = fmt.Fprintf(os.Stderr, "Unable to load %s: %s\n", file, err.Error())
  83. os.Exit(1)
  84. }
  85. return
  86. }
  87. func main() {
  88. fromAddress = flag.String("from", "", "address to send e-mail from")
  89. toAddress = flag.String("to", "", "address to send e-mail to")
  90. subject = flag.String("subject", "Contact form submission", "e-mail subject")
  91. smtpServer = flag.String("smtp-host", "", "SMTP server to connect to")
  92. smtpPort = flag.Int("smtp-port", 25, "port to use when connecting to the SMTP server")
  93. smtpUsername = flag.String("smtp-user", "", "username to supply to the SMTP server")
  94. smtpPassword = flag.String("smtp-pass", "", "password to supply to the SMTP server")
  95. csrfKey = flag.String("crsf-key", "", "CRSF key to use")
  96. port = flag.Int("port", 8080, "port to listen on for connections")
  97. envy.Parse("CONTACT")
  98. flag.Parse()
  99. checkFlag(*fromAddress, "from address")
  100. checkFlag(*toAddress, "to address")
  101. checkFlag(*smtpServer, "SMTP server")
  102. checkFlag(*smtpUsername, "SMTP username")
  103. checkFlag(*smtpPassword, "SMTP password")
  104. if len(*csrfKey) != 32 {
  105. newKey := randomKey()
  106. csrfKey = &newKey
  107. }
  108. formTemplate = loadTemplate("form.html")
  109. successTemplate = loadTemplate("success.html")
  110. failureTemplate = loadTemplate("failure.html")
  111. r := mux.NewRouter()
  112. r.HandleFunc("/", showForm).Methods("GET")
  113. r.HandleFunc("/success", showSuccess).Methods("GET")
  114. r.HandleFunc("/failure", showFailure).Methods("GET")
  115. r.HandleFunc("/submit", handleForm).Methods("POST")
  116. CSRF := csrf.Protect([]byte(*csrfKey), csrf.FieldName(csrfFieldName))
  117. err := http.ListenAndServe(fmt.Sprintf(":%d", *port), CSRF(r))
  118. if err != nil {
  119. _, _ = fmt.Fprintf(os.Stderr, "Unable to listen on port %d: %s\n", *port, err.Error())
  120. }
  121. }