37 lines
988 B
Go
37 lines
988 B
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"clintonambulance.com/calculate_negative_points/internal/config"
|
|
)
|
|
|
|
func OidcMiddleware(config *config.ApplicationConfig) (func(http.Handler) http.Handler, error) {
|
|
middleware := func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
session, _ := config.CookieStore.Get(r, config.SessionName)
|
|
rawIDToken, ok := session.Values["id_token"].(string)
|
|
if !ok {
|
|
// Not authenticated; redirect to login
|
|
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
|
return
|
|
}
|
|
|
|
idToken, _, err := verifyTokenAndGetClaims(config, r.Context(), rawIDToken)
|
|
if err != nil {
|
|
session.Options.MaxAge = -1
|
|
session.Save(r, w)
|
|
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
|
return
|
|
}
|
|
|
|
// Add token to context
|
|
ctx := context.WithValue(r.Context(), "id_token", idToken)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
return middleware, nil
|
|
}
|