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.

80 lines
1.7 KiB

package middleware
import (
// URL suffixes to allow to bypass the age gate middleware.
var ageGateSuffixes = []string{
"/blog.rss", // Allow public access to RSS and Atom feeds.
// AgeGate is a middleware generator that does age verification for NSFW sites.
// Single GET requests with ?over18=1 parameter may skip the middleware check.
func AgeGate(next http.Handler) http.Handler {
middleware := func(w http.ResponseWriter, r *http.Request) {
s := settings.Current
if !s.NSFW {
next.ServeHTTP(w, r)
path := r.URL.Path
// Let the age-verify handler catch its route.
if strings.HasPrefix(path, "/age-verify") {
next.ServeHTTP(w, r)
// Allow static file requests to skip the check.
for _, suffix := range ageGateSuffixes {
if strings.HasSuffix(path, suffix) {
next.ServeHTTP(w, r)
// POST requests are permitted (e.g. post a comment on a /?over18=1 page)
if r.Method == http.MethodPost {
next.ServeHTTP(w, r)
// Finally, check if they've confirmed their age on the age-verify handler.
ses := session.Get(r)
if val, _ := ses.Values["age-ok"].(bool); !val {
// They haven't been verified. Redirect them to the age-verify handler.
if r.FormValue("over18") == "" {
responses.Redirect(w, r, "/age-verify?next="+path)
next.ServeHTTP(w, r)
return http.HandlerFunc(middleware)