Writing auth middleware

This commit is contained in:
2024-07-19 18:40:19 +02:00
parent a6dca00199
commit a0853cf880
4 changed files with 22 additions and 3 deletions

View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"go-udemy-web-1/internal/helpers"
"net/http"
"github.com/justinas/nosurf"
@ -34,3 +35,15 @@ func NoSurf(next http.Handler) http.Handler {
func SessionLoad(next http.Handler) http.Handler {
return session.LoadAndSave(next)
}
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)
})
}