This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/middleware/auth.go
Tim Wundenberg bb9381433b
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 46s
chore(auth): add test for retrieving session from db #181
2024-09-18 23:07:01 +02:00

32 lines
601 B
Go

package middleware
import (
"me-fit/service"
"me-fit/utils"
"context"
"database/sql"
"net/http"
)
func EnsureValidSession(db *sql.DB, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := service.GetUserFromRequest(db, r)
if user == nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
if !user.EmailVerified && r.URL.Path != "/auth/verify" {
utils.DoRedirect(w, r, "/auth/verify")
return
}
ctx := context.WithValue(r.Context(), utils.ContextKeyUser, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}