All checks were successful
Build and Push Docker Image / Build-And-Push-Docker-Image (push) Successful in 1m17s
54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"spend-sparrow/internal/core"
|
|
"spend-sparrow/internal/service"
|
|
"strings"
|
|
)
|
|
|
|
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) {
|
|
ctx := r.Context()
|
|
|
|
if strings.Contains(r.URL.Path, "/static/") {
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
return
|
|
}
|
|
|
|
sessionId := getSessionID(r)
|
|
session, user, _ := service.SignInSession(r.Context(), sessionId)
|
|
|
|
var err error
|
|
// Always sign in anonymous
|
|
// This way, we can always generate csrf tokens
|
|
if session == nil {
|
|
session, err = service.SignInAnonymous(r.Context())
|
|
if err != nil {
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
cookie := CreateSessionCookie(session.Id)
|
|
http.SetCookie(w, &cookie)
|
|
}
|
|
|
|
ctx = context.WithValue(ctx, core.UserKey, user)
|
|
ctx = context.WithValue(ctx, core.SessionKey, session)
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
func getSessionID(r *http.Request) string {
|
|
cookie, err := r.Cookie("id")
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
|
|
return cookie.Value
|
|
}
|