chore(auth): add test for retrieving session from db #181
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 46s

This commit is contained in:
2024-09-18 23:07:01 +02:00
parent dbe687c105
commit bb9381433b
9 changed files with 229 additions and 82 deletions

View File

@@ -3,17 +3,19 @@ package handler
import (
"me-fit/middleware"
"me-fit/service"
"me-fit/template"
"me-fit/utils"
"database/sql"
"net/http"
)
func GetHandler(db *sql.DB) http.Handler {
var router = http.NewServeMux()
router := http.NewServeMux()
router.HandleFunc("/", service.HandleIndexAnd404(db))
router.HandleFunc("/$", handleIndex(db))
router.HandleFunc("/", handleNotFound(db))
// Serve static files (CSS, JS and images)
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
router.Handle("/auth/", authUi(db))
@@ -32,3 +34,33 @@ func GetHandler(db *sql.DB) http.Handler {
func auth(db *sql.DB, h http.Handler) http.Handler {
return middleware.EnsureValidSession(db, h)
}
func handleIndex(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := service.GetUserFromRequest(db, r)
err := template.
Layout(template.Index(), service.UserInfoComp(user)).
Render(r.Context(), w)
if err != nil {
utils.LogError("Failed to render index", err)
http.Error(w, "Failed to render index", http.StatusInternalServerError)
}
}
}
func handleNotFound(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := service.GetUserFromRequest(db, r)
err := template.
Layout(template.NotFound(), service.UserInfoComp(user)).
Render(r.Context(), w)
if err != nil {
utils.LogError("Failed to render index", err)
http.Error(w, "Failed to render index", http.StatusInternalServerError)
}
w.WriteHeader(http.StatusNotFound)
}
}