A temporary email service written in Go.
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.

67 lines
1.7 KiB

  1. package auth
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "regexp"
  9. "github.com/thebaer/burner/validate"
  10. )
  11. // Serve starts an HTTP server that handles auth requests from nginx.
  12. func Serve(port int) error {
  13. if port <= 0 {
  14. return errors.New("auth server: Invalid port number.")
  15. }
  16. serverPort = port
  17. mailInfo := log.New(os.Stdout, "", log.Ldate|log.Ltime)
  18. mailInfo.Printf("Starting mail auth server on :%d", serverPort)
  19. http.HandleFunc("/auth", authHandler)
  20. http.ListenAndServe(fmt.Sprintf("127.0.0.1:%d", serverPort), nil)
  21. return nil
  22. }
  23. var (
  24. // Port that the auth server will run on.
  25. serverPort int
  26. // Regular expression for matching / finding a valid To address.
  27. smtpEmailReg = regexp.MustCompile("<(.+)>")
  28. )
  29. // authHandler works with nginx to determine whether or not a receipient email
  30. // address is valid. If it is, running mail server's information is passed
  31. // back.
  32. func authHandler(w http.ResponseWriter, r *http.Request) {
  33. toHeader := r.Header.Get("Auth-SMTP-To")
  34. if toHeader == "" {
  35. w.Header().Set("Auth-Status", "Unrecognized receipient.")
  36. w.Header().Set("Auth-Error-Code", "550")
  37. return
  38. }
  39. to := smtpEmailReg.FindStringSubmatch(toHeader)[1]
  40. if to == "" {
  41. w.Header().Set("Auth-Status", "Unrecognized receipient.")
  42. w.Header().Set("Auth-Error-Code", "550")
  43. return
  44. }
  45. if err := validate.Email(to); err != nil {
  46. // Email address validation failed
  47. w.Header().Set("Auth-Status", err.Error())
  48. w.Header().Set("Auth-Error-Code", "550")
  49. return
  50. }
  51. // Email passed validation, send back mail server information
  52. w.Header().Set("Auth-Status", "OK")
  53. w.Header().Set("Auth-Server", "127.0.0.1")
  54. w.Header().Set("Auth-Port", fmt.Sprintf("%d", serverPort))
  55. }