Add custom claims
All checks were successful
ci/woodpecker/pr/woodpecker Pipeline was successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
2022-01-20 13:33:11 +01:00
parent e0850233dc
commit 6fdd55def8
5 changed files with 39 additions and 15 deletions

View File

@@ -16,6 +16,7 @@ type authCtxKey int
const (
authCtxUsername authCtxKey = iota
authCtxAuthLevel
authCtxClaims
)
func (s *HTTPServer) MiddlewareAccessLogger(next http.Handler) http.Handler {
@@ -66,7 +67,8 @@ func (s *HTTPServer) MiddlewareAuthentication(next http.Handler) http.Handler {
}
ctx := context.WithValue(r.Context(), authCtxUsername, claims.Subject)
ctx = context.WithValue(ctx, authCtxAuthLevel, gpaste.AuthLevelUser)
ctx = context.WithValue(ctx, authCtxAuthLevel, claims.Role)
ctx = context.WithValue(ctx, authCtxClaims, claims)
withCtx := r.WithContext(ctx)
s.Logger.Debugw("Request is authenticated.", "req_id", reqID, "username", claims.Subject)
@@ -79,7 +81,6 @@ func (s *HTTPServer) MiddlewareAuthentication(next http.Handler) http.Handler {
func UsernameFromRequest(r *http.Request) (string, error) {
rawUsername := r.Context().Value(authCtxUsername)
if rawUsername == nil {
return "", fmt.Errorf("no username")
}
username, ok := rawUsername.(string)
@@ -100,3 +101,15 @@ func AuthLevelFromRequest(r *http.Request) (gpaste.AuthLevel, error) {
}
return level, nil
}
func ClaimsFromRequest(r *http.Request) *gpaste.Claims {
rawClaims := r.Context().Value(authCtxAuthLevel)
if rawClaims == nil {
return nil
}
claims, ok := rawClaims.(*gpaste.Claims)
if !ok {
return nil
}
return claims
}