Installing and setting up a sessions package
This commit is contained in:
@ -7,13 +7,30 @@ import (
|
||||
"go-udemy-web-1/pkg/render"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/alexedwards/scs/v2"
|
||||
)
|
||||
|
||||
const portNumber = ":8080"
|
||||
|
||||
var (
|
||||
app config.AppConfig
|
||||
session *scs.SessionManager
|
||||
)
|
||||
|
||||
// main is the main application function
|
||||
func main() {
|
||||
var app config.AppConfig
|
||||
// change this to true when in production
|
||||
app.InProduction = false
|
||||
|
||||
session = scs.New()
|
||||
session.Lifetime = 24 * time.Hour
|
||||
session.Cookie.Persist = true
|
||||
session.Cookie.SameSite = http.SameSiteLaxMode
|
||||
session.Cookie.Secure = app.InProduction
|
||||
|
||||
app.Session = session
|
||||
|
||||
tc, err := render.CreateTemplateCache()
|
||||
if err != nil {
|
||||
|
@ -7,6 +7,7 @@ import (
|
||||
"github.com/justinas/nosurf"
|
||||
)
|
||||
|
||||
// WriteToConsole writes a log when user hits a page
|
||||
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())
|
||||
@ -15,15 +16,21 @@ func WriteToConsole(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// NoSurf adds CSRF protection to all POST requests
|
||||
func NoSurf(next http.Handler) http.Handler {
|
||||
csrfHandler := nosurf.New(next)
|
||||
|
||||
csrfHandler.SetBaseCookie(http.Cookie{
|
||||
HttpOnly: true,
|
||||
Path: "/",
|
||||
Secure: false,
|
||||
Secure: app.InProduction,
|
||||
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)
|
||||
}
|
||||
|
@ -15,6 +15,7 @@ func routes(app *config.AppConfig) http.Handler {
|
||||
mux.Use(middleware.Recoverer)
|
||||
mux.Use(WriteToConsole)
|
||||
mux.Use(NoSurf)
|
||||
mux.Use(SessionLoad)
|
||||
|
||||
mux.Get("/", handlers.Repo.Home)
|
||||
mux.Get("/about", handlers.Repo.About)
|
||||
|
Reference in New Issue
Block a user