package db import ( "log" "github.com/spf13/viper" "gorm.io/gorm" "git.jmbit.de/jmb/goipam/utils" ) // SetupDB checks if database has already been initialized and users exist, otherwise creates default users func SetupDB() { ConnectDB() var users []User var count int64 var err error var adminPW string conn.Find(&users).Count(&count) if count >= 1 { return } if viper.GetString("web.adminpw") != "" { adminPW = viper.GetString("web.adminpw") } else { adminPW, err = utils.RandomString(32) } if err != nil { log.Fatalf("Could not generate admin PW: %v", err) } else { log.Println("Admin PW is:", adminPW) } adminPWHash, err := utils.HashPassword(adminPW) if err != nil { log.Fatalf("Could not generate admin PW: %v", err) } else { log.Println("Hashed Admin PW", adminPWHash) } adminUser := User{ Model: gorm.Model{}, Name: "admin", PassHash: adminPWHash, Email: "admin@example.com", DisplayName: "Administrator", Admin: true, } result := conn.Create(&adminUser) if result.Error != nil { log.Println(err) } result = nil result = conn.Create(&Location{ Name: "Example", Comment: "This is an example Location", Subnets: []Subnet{ { Name: "VLAN1337", DisplayName: "Example Subnet", IPv4Net: "1.3.3.7/32", IPv6Net: "dead:beef:ca1f/64", }, }, }) if result.Error != nil { log.Println(err) } }