You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

175 lines
4.0 KiB
Go

/*
Copyright 2020-2023 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handlers
import (
"context"
"fmt"
"html/template"
"net/http"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
"code.cacert.org/cacert/oidc-demo-app/ui"
"code.cacert.org/cacert/oidc-demo-app/internal/services"
)
type errorKey int
const (
errorBucketKey errorKey = iota
)
type ErrorDetails struct {
ErrorMessage string
ErrorDetails []string
ErrorCode string
Error error
}
type ErrorBucket struct {
errorDetails *ErrorDetails
templates *template.Template
logger *log.Logger
bundle *i18n.Bundle
messageCatalog *services.MessageCatalog
}
func (b *ErrorBucket) GetBundle() *i18n.Bundle {
return b.bundle
}
func (b *ErrorBucket) GetCatalog() *services.MessageCatalog {
return b.messageCatalog
}
func (b *ErrorBucket) serveHTTP(w http.ResponseWriter, r *http.Request) {
if b.errorDetails != nil {
localizer := GetLocalizer(b, r)
data := BaseTemplateData(b, localizer)
data["Title"] = b.messageCatalog.LookupMessage(
"ErrorTitle",
nil,
localizer,
)
data["details"] = b.errorDetails
err := b.templates.Lookup("base").Execute(w, data)
if err != nil {
log.WithError(err).Error("error rendering error template")
http.Error(
w,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
}
}
}
func GetErrorBucket(r *http.Request) *ErrorBucket {
if v, ok := r.Context().Value(errorBucketKey).(*ErrorBucket); ok {
return v
}
return nil
}
// AddError can be called from an application handler to add an error
func (b *ErrorBucket) AddError(details *ErrorDetails) {
b.errorDetails = details
}
type errorResponseWriter struct {
http.ResponseWriter
errorBucket *ErrorBucket
statusCode int
}
func (w *errorResponseWriter) WriteHeader(code int) {
w.statusCode = code
if code >= http.StatusBadRequest {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if w.errorBucket != nil && w.errorBucket.errorDetails == nil {
w.errorBucket.AddError(&ErrorDetails{
ErrorMessage: http.StatusText(code),
})
}
}
w.ResponseWriter.WriteHeader(code)
}
func (w *errorResponseWriter) Write(content []byte) (int, error) {
if w.statusCode > http.StatusBadRequest {
if w.errorBucket != nil {
if w.errorBucket.errorDetails.ErrorDetails == nil {
w.errorBucket.errorDetails.ErrorDetails = make([]string, 0)
}
w.errorBucket.errorDetails.ErrorDetails = append(
w.errorBucket.errorDetails.ErrorDetails, string(content),
)
return len(content), nil
}
}
l, err := w.ResponseWriter.Write(content)
if err != nil {
return l, fmt.Errorf("could not write to response: %w", err)
}
return l, nil
}
func ErrorHandling(
logger *log.Logger,
bundle *i18n.Bundle,
messageCatalog *services.MessageCatalog,
) (func(http.Handler) http.Handler, error) {
errorTemplates, err := template.ParseFS(
ui.Templates,
"templates/base.gohtml",
"templates/errors.gohtml",
)
if err != nil {
return nil, fmt.Errorf("could not parse templates: %w", err)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
errorBucket := &ErrorBucket{
templates: errorTemplates,
logger: logger,
bundle: bundle,
messageCatalog: messageCatalog,
}
next.ServeHTTP(
&errorResponseWriter{w, errorBucket, http.StatusOK},
r.WithContext(context.WithValue(r.Context(), errorBucketKey, errorBucket)),
)
errorBucket.serveHTTP(w, r)
})
}, nil
}