Writing auth middleware
This commit is contained in:
		@ -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)
 | 
			
		||||
	})
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user