A web blog and personal homepage engine 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.
 
 

81 lines
1.7 KiB

  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. "git.kirsle.net/apps/gophertype/pkg/responses"
  6. "git.kirsle.net/apps/gophertype/pkg/session"
  7. "git.kirsle.net/apps/gophertype/pkg/settings"
  8. )
  9. // URL suffixes to allow to bypass the age gate middleware.
  10. var ageGateSuffixes = []string{
  11. "/blog.rss", // Allow public access to RSS and Atom feeds.
  12. "/blog.atom",
  13. "/blog.json",
  14. ".js",
  15. ".css",
  16. ".txt",
  17. ".ico",
  18. ".png",
  19. ".jpg",
  20. ".jpeg",
  21. ".gif",
  22. ".mp4",
  23. ".webm",
  24. ".ttf",
  25. ".eot",
  26. ".svg",
  27. ".woff",
  28. ".woff2",
  29. }
  30. // AgeGate is a middleware generator that does age verification for NSFW sites.
  31. // Single GET requests with ?over18=1 parameter may skip the middleware check.
  32. func AgeGate(next http.Handler) http.Handler {
  33. middleware := func(w http.ResponseWriter, r *http.Request) {
  34. s := settings.Current
  35. if !s.NSFW {
  36. next.ServeHTTP(w, r)
  37. return
  38. }
  39. path := r.URL.Path
  40. // Let the age-verify handler catch its route.
  41. if strings.HasPrefix(path, "/age-verify") {
  42. next.ServeHTTP(w, r)
  43. return
  44. }
  45. // Allow static file requests to skip the check.
  46. for _, suffix := range ageGateSuffixes {
  47. if strings.HasSuffix(path, suffix) {
  48. next.ServeHTTP(w, r)
  49. return
  50. }
  51. }
  52. // POST requests are permitted (e.g. post a comment on a /?over18=1 page)
  53. if r.Method == http.MethodPost {
  54. next.ServeHTTP(w, r)
  55. return
  56. }
  57. // Finally, check if they've confirmed their age on the age-verify handler.
  58. ses := session.Get(r)
  59. if val, _ := ses.Values["age-ok"].(bool); !val {
  60. // They haven't been verified. Redirect them to the age-verify handler.
  61. if r.FormValue("over18") == "" {
  62. responses.Redirect(w, r, "/age-verify?next="+path)
  63. return
  64. }
  65. }
  66. next.ServeHTTP(w, r)
  67. }
  68. return http.HandlerFunc(middleware)
  69. }