103 lines
2.6 KiB
Go
103 lines
2.6 KiB
Go
package validatedprofile
|
|
|
|
import (
|
|
"cmp"
|
|
"slices"
|
|
"time"
|
|
|
|
"git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
|
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
|
"github.com/go-viper/mapstructure/v2"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/viper"
|
|
"github.com/stretchr/objx"
|
|
)
|
|
|
|
type Comparison struct {
|
|
Field string
|
|
Type string
|
|
Value any
|
|
}
|
|
|
|
func ValidateProfile(cfg *viper.Viper) func(mobilityaccountsstorage.Account, []storage.FileInfo) bool {
|
|
enabled := cfg.GetBool("enabled")
|
|
requiredDocuments := cfg.GetStringSlice("required.documents")
|
|
requiredFields := cfg.GetStringSlice("required.fields")
|
|
comp := cfg.Get("assert.compare")
|
|
var comparisons []Comparison
|
|
err := mapstructure.Decode(comp, &comparisons)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("reading comparisons issue")
|
|
}
|
|
return func(account mobilityaccountsstorage.Account, docs []storage.FileInfo) bool {
|
|
if !enabled {
|
|
return true
|
|
}
|
|
|
|
for _, d := range requiredDocuments {
|
|
if !slices.ContainsFunc(docs, func(f storage.FileInfo) bool {
|
|
log.Debug().Str("required", d).Str("checked", f.Metadata["Type"]).Msg("file check")
|
|
return f.Metadata["Type"] == d
|
|
}) {
|
|
log.Debug().Msg("file missing")
|
|
return false
|
|
}
|
|
}
|
|
|
|
obj := objx.Map(account.Data)
|
|
|
|
for _, f := range requiredFields {
|
|
if obj.Get(f) == nil {
|
|
log.Debug().Msg("field missing")
|
|
return false
|
|
}
|
|
}
|
|
|
|
for _, c := range comparisons {
|
|
val := obj.Get(c.Field)
|
|
if val == nil {
|
|
return false
|
|
}
|
|
value := ""
|
|
if v, ok := c.Value.(string); ok {
|
|
value = v
|
|
} else if v, ok := c.Value.(time.Time); ok {
|
|
value = v.Format("2006-01-02")
|
|
} else {
|
|
log.Error().Msg("could not get type")
|
|
return false
|
|
}
|
|
result := cmp.Compare(val.String(), value)
|
|
|
|
if c.Type == "gte" {
|
|
if result < 0 {
|
|
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
|
return false
|
|
}
|
|
} else if c.Type == "gt" {
|
|
if result <= 0 {
|
|
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
|
return false
|
|
}
|
|
} else if c.Type == "lt" {
|
|
if result >= 0 {
|
|
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
|
return false
|
|
}
|
|
} else if c.Type == "lte" {
|
|
if result < 0 {
|
|
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
|
return false
|
|
}
|
|
} else if c.Type == "eq" {
|
|
if result != 0 {
|
|
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
}
|