aboutsummaryrefslogtreecommitdiff
path: root/conf/conf.go
diff options
context:
space:
mode:
Diffstat (limited to 'conf/conf.go')
-rw-r--r--conf/conf.go63
1 files changed, 56 insertions, 7 deletions
diff --git a/conf/conf.go b/conf/conf.go
index 26a5d90..6cf0d99 100644
--- a/conf/conf.go
+++ b/conf/conf.go
@@ -19,9 +19,60 @@ package conf
import (
"github.com/spf13/viper"
+ "golang.org/x/crypto/bcrypt"
"log"
)
+func validateConf() {
+ ok := true
+ log.Println("\x1b[46m\x1b[30m[info]\x1b[0m Checking errors in config file...")
+
+ port := viper.GetInt("port")
+ if port < 1024 || port > 65535 {
+ log.Println("\x1b[41m\x1b[30m[err]\x1b[0m Invalid port number.")
+ ok = false
+ }
+
+ if viper.GetInt("username.min_username_length") < 1 {
+ log.Println("\x1b[41m\x1b[30m[err]\x1b[0m Minimum username length must be greater than 0.")
+ ok = false
+ }
+
+ minPassLen := viper.GetInt("security.min_password_length")
+ maxPassLen := viper.GetInt("security.max_password_length")
+
+ if minPassLen < 1 {
+ log.Println("\x1b[41m\x1b[30m[err]\x1b[0m Minimum password length must be greater than 0.")
+ ok = false
+ }
+
+ if maxPassLen > 72 {
+ log.Println("\x1b[41m\x1b[30m[err]\x1b[0m Maximum password length can't exceed 72 characters.")
+ ok = false
+ }
+
+ if minPassLen > maxPassLen {
+ log.Println("\x1b[41m\x1b[30m[err]\x1b[0m Minimum password length can't be greater than maximum password length.")
+ ok = false
+ }
+
+ hashingCost := viper.GetInt("cryptography.password_hashing_cost")
+
+ if hashingCost > bcrypt.MaxCost {
+ log.Printf("\x1b[41m\x1b[30m[err]\x1b[0m Password hashing cost can't be greater than %d.\n", bcrypt.MaxCost)
+ ok = false
+ }
+
+ if hashingCost < bcrypt.MinCost {
+ log.Printf("\x1b[41m\x1b[30m[err]\x1b[0m Password hashing cost can't be less than %d.\n", bcrypt.MinCost)
+ ok = false
+ }
+
+ if !ok {
+ log.Fatalln("\x1b[41m\x1b[30m[err]\x1b[0m Config file has errors.")
+ }
+}
+
// TODO: validate config
func init() {
viper.SetConfigName("openbills")
@@ -29,11 +80,8 @@ func init() {
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
- if _, ok := err.(viper.ConfigFileNotFoundError); ok {
- log.Printf("\x1b[43m\x1b[30m[warn]\x1b[0m config file not found, skipping...\n")
- } else {
- log.Fatalf("\x1b[41m\x1b[30m[err]\x1b[0m cannot read config file. %v\n", err.Error())
- }
+ log.Printf("\x1b[41m\x1b[30m[err]\x1b[0m Failed to read config file:\n")
+ log.Fatalf("%v\n", err.Error())
}
viper.SetDefault("port", "8765")
@@ -51,7 +99,8 @@ func init() {
viper.SetDefault("username.min_username_length", 2)
viper.SetDefault("username.max_username_length", 20)
- viper.SetDefault("cryptography.password_hashing_cost", 14)
+ viper.SetDefault("cryptography.password_hashing_cost", bcrypt.DefaultCost)
- log.Printf("\x1b[46m\x1b[30m[info]\x1b[0m Loaded Config File \"%s\"\n", viper.ConfigFileUsed())
+ validateConf()
+ log.Printf("\x1b[46m\x1b[30m[info]\x1b[0m Loaded Config \"%s\"\n", viper.ConfigFileUsed())
}