36 lines
973 B
Go
36 lines
973 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gorilla/sessions"
|
|
)
|
|
|
|
// SecureHeaders is a middleware function that adds secure headers to the HTTP response
|
|
func SecureHeaders(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Security-Policy", "default-src 'self'")
|
|
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// middleware/csrf.go
|
|
func CSRFMiddleware(store sessions.Store) Middleware {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == "POST" {
|
|
session, _ := store.Get(r, "auth-session")
|
|
csrfToken := session.Values["csrf_token"].(string)
|
|
formToken := r.FormValue("_csrf")
|
|
|
|
if csrfToken != formToken {
|
|
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
|
|
return
|
|
}
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|