cleaned up logic

This commit is contained in:
Darko Luketic 2021-11-16 15:55:07 +01:00
parent 4d131928ad
commit 448ee700c8

23
gin.go
View File

@ -24,12 +24,11 @@ func onError(c *gin.Context, errorHandler options.ErrorHandler, statusCode int,
c.AbortWithStatusJSON(statusCode, gin.H{"error": err.Error()}) c.AbortWithStatusJSON(statusCode, gin.H{"error": err.Error()})
} }
// toGinHandler creates a gin.HandlerFunc so the stdlib handler can be used as a gin middleware.
func toGinHandler(parseToken oidc.ParseTokenFunc, setters ...options.Option) gin.HandlerFunc { func toGinHandler(parseToken oidc.ParseTokenFunc, setters ...options.Option) gin.HandlerFunc {
opts := options.New(setters...) opts := options.New(setters...)
return func(c *gin.Context) { return func(c *gin.Context) {
var errorTypes []ginerror.Error
ctx := c.Request.Context() ctx := c.Request.Context()
tokenString, err := oidc.GetTokenString(c.Request.Header.Get, opts.TokenString) tokenString, err := oidc.GetTokenString(c.Request.Header.Get, opts.TokenString)
@ -38,41 +37,29 @@ func toGinHandler(parseToken oidc.ParseTokenFunc, setters ...options.Option) gin
onError(c, opts.ErrorHandler, http.StatusBadRequest, options.GetTokenErrorDescription, err) onError(c, opts.ErrorHandler, http.StatusBadRequest, options.GetTokenErrorDescription, err)
return return
} else { } else {
errorTypes = append(errorTypes, ginerror.Error{ c.Set(string(opts.ErrorsContextKeyName), ginerror.Error{
Description: string(options.GetTokenErrorDescription), Description: string(options.GetTokenErrorDescription),
Error: err, Error: err,
}) })
c.Next()
return
} }
} }
token, err := parseToken(ctx, tokenString) token, err := parseToken(ctx, tokenString)
if err != nil { if err != nil {
if !opts.Permissive {
onError(c, opts.ErrorHandler, http.StatusUnauthorized, options.ParseTokenErrorDescription, err) onError(c, opts.ErrorHandler, http.StatusUnauthorized, options.ParseTokenErrorDescription, err)
return return
} else {
errorTypes = append(errorTypes, ginerror.Error{
Description: string(options.ParseTokenErrorDescription),
Error: err,
})
}
} }
tokenClaims, err := token.AsMap(ctx) tokenClaims, err := token.AsMap(ctx)
if err != nil { if err != nil {
if !opts.Permissive {
onError(c, opts.ErrorHandler, http.StatusUnauthorized, options.ConvertTokenErrorDescription, err) onError(c, opts.ErrorHandler, http.StatusUnauthorized, options.ConvertTokenErrorDescription, err)
return return
} else {
errorTypes = append(errorTypes, ginerror.Error{
Description: string(options.ConvertTokenErrorDescription),
Error: err,
})
}
} }
c.Set(string(opts.ClaimsContextKeyName), tokenClaims) c.Set(string(opts.ClaimsContextKeyName), tokenClaims)
c.Set(string(opts.ErrorsContextKeyName), errorTypes)
c.Next() c.Next()
} }