alfheim-website/cmd/web/middleware.go

42 lines
1.0 KiB
Go

package main
import (
"log"
"net/http"
)
func secureHeaders(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("X-Frame-Options", "deny")
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func logRequest(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s - %s %s %s", r.RemoteAddr, r.Proto, r.Method, r.URL)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func requireAuthenticatedUser(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// If the user is not authenticated, redirect them to the login page and
// return from the middleware chain so that no subsequent handlers in
// the chain are executed.
if authenticatedUser(w, r) == 0 {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// Otherwise call the next handler in the chain.
next.ServeHTTP(w, r)
})
}