diff options
Diffstat (limited to 'internal/configuration/decode_hooks.go')
| -rw-r--r-- | internal/configuration/decode_hooks.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/internal/configuration/decode_hooks.go b/internal/configuration/decode_hooks.go index 513f7fd37..cc9aac697 100644 --- a/internal/configuration/decode_hooks.go +++ b/internal/configuration/decode_hooks.go @@ -4,8 +4,11 @@ import ( "fmt" "net/mail" "reflect" + "time" "github.com/mitchellh/mapstructure" + + "github.com/authelia/authelia/v4/internal/utils" ) // StringToMailAddressFunc decodes a string into a mail.Address. @@ -33,3 +36,67 @@ func StringToMailAddressFunc() mapstructure.DecodeHookFunc { return *mailAddress, nil } } + +// ToTimeDurationFunc converts string and integer types to a time.Duration. +func ToTimeDurationFunc() mapstructure.DecodeHookFuncType { + return func(f reflect.Type, t reflect.Type, data interface{}) (value interface{}, err error) { + var ( + ptr bool + ) + + switch f.Kind() { + case reflect.String, reflect.Int, reflect.Int32, reflect.Int64: + // We only allow string and integer from kinds to match. + break + default: + return data, nil + } + + typeTimeDuration := reflect.TypeOf(time.Hour) + + if t.Kind() == reflect.Ptr { + if t.Elem() != typeTimeDuration { + return data, nil + } + + ptr = true + } else if t != typeTimeDuration { + return data, nil + } + + var duration time.Duration + + switch { + case f.Kind() == reflect.String: + break + case f.Kind() == reflect.Int: + seconds := data.(int) + + duration = time.Second * time.Duration(seconds) + case f.Kind() == reflect.Int32: + seconds := data.(int32) + + duration = time.Second * time.Duration(seconds) + case f == typeTimeDuration: + duration = data.(time.Duration) + case f.Kind() == reflect.Int64: + seconds := data.(int64) + + duration = time.Second * time.Duration(seconds) + } + + if duration == 0 { + dataStr := data.(string) + + if duration, err = utils.ParseDurationString(dataStr); err != nil { + return nil, err + } + } + + if ptr { + return &duration, nil + } + + return duration, nil + } +} |
