summaryrefslogtreecommitdiff
path: root/app/middleware/id_token.go
blob: dbaf691fe34b355ba121aeb4a79548315b6c09de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package middleware

import (
	"net/http"

	"github.com/xlgmokha/x/pkg/log"
	"github.com/xlgmokha/x/pkg/x"
	xcfg "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/oidc"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/web"
)

func IDToken(cfg *oidc.OpenID, parsers ...TokenParser) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			for _, parser := range parsers {
				rawIDToken := parser(r)
				if x.IsPresent(rawIDToken) {
					idToken, err := cfg.ValidateIDToken(r.Context(), rawIDToken)

					if err != nil {
						pls.LogError(r.Context(), err)
						web.ExpireCookie(w, xcfg.IDTokenCookie)
					} else {
						log.WithFields(r.Context(), log.Fields{"id_token": idToken})
						next.ServeHTTP(
							w,
							r.WithContext(xcfg.IDToken.With(r.Context(), idToken)),
						)
						return
					}
				}
			}

			next.ServeHTTP(w, r)
		})
	}
}