Added page protection for unauthorized access

This commit is contained in:
2025-02-14 19:51:40 +11:00
parent 5616b8a248
commit ea4dd2a407
8 changed files with 107 additions and 15 deletions

View File

@@ -0,0 +1,36 @@
package middleware
import (
"net/http"
"projectreshoot/contexts"
"projectreshoot/view/page"
)
// Checks if the user is set in the context and shows 401 page if not logged in
func RequiresLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := contexts.GetUser(r.Context())
if user == nil {
page.Error(
"401",
"Unauthorized",
"Please login to view this page",
).Render(r.Context(), w)
return
}
next.ServeHTTP(w, r)
})
}
// Checks if the user is set in the context and redirects them to profile if
// they are logged in
func RequiresLogout(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := contexts.GetUser(r.Context())
if user != nil {
http.Redirect(w, r, "/profile", http.StatusFound)
return
}
next.ServeHTTP(w, r)
})
}