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/handler/middleware/authenticate.go
Tim Wundenberg 3db73cb6e5
Some checks failed
Build Docker Image / Build-Docker-Image (push) Has been cancelled
tbs
2024-12-05 23:24:39 +01:00

39 lines
726 B
Go

package middleware
import (
"context"
"me-fit/service"
"net/http"
)
type ContextKey string
var SessionKey ContextKey = "session"
func Authenticate(service service.Auth) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sessionId := getSessionID(r)
session, _ := service.SignInSession(sessionId)
if session != nil {
ctx := context.WithValue(r.Context(), SessionKey, session)
next.ServeHTTP(w, r.WithContext(ctx))
} else {
next.ServeHTTP(w, r)
}
})
}
}
func getSessionID(r *http.Request) string {
cookie, err := r.Cookie("id")
if err != nil {
return ""
}
return cookie.Name
}