drone/internal/api/middleware/authn/authn.go
2022-09-05 13:47:00 -07:00

42 lines
1.1 KiB
Go

// Copyright 2021 Harness Inc. All rights reserved.
// Use of this source code is governed by the Polyform Free Trial License
// that can be found in the LICENSE.md file for this repository.
package authn
import (
"net/http"
"github.com/harness/gitness/internal/api/render"
"github.com/harness/gitness/internal/api/request"
"github.com/harness/gitness/internal/auth/authn"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
/*
* Enforce returns an http.HandlerFunc middleware that authenticates
* the http.Request and errors if the account cannot be authenticated.
*/
func Enforce(authenticator authn.Authenticator) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := authenticator.Authenticate(r)
if err != nil {
render.Unauthorized(w, err)
return
}
ctx := r.Context()
log.Ctx(ctx).UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("session_email", user.Email).Bool("session_admin", user.Admin)
})
next.ServeHTTP(w, r.WithContext(
request.WithUser(ctx, user),
))
})
}
}