ch11.7
This commit is contained in:
@@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/justinas/nosurf"
|
||||
)
|
||||
|
||||
func secureHeaders(next http.Handler) http.Handler {
|
||||
@@ -49,3 +51,14 @@ func (app *application) requireAuthentication(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func noSurf(next http.Handler) http.Handler {
|
||||
csrfHanlder := nosurf.New(next)
|
||||
csrfHanlder.SetBaseCookie(http.Cookie{
|
||||
HttpOnly: true,
|
||||
Path: "/",
|
||||
Secure: true,
|
||||
})
|
||||
|
||||
return csrfHanlder
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ func (app *application) routes() http.Handler {
|
||||
fileServer := http.FileServer(http.Dir("./ui/static/"))
|
||||
router.Handler(http.MethodGet, "/static/*filepath", http.StripPrefix("/static", fileServer))
|
||||
|
||||
dynamic := alice.New(app.sessionManager.LoadAndSave)
|
||||
dynamic := alice.New(app.sessionManager.LoadAndSave, noSurf)
|
||||
|
||||
router.Handler(http.MethodGet, "/", dynamic.ThenFunc(app.home))
|
||||
router.Handler(http.MethodGet, "/snippet/view/:id", dynamic.ThenFunc(app.snippetView))
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"gitea.local.lab/Lbenedar/snippetbox/internal/models"
|
||||
"github.com/justinas/nosurf"
|
||||
)
|
||||
|
||||
type templateData struct {
|
||||
@@ -16,6 +17,7 @@ type templateData struct {
|
||||
Form any
|
||||
Flash string
|
||||
IsAuthenticated bool
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
func humanDate(t time.Time) string {
|
||||
@@ -31,6 +33,7 @@ func (app *application) newTemplateData(r *http.Request) *templateData {
|
||||
CurrentYear: time.Now().Year(),
|
||||
Flash: app.sessionManager.PopString(r.Context(), "flash"),
|
||||
IsAuthenticated: app.isAuthenticated(r),
|
||||
CSRFToken: nosurf.Token(r),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user