Add RequireUser middleware

This commit is contained in:
Lucas Schumacher 2024-08-29 07:03:13 -04:00
parent e32aa9ca6c
commit 530672437c
2 changed files with 29 additions and 5 deletions

View File

@ -47,3 +47,25 @@ func (umw UserMiddleware) SetUser(next http.Handler) http.Handler {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
}) })
} }
func (umw UserMiddleware) RequireUserfn(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := User(r.Context())
if user == nil {
http.Redirect(w, r, "/signin", http.StatusFound)
return
}
next(w, r)
})
}
func (umw UserMiddleware) RequireUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := User(r.Context())
if user == nil {
http.Redirect(w, r, "/signin", http.StatusFound)
return
}
next.ServeHTTP(w, r)
})
}

12
main.go
View File

@ -69,9 +69,13 @@ func main() {
sessionService := models.SessionService{DB: db} sessionService := models.SessionService{DB: db}
var usersCtrlr ctrlrs.Users = ctrlrs.Default(&userService, &sessionService) var usersCtrlr ctrlrs.Users = ctrlrs.Default(&userService, &sessionService)
umw := userctx.UserMiddleware{SS: &sessionService}
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.Logger) r.Use(middleware.Logger)
r.Use(csrf.Protect(csrfKey, csrf.Secure(!DEBUG)))
r.Use(umw.SetUser)
r.Get("/", ctrlrs.StaticController("home.gohtml", "tailwind.gohtml")) r.Get("/", ctrlrs.StaticController("home.gohtml", "tailwind.gohtml"))
r.Get("/contact", ctrlrs.StaticController("contact.gohtml", "tailwind.gohtml")) r.Get("/contact", ctrlrs.StaticController("contact.gohtml", "tailwind.gohtml"))
@ -83,12 +87,10 @@ func main() {
r.Post("/signin", usersCtrlr.PostSignin) r.Post("/signin", usersCtrlr.PostSignin)
r.Post("/signout", usersCtrlr.GetSignout) r.Post("/signout", usersCtrlr.GetSignout)
r.Get("/user", usersCtrlr.CurrentUser) //r.Get("/user", usersCtrlr.CurrentUser)
r.Get("/user", umw.RequireUserfn(usersCtrlr.CurrentUser))
r.NotFound(notFoundHandler) r.NotFound(notFoundHandler)
umw := userctx.UserMiddleware{SS: &sessionService}
fmt.Println("Starting the server on :3000...") fmt.Println("Starting the server on :3000...")
http.ListenAndServe(":3000", csrf.Protect(csrfKey, csrf.Secure(!DEBUG))(umw.SetUser(r))) http.ListenAndServe(":3000", r)
} }