2020-07-08 09:48:11 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-08-28 09:44:43 +02:00
|
|
|
"errors"
|
2020-07-08 09:48:11 +02:00
|
|
|
|
|
|
|
"github.com/rakyll/statik/fs"
|
2022-04-27 01:01:45 +02:00
|
|
|
"github.com/zitadel/logging"
|
2020-07-08 09:48:11 +02:00
|
|
|
"golang.org/x/text/language"
|
2021-07-05 10:58:58 +02:00
|
|
|
|
2022-04-27 01:01:45 +02:00
|
|
|
caos_errs "github.com/zitadel/zitadel/internal/errors"
|
|
|
|
"github.com/zitadel/zitadel/internal/i18n"
|
2020-07-08 09:48:11 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type localizers interface {
|
|
|
|
Localizers() []Localizer
|
|
|
|
}
|
|
|
|
type Localizer interface {
|
|
|
|
LocalizationKey() string
|
|
|
|
SetLocalizedMessage(string)
|
|
|
|
}
|
|
|
|
|
|
|
|
func translateFields(ctx context.Context, object localizers, translator *i18n.Translator) {
|
|
|
|
if translator == nil || object == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for _, field := range object.Localizers() {
|
|
|
|
field.SetLocalizedMessage(translator.LocalizeFromCtx(ctx, field.LocalizationKey(), nil))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-28 09:44:43 +02:00
|
|
|
func translateError(ctx context.Context, err error, translator *i18n.Translator) error {
|
|
|
|
if translator == nil || err == nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
caosErr := new(caos_errs.CaosError)
|
|
|
|
if errors.As(err, &caosErr) {
|
|
|
|
caosErr.SetMessage(translator.LocalizeFromCtx(ctx, caosErr.GetMessage(), nil))
|
|
|
|
}
|
2021-07-05 10:58:58 +02:00
|
|
|
return err
|
2020-08-28 09:44:43 +02:00
|
|
|
}
|
|
|
|
|
2022-07-07 14:58:00 +02:00
|
|
|
func newZitadelTranslator(defaultLanguage language.Tag) (*i18n.Translator, error) {
|
2020-07-08 09:48:11 +02:00
|
|
|
return translatorFromNamespace("zitadel", defaultLanguage)
|
|
|
|
}
|
|
|
|
|
2022-07-07 14:58:00 +02:00
|
|
|
func translatorFromNamespace(namespace string, defaultLanguage language.Tag) (*i18n.Translator, error) {
|
2020-07-08 09:48:11 +02:00
|
|
|
dir, err := fs.NewWithNamespace(namespace)
|
2022-07-07 14:58:00 +02:00
|
|
|
logging.WithFields("namespace", namespace).OnError(err).Panic("unable to get namespace")
|
2020-07-08 09:48:11 +02:00
|
|
|
|
2022-07-07 14:58:00 +02:00
|
|
|
return i18n.NewTranslator(dir, defaultLanguage, "")
|
2020-07-08 09:48:11 +02:00
|
|
|
}
|