udemy-go-web-1/cmd/web/middleware.go

50 lines
1.1 KiB
Go
Raw Normal View History

2024-06-28 11:33:43 +00:00
package main
import (
"fmt"
2024-07-19 16:40:19 +00:00
"go-udemy-web-1/internal/helpers"
2024-06-28 11:33:43 +00:00
"net/http"
"github.com/justinas/nosurf"
)
// WriteToConsole writes a log when user hits a page
2024-06-28 11:33:43 +00:00
func WriteToConsole(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Hit the page %s\n", r.URL.String())
next.ServeHTTP(w, r)
})
}
// NoSurf adds CSRF protection to all POST requests
2024-06-28 11:33:43 +00:00
func NoSurf(next http.Handler) http.Handler {
csrfHandler := nosurf.New(next)
csrfHandler.SetBaseCookie(http.Cookie{
HttpOnly: true,
Path: "/",
Secure: app.InProduction,
2024-06-28 11:33:43 +00:00
SameSite: http.SameSiteLaxMode,
})
return csrfHandler
}
// SessionLoad loads and saves the session on every request
func SessionLoad(next http.Handler) http.Handler {
return session.LoadAndSave(next)
}
2024-07-19 16:40:19 +00:00
func Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !helpers.IsAuthenticated(r) {
session.Put(r.Context(), "error", "Log in first!")
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}